code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
{% comment %}
<!--
Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
Created on 2010-02-08.
$Id$
-->
{% endcomment %}
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>{% block html_title %}{% endblock %} :: {{ site_name_|escape }}</title>
<link rel="shortcut icon" type="image/ico" href="/favicon.ico"/>
<!-- jQuery, jQuery UI, Google Maps API (via Google Javascript API) -->
<script src="http://www.google.com/jsapi?key={{ google_ajax_api_key_ }}" type="text/javascript"></script>
<script type="text/javascript">//<![CDATA[
google.load("jquery", "1.4.2");
google.load("jqueryui", "1.8.0");
google.load("maps", "2");
//]]></script>
<!-- jQuery UI flick theme -->
<link rel="stylesheet" type="text/css" media="screen,print" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/flick/jquery-ui.css"/>
<!-- Website specific javascript library -->
<script src="{{ static_ }}/js/friday.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" media="screen,print" href="{{ static_ }}/css/layout.css"/>
<link rel="stylesheet" type="text/css" media="screen,print" href="{{ static_ }}/css/common.css"/>
<link rel="stylesheet" type="text/css" media="screen,print" href="{{ static_ }}/css/form.css"/>
<link rel="stylesheet" type="text/css" media="screen,print" href="{{ static_ }}/css/table.css"/>
<link rel="stylesheet" type="text/css" media="screen,print" href="{{ static_ }}/css/user.css"/>
{% block html_head %}{% endblock %}
<!-- Google Analytics async-tracking code -->
<script type="text/javascript">//<![CDATA[
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-356705-9']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//]]></script>
</head>
<body>
{% block html_body %}
<div id="outer-wrapper">
{% block no_ie %}
{% ifequal browser_.id "MSIE" %}
<div id="no-ie-wrapper">
<b>Attention:</b>
<a href="{% url friday.about topic='browser' %}">bad browser detected!</a>
</div>
{% endifequal %}
{% endblock %}
<!-- topbar-wrapper ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<div id="topbar-wrapper">
{% block topbar %}
<div class="topbar-logo">
<a href="{% url friday.home %}">
<img src="{{ static_ }}/images/logo.gif" alt="{{ site_name_|escape|default:'logo' }}"/>
</a>
</div>
<div class="topbar-text">
{% if user_ %}
<a href="{% url friday.view_profile username=user_.username %}"><b>{{ user_|escape }}</b></a>
• <a href="{{ logout_url_ }}">Logout</a>
{% else %}
<a href="{{ login_url_ }}">Login</a>
{% endif %}
• <a href="{% url friday.home %}">Home</a>
• <a href="{% url friday.about %}">About</a>
</div>
<div class="clear"></div>
{% endblock %}
</div><!--/#topbar-wrapper-->
<!-- navbar-wrapper ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<div id="navbar-wrapper">
{% block navbar %}
<div class="menutabs">
<a href="{% url friday.groups_home %}">Groups</a>
<a href="{% url friday.restos_home %}">Restos</a>
</div>
{% endblock %}
</div><!--/#navbar-wrapper-->
<!-- navbar-wrapper ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<div id="banner-wrapper">
{% block banner %}{% endblock %}
</div>
<!-- main-wrapper ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<div id="main-wrapper">
{% block main %}
<div id="content-wrapper">
{% block content %}FIXME: content block is required!{% endblock %}
</div>
<div id="sidebar-wrapper">
{% block sidebar %}{% endblock %}
</div>
<div class="clear"></div>
{% endblock %}{# main #}
</div><!--/#main-wrapper-->
<!-- footer-wrapper ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<div id="footer-wrapper">
{% block footer %}
<div class="footer-left">
<a href="{% url friday.home %}">{{ site_name_|escape }}</a>
•
<a href="{% url friday.about topic='versions' %}">Version {{ website_version_|escape }}</a>
<br/>
Built and maintained by <a href="http://www.zhengzhong.net/">ZHENG Zhong</a>
</div>
<div class="footer-right">
<a href="http://appengine.google.com/" rel="external">Google App Engine</a>
•
<a href="http://www.python.org/" rel="external">Python {{ python_version_|escape }}</a>
•
<a href="http://www.djangoproject.com/" rel="external">Django {{ django_version_|escape }}</a>
•
<a href="http://jquery.com/" rel="external">jQuery</a>
<br/>
<a href="http://validator.w3.org/check?uri=referer" rel="external">Valid XHTML</a>
•
<a href="http://jigsaw.w3.org/css-validator/check/referer" rel="external">Valid CSS</a>
</div>
<div class="clear"></div>
{% endblock %}
</div><!--/#footer-wrapper-->
</div><!--/#outer-wrapper-->
{% endblock %}{# html_body #}
</body>
</html>
| zzheng | friday/website/friday/templates/base.html | HTML | asf20 | 6,504 |
{% extends "profiles/base.html" %}
{% comment %}
<!--
Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
Created on 2010-02-19.
$Id$
-->
{% endcomment %}
{% load friday_extra %}
{#________________________________________________________________________________________________#}
{% block html_title %} Choose an avatar image for {{ user|escape }} {% endblock %}
{#________________________________________________________________________________________________#}
{% block content %}
{% if avatar_form %}
<div class="section">
<h1>Choose your avatar image ...</h1>
</div>
<div class="section">
<form id="avatar-form" class="xl-form" action="." method="POST">
<div class="field">
<div class="label">Where should we take your avatar image: *</div>
<div id="avatar-source" class="input required">{{ avatar_form.avatar_source|safe }}</div>
<div class="error-list">{{ avatar_form.avatar_source.errors|safe }}</div>
</div>
<div id="gravatar" class="avatar field hidden">
<div class="label">Your avatar image from <a href="http://www.gravatar.com/">gravatar.com</a>:</div>
<div class="input"><img src="{{ profile.email|gravatar }}" alt="gravatar"/></div>
<div class="help-text">If you do not have a gravatar image, a random avatar image will be used.</div>
</div>
<div id="image_url" class="avatar field hidden">
<div class="label">Your avatar image URL:</div>
<div class="input required">{{ avatar_form.avatar_url|safe }}</div>
<div class="help-text">Please make sure your avatar image on the web is publicly available.</div>
<div class="error-list">{{ avatar_form.avatar_url.errors|safe }}</div>
</div>
<div class="field">
<input class="button" type="submit" value="Update avatar image"/>
or,
<a href="{% url friday.view_profile username=user_.username %}">return to your profile</a>
</div>
</form><!--/#avatar-form-->
<script type="text/javascript">//<![CDATA[
$(function() {
var avatar_field_id = "#" + $("#avatar-form #avatar-source :input").val();
$("#avatar-form .avatar").hide();
$("#avatar-form " + avatar_field_id).show();
$("#avatar-form #avatar-source :input").change(function() {
$("#avatar-form .avatar").hide();
var avatar_field_id = "#" + $(this).val();
$("#avatar-form " + avatar_field_id).show();
});
});
//]]></script>
</div>
{% endif %}{# profile_form #}
{% endblock %}{# content #}
| zzheng | friday/website/friday/templates/profiles/edit_avatar.html | HTML | asf20 | 2,797 |
{% extends "profiles/base.html" %}
{% comment %}
<!--
Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
Created on 2010-02-10.
$Id$
-->
{% endcomment %}
{% load friday_extra %}
{#________________________________________________________________________________________________#}
{% block html_title %} {{ user|escape }} {% endblock %}
{#________________________________________________________________________________________________#}
{% block sidebar %}
{% if profile %}
<div class="section">
<h2>About {{ user|escape }}:</h2>
<dl>
<dt>
<img class="icon" src="{{ static_ }}/images/email.png" alt="Email"/>
Email:
</dt>
<dd>
{{ user.email|safe_email }}
{% if profile.alt_email %}
<br/>
{{ profile.alt_email|safe_email }} (alt.)
{% endif %}
</dd>
</dl>
{% if profile.tel %}
<dl>
<dt>
<img class="icon" src="{{ static_ }}/images/tel.png" alt="Telephone"/>
Telephone:
</dt>
<dd>{{ profile.tel }}</dd>
</dl>
{% endif %}
{% if profile.website %}
<dl>
<dt>
<img class="icon" src="{{ static_ }}/images/website.png" alt="Website"/>
Website:
</dt>
<dd><a href="{{ profile.website }}">{{ profile.website|summary:32 }}</a></dd>
</dl>
{% endif %}
</div>
{% endif %}
{% ifequal user_ user %}
<div class="section">
{% if not profile %}
<h2><a href="{% url friday.edit_profile username=user.username %}">Create your profile</a></h2>
{% else %}
<h2>Edit your profile:</h2>
<ul>
<li><a href="{% url friday.edit_profile username=user.username %}">Basic information</a></li>
<li><a href="{% url friday.edit_avatar username=user.username %}">Avatar image</a></li>
</ul>
{% endif %}
</div>
{% endifequal %}
{% endblock %}
{#________________________________________________________________________________________________#}
{% block content %}
<div class="section">
{% if not profile %}
<p class="aux">This user doest not have a profile yet.</p>
{% else %}
{% if profile.biography %}
{{ profile.biography|escape|linebreaks }}
{% else %}
<p class="aux">This user does not have a biography.</p>
{% endif %}
{% endif %}
</div>
{% endblock %}
| zzheng | friday/website/friday/templates/profiles/view_profile.html | HTML | asf20 | 2,582 |
{% extends "profiles/base.html" %}
{% comment %}
<!--
Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
Created on 2010-02-19.
$Id$
-->
{% endcomment %}
{#________________________________________________________________________________________________#}
{% block html_title %} Edit profile of {{ user|escape }} {% endblock %}
{#________________________________________________________________________________________________#}
{% block content %}
{% if profile_form %}
<div class="section">
<h1>
{% if not profile %}
Create your profile ....
{% else %}
Edit your basic information ...
{% endif %}
</h1>
</div>
<div class="section">
<form id="profile-form" class="xl-form" action="." method="POST">
<div class="field">
<div class="label">Your email address:</div>
<div class="disabled-value">{{ user.email|escape }}</div>
</div>
<div class="field">
<div class="label">Your name: *</div>
<div class="input required">{{ profile_form.name|safe }}</div>
{% if profile_form.name.errors %}
<div class="error-list">{{ profile_form.name.errors|safe }}</div>
{% endif %}
</div>
<div class="field">
<div class="label">Alternative Email address:</div>
<div class="input">{{ profile_form.alt_email|safe }}</div>
{% if profile_form.alt_email.errors %}
<div class="error-list">{{ profile_form.alt_email.errors|safe }}</div>
{% endif %}
</div>
<div class="field">
<div class="label">Your phone number:</div>
<div class="input">{{ profile_form.tel|safe }}</div>
{% if profile_form.tel.errors %}
<div class="error-list">{{ profile_form.tel.errors|safe }}</div>
{% endif %}
</div>
<div class="field">
<div class="label">Write something about yourself:</div>
<div class="input">{{ profile_form.biography|safe }}</div>
{% if profile_form.biography.errors %}
<div class="error-list">{{ profile_form.biography.errors|safe }}</div>
{% endif %}
</div>
<div class="field">
<div class="label">Your personal website:</div>
<div class="input">{{ profile_form.website|safe }}</div>
{% if profile_form.website.errors %}
<div class="error-list">{{ profile_form.website.errors|safe }}</div>
{% endif %}
</div>
<div class="field">
<input class="button" type="submit" value="Submit"/>
or,
<a href="{% url friday.view_profile username=user_.username %}">return to your profile</a>
</div>
</form><!--/#profile-form-->
</div>
{% endif %}
{% endblock %}
| zzheng | friday/website/friday/templates/profiles/edit_profile.html | HTML | asf20 | 2,960 |
{% extends "base.html" %}
{% comment %}
<!--
Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
Created on 2010-02-18.
$Id$
-->
{% endcomment %}
{% load friday_extra %}
{% block banner %}
<div class="simple">
<div class="banner-text">
<img class="icon" src="{% url friday.view_avatar username=user.username %}" alt="{{ user|escape }}"/>
<h1>
<a href="{% url friday.view_profile username=user.username %}">
{% if profile %}
{{ profile|escape }}
{% else %}
{{ user|escape }}
{% endif %}
</a>
</h1>
<div class="links">
<a href="{% url friday.view_profile username=user.username %}">Profile</a>
{% if profile and profile.website %}
• <a href="{{ profile.website }}">Website</a>
{% endif %}
• Joined on {{ user.join_date|date:"d N Y" }}
</div>
<div class="clear"></div>
</div>
</div>
{% endblock %}
| zzheng | friday/website/friday/templates/profiles/base.html | HTML | asf20 | 1,026 |
{% extends "base.html" %}
{% comment %}
<!--
Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
Created on 2010-05-21.
$Id$
-->
{% endcomment %}
{#________________________________________________________________________________________________#}
{% block html_title %} Cron Jobs {% endblock %}
{#________________________________________________________________________________________________#}
{% block content %}
<div class="section">
<h1>Cron Jobs</h1>
</div>
{% endblock %}
| zzheng | friday/website/friday/templates/cronjobs/home.html | HTML | asf20 | 533 |
{% extends "base.html" %}
{% comment %}
<!--
Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
Created on 2010-05-21.
$Id$
-->
{% endcomment %}
{#________________________________________________________________________________________________#}
{% block html_title %} Cron Job: {{ job_title|escape }} {% endblock %}
{#________________________________________________________________________________________________#}
{% block main %}
<div class="section">
<h1>Cron Job: {{ job_title|escape }}</h1>
</div>
{% if prompt %}
<div class="section">
<div class="{{ prompt.severity }}-prompt">
<img class="icon" src="{{ static_ }}/images/{{ prompt.severity }}.png" alt="{{ prompt.severity }}"/>
{{ prompt|escape }}
</div>
</div>
{% endif %}
{% if job_description %}
<div class="section">
<h2>Job Description:</h2>
{{ job_description|escape|linebreaks }}
</div>
{% endif %}
<div class="section">
<form class="xl-form" action="." method="GET">
<input type="hidden" name="cron_" value="true"/>
<div class="field">
<input class="button" type="submit" value="Launch this job manually"/>
</div>
</form>
</div>
{% endblock %}
| zzheng | friday/website/friday/templates/cronjobs/cron_job.html | HTML | asf20 | 1,297 |
{% comment %}
<!--
Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
Created on 2010-02-08.
$Id$
-->
{% endcomment %}
{% if prompt %}
<div id="{{ prompt.id }}" class="hidden">
<img src="{{ static_ }}/images/{{ prompt.severity }}.png" alt="{{ prompt.severity }}"/>
{{ prompt|escape }}
</div><!--/#{{ prompt.id }}-->
<script type="text/javascript">//<![CDATA[
$(function() {
$("#{{ prompt.id }}").dialog({
bgiframe: true,
title: "{{ prompt.severity }}",
modal: true,
buttons: {
OK: function() {
$(this).dialog("close");
}
},
minHeight: 80,
minWidth: 540,
width: 540
});
});
//]]></script>
{% endif %}
| zzheng | friday/website/friday/templates/include/prompt.html | HTML | asf20 | 785 |
{% comment %}
<!--
Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
Created on 2010-02-08.
$Id$
-->
{% endcomment %}
{% if ajax_prompt %}
<div id="ajax-{{ ajax_prompt.id }}" class="hidden">
<img src="{{ static_ }}/images/{{ ajax_prompt.severity }}.png" alt="{{ ajax_prompt.severity }}"/>
{{ ajax_prompt|escape }}
</div><!--/#ajax-{{ ajax_prompt.id }}-->
<script type="text/javascript">//<![CDATA[
$(function() {
$("#ajax-{{ ajax_prompt.id }}").dialog({
bgiframe: true,
title: "AJAX {{ ajax_prompt.severity }}",
modal: true,
buttons: {
OK: function() {
$(this).dialog("close");
}
},
minHeight: 80,
minWidth: 540,
width: 540
});
});
//]]></script>
{% endif %}{# ajax_prompt #}
| zzheng | friday/website/friday/templates/include/ajax_prompt.html | HTML | asf20 | 862 |
{% extends "base.html" %}
{% comment %}
<!--
Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
Created on 2010-05-06.
$Id$
-->
{% endcomment %}
{#________________________________________________________________________________________________#}
{% block html_title %} Code Viewer {% endblock %}
{#________________________________________________________________________________________________#}
{% block html_head %}
<!-- Google Code Prettify -->
<link rel="stylesheet" type="text/css" media="screen,print" href="{{ static_ }}/css/prettify.css"/>
<style type="text/css"><!--
/* Override Google Code Prettify style. */
pre.prettyprint {
margin: 4px 0 4px 0;
padding: 4px;
}
--></style>
<script src="{{ static_ }}/js/prettify.js" type="text/javascript"></script>
{% endblock %}
{#________________________________________________________________________________________________#}
{% block main %}
<!-- path ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<div class="section">
<h1>
<a href="{% url friday.view_code path='' %}">Code Viewer:</a>
{% for parent in entry.parents %}
<a href="{% url friday.view_code path=parent.path %}">{{ parent.name|escape }}</a> /
{% endfor %}
{{ entry.name|escape }} {{ entry.is_dir|yesno:"/," }}
</h1>
{% if not entry.exists %}
<p class="code">
<img class="icon" src="{{ static_ }}/images/error.png" alt="Error"/>
This file does not exist.
</p>
{% endif %}
{% if entry.is_file %}
<p class="code">
<img class="icon" src="{{ static_ }}/images/download.png" alt="Download"/>
<a href="?download=true">download this file</a>
</p>
{% endif %}
</div>
<!-- children ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
{% if entry.children %}
<div class="section">
<table class="table">
<thead>
<tr>
<th><span class="nowrap">Name</span></th>
<th><span class="nowrap">Mimetype</span></th>
<th><span class="nowrap">Size (bytes)</span></th>
</tr>
</thead>
<tbody>
{% for child in entry.children %}
<tr>
<td>
<span class="nowrap">
{% if child.is_dir or child.is_file %}
{% if child.is_dir %}
<img class="icon" src="{{ static_ }}/images/folder.png" alt="Directory"/>
{% else %}
<img class="icon" src="{{ static_ }}/images/file.png" alt="File"/>
{% endif %}
{% else %}
<img class="icon" src="{{ static_ }}/images/error.png" alt="Unknown"/>
{% endif %}
<code>
<a href="{% url friday.view_code path=child.path %}">{{ child.name|escape }}</a>
</code>
</span>
</td>
<td>
{% if child.mimetype %}
<code class="nowrap">{{ child.mimetype|escape }}</code>
{% else %}
<code class="na nowrap">N/A</code>
{% endif %}
</td>
<td><code class="nowrap">{{ child.size|default_if_none:"N/A" }}</code></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
<!-- text content ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
{% if entry.is_text_file %}
<div class="section">
<pre class="prettyprint">{{ entry.content|escape }}</pre>
<script type="text/javascript">//<![CDATA[
$(function() {
prettyPrint();
});
//]]></script>
</div>
{% endif %}
{% endblock %}
| zzheng | friday/website/friday/templates/codeviewer/view_code.html | HTML | asf20 | 4,020 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-02-08.
# $Id$
#
__version__ = "1.0.00"
def get_version():
"""
Returns the website version number.
"""
return __version__
# EOF
| zzheng | friday/website/friday/__init__.py | Python | asf20 | 296 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-02-08.
# $Id$
#
import logging
from django.http import HttpRequest, HttpResponse, Http404
from django.template import RequestContext
from django.shortcuts import render_to_response
class DummyMiddleware(object):
def __init__(self):
"""Most middleware classes won't need an initializer since middleware classes are
essentially placeholders for the process_* methods. If you do need some global state you
may use __init__ to set up. However, keep in mind a couple of caveats:
* Django initializes your middleware without any arguments, so you can't define __init__
as requiring any arguments.
* Unlike the process_* methods which get called once per request, __init__ gets called
only once, when the web server starts up.
"""
pass
def process_request(self, request):
"""This function is called on each request, before Django decides which view to execute.
This function should return either None or an HttpResponse object. If it returns None,
Django will continue processing this request, executing any other middleware and, then,
the appropriate view. If it returns an HttpResponse object, Django won't bother calling
ANY other request, view or exception middleware, or the appropriate view; it'll return that
HttpResponse. Response middleware is always called on every response.
"""
return None
def process_view(self, request, view_func, view_args, view_kwargs):
"""This function is called just before Django calls the view. It should return either None
or an HttpResponse object. If it returns None, Django will continue processing this
request, executing any other process_view() middleware and, then, the appropriate view.
If it returns an HttpResponse object, Django won't bother calling ANY other request, view
or exception middleware, or the appropriate view; it'll return that HttpResponse. Response
middleware is always called on every response.
"""
return None
def process_response(self, request, response):
"""This function should return an HttpResponse object. It could alter the given response,
or it could create and return a brand-new HttpResponse.
"""
return response
def process_exception(self, request, exception):
"""This function is called when a view raises an exception. This function should return
either None or an HttpResponse object. If it returns an HttpResponse object, the response
will be returned to the browser. Otherwise, default exception handling kicks in.
"""
return None
class RenderErrorMiddleware(object):
ERROR_TEMPLATE = "error.html"
def process_exception(self, request, exception):
logging.error("Error occurred: %s - %s" % (type(exception), exception))
if not isinstance(exception, Http404):
logging.exception(exception)
try:
data = {"error": exception}
response = render_to_response(self.ERROR_TEMPLATE, data, RequestContext(request))
response.status_code = 500 # server error.
return response
except Exception, exc:
logging.error("Failed to render error page: %s" % exc)
logging.exception(exc)
return None
# EOF
| zzheng | friday/website/friday/common/middlewares.py | Python | asf20 | 3,617 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-04-14.
# $Id$
#
import re
__all__ = ("Browser",)
_BROWSERS = (
# Opera likes to pretend to be some other browser, so detect it first.
(re.compile(r"(?P<id>Opera)[/\s](?P<version>[\w\.\-]+)"), "Opera"),
(re.compile(r"(?P<id>MSIE)\s(?P<version>[\w\.\-]+)"), "Microsoft Internet Explorer"),
(re.compile(r"(?P<id>Firefox)/(?P<version>[\w\.\-]+)"), "Mozilla Firefox"),
(re.compile(r"(?P<id>Chrome)/(?P<version>[\w\.\-]+)"), "Google Chrome"),
(re.compile(r"(?P<id>Safari)/(?P<version>[\w\.\-]+)"), "Safari"),
)
def _parse_browser(user_agent):
user_agent = user_agent or ""
for expr, browser_name in _BROWSERS:
match = expr.search(user_agent)
if match:
return (match.group("id"), browser_name, match.group("version"))
return (None, None, None)
def _parse_platform(user_agent):
user_agent = user_agent or ""
expr = re.compile(r"(?P<platform>Windows|Linux|Mac\sOS\sX|FreeBSD|OpenBSD)")
match = expr.search(user_agent)
if match:
return match.group("platform")
else:
return None
class Browser(object):
def __init__(self, user_agent):
self.user_agent = user_agent or None
self.id, self.name, self.version = _parse_browser(user_agent)
self.platform = _parse_platform(user_agent)
def __str__(self):
return "%s %s (%s)" % (self.name, self.version, self.platform)
def __unicode__(self):
return u"%s %s (%s)" % (self.name, self.version, self.platform)
# EOF
| zzheng | friday/website/friday/common/browsers.py | Python | asf20 | 1,698 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-02-08.
# $Id$
#
from django import forms
from google.appengine.ext import db
class GeoPtField(forms.Field):
def __init__(self, *args, **kwargs):
super(GeoPtField, self).__init__(*args, **kwargs)
def clean(self, value):
"""
Returns a db.GeoPt object for valid values, and None for empty values.
"""
super(GeoPtField, self).clean(value)
if not self.required and not value:
return None
try:
geo_pt = value.split(",")
if len(geo_pt) != 2:
raise forms.ValidationError(self.error_messages["invalid"])
lat = float(geo_pt[0])
lon = float(geo_pt[1])
value = db.GeoPt(lat=lat, lon=lon)
except (TypeError, ValueError):
raise forms.ValidationError(self.error_messages["invalid"])
return value
# EOF
| zzheng | friday/website/friday/common/fields.py | Python | asf20 | 1,038 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-02-09.
# $Id$
#
import datetime
from platform import python_version
from django import get_version as django_version
from django.conf import settings
from django.http import HttpRequest
from friday import get_version as website_version
from friday.auth import users
from friday.common.browsers import Browser
_GOOGLE_AJAX_API_KEYS = {
"www.zhengzhong.net": "ABQIAAAA6SC56e9JfGUas7BsUDqyuBQTYCh4nfnZskh9tX3CKbKESYY0QBQRDfWUx_P2DPVUCiFC7DmMx_qv6A",
"www.vivelevendredi.com": "ABQIAAAA6SC56e9JfGUas7BsUDqyuBRacFmEPTJzb4yjspz2bxZUGH0cJxRPO3jA05G-_oS_gOABChUa1kNrxQ",
"vive-le-vendredi.appspot.com": "ABQIAAAA6SC56e9JfGUas7BsUDqyuBTWewClXGnxECXWTdo1Pd4Yqcf9URTwPTM4ilvh_nm6-VvgEF2IQ7A-fg",
}
def common_data_processor(request):
server_name = request.META.get("SERVER_NAME")
google_ajax_api_key = _GOOGLE_AJAX_API_KEYS.get(server_name, "")
return {
"site_name_": getattr(settings, "MY_SITE_NAME", None),
"static_": getattr(settings, "MY_STATIC_URL_PREFIX", ""),
"browser_": Browser(request.META.get("HTTP_USER_AGENT")),
"server_name_": server_name,
"google_ajax_api_key_": google_ajax_api_key,
"today_": datetime.date.today(),
}
def current_user_processor(request):
user = users.get_current_user(request)
if not user:
login_url = users.create_login_url(request.path)
logout_url = None
else:
login_url = None
logout_url = users.create_logout_url(request.path)
return {
"user_": user,
"user_ip_": request.META["REMOTE_ADDR"],
"login_url_": login_url,
"logout_url_": logout_url,
"is_webmaster_": users.is_webmaster(user),
}
def powered_by_processor(request):
return {
"website_version_": website_version(),
"python_version_": python_version(),
"django_version_": django_version(),
}
# EOF
| zzheng | friday/website/friday/common/context_processors.py | Python | asf20 | 2,088 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-02-08.
# $Id$
#
import urllib
from django.http import HttpRequest
class Prompt(object):
INFO = "info"
ERROR = "error"
def __init__(self, **kwargs):
self.severity = None
self.message = None
if kwargs.get("request"):
request_dict = kwargs["request"].REQUEST
else:
request_dict = kwargs
if request_dict.get(Prompt.ERROR):
self.severity = Prompt.ERROR
self.message = request_dict[Prompt.ERROR]
elif request_dict.get(Prompt.INFO):
self.severity = Prompt.INFO
self.message = request_dict[Prompt.INFO]
def __nonzero__(self):
return bool(self.message)
def __str__(self):
return str(self.message)
def __unicode__(self):
return unicode(self.message)
@property
def id(self):
return "prompt-%s-%d" % (self.severity, abs(hash(self.message)))
def as_dict(self):
if self.severity and self.message:
return {self.severity: self.message}
else:
return {}
def urlencode(self):
return urllib.urlencode(self.as_dict())
# EOF
| zzheng | friday/website/friday/common/prompt.py | Python | asf20 | 1,340 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-02-08.
# $Id$
#
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from friday.auth import users
from friday.common.errors import ProgrammingError, BadRequestError
__all__ = ("Action", "WebmasterAction",)
class Action(object):
PAGE_URL_NAME = None
PAGE_TEMPLATE = None
AJAX_URL_NAME = None
AJAX_TEMPLATE = None
def __init__(self, request):
self._request = request
@property
def name(self):
return self.__class__.__name__
@property
def request(self):
return self._request
def get_page_template(self):
return self.PAGE_TEMPLATE
def get_ajax_template(self):
return self.AJAX_TEMPLATE
@property
def current_user(self):
return users.get_current_user(self.request)
def process(self):
is_ajax = self.request.is_ajax() or (self.request.REQUEST.get("ajax") == "ajax")
if is_ajax:
return self.process_ajax()
else:
return self.process_page()
def process_ajax(self):
if self.request.method == "GET":
data = self.get_ajax()
elif self.request.method == "POST":
data = self.post_ajax()
else:
message = "%s does not support AJAX %s request." % (self.name, self.request.method)
raise BadRequestError(self.request, message)
data = self.update_data(data)
return render_to_response(self.get_ajax_template(), data, RequestContext(self.request))
def process_page(self):
if self.request.method == "GET":
return self.get_page()
elif self.request.method == "POST":
return self.post_page()
else:
message = "%s does not support %s request." % (self.name, self.request.method)
raise BadRequestError(self.request, message)
def update_data(self, data):
return data
def get_page(self):
message = "%s does not support GET request." % self.name
raise BadRequestError(self.request, message)
def post_page(self):
message = "%s does not support POST request." % self.name
raise BadRequestError(self.request, message)
def get_ajax(self):
message = "%s does not support AJAX GET request." % self.name
raise BadRequestError(self.request, message)
def post_ajax(self):
message = "%s does not support AJAX POST request." % self.name
raise BadRequestError(self.request, message)
@classmethod
def get_page_url(cls, **kwargs):
if not cls.PAGE_URL_NAME:
message = "Failed to get page URL for %s: PAGE_URL_NAME not defined." % cls.__name__
raise ProgrammingError(message)
return reverse(cls.PAGE_URL_NAME, kwargs=kwargs)
@classmethod
def get_ajax_url(cls, **kwargs):
if not cls.AJAX_URL_NAME:
message = "Failed to get AJAX URL for %s: AJAX_URL_NAME not defined." % cls.__name__
raise ProgrammingError(message)
return reverse(cls.AJAX_URL_NAME, kwargs=kwargs)
class WebmasterAction(Action):
def process(self):
if not users.is_webmaster(self.current_user):
message = "The action '%s' is restricted to webmasters." % self.name
raise BadRequestError(self.request, message)
else:
return super(WebmasterAction, self).process()
# EOF
| zzheng | friday/website/friday/common/actions.py | Python | asf20 | 3,779 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2009-10-29.
# $Id$
#
| zzheng | friday/website/friday/common/__init__.py | Python | asf20 | 150 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2009-10-29.
# $Id$
#
__all__ = ("Error", "ProgrammingError", "BadRequestError", "InvalidFormError",)
class Error(Exception): pass
class ProgrammingError(Error): pass
class EntityNotFoundError(Error):
def __init__(self, model_class, searched_by):
message = u"%s not found: %s" % (model_class.__name__, searched_by)
super(EntityNotFoundError, self).__init__(message)
class InvalidFormError(Error):
def __init__(self, errors):
bad_fields = u", ".join(errors.keys())
message = u"Invalid value(s) in field(s): %s." % bad_fields
super(InvalidFormError, self).__init__(message)
class BadRequestError(Error):
def __init__(self, request, message):
super(BadRequestError, self).__init__(message)
self._path = request.path
self._method = request.method
@property
def path(self):
return self._path
@property
def method(self):
return self._method
# EOF
| zzheng | friday/website/friday/common/errors.py | Python | asf20 | 1,135 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-02-08.
# $Id$
#
import datetime
import logging
import random
__all__ = ("filter_key", "ord_to_key", "generate_key")
def _is_valid_key(s):
if s.isdigit():
return True
elif s.lower() >= "a" and s.lower() <= "z":
return True
elif s == "-" or s == "." or s == "@" or s == "_":
return True
else:
return False
def filter_key(name, min_length=None, reserved=None, force_lower=True):
reserved = reserved or []
pk = filter(_is_valid_key, str(name))
if force_lower:
pk = pk.lower()
if min_length and len(pk) < min_length:
raise ValueError("'%s' is too short." % pk)
if pk in reserved:
raise ValueError("'%s' is reserved." % pk)
return pk
def ord_to_key(name, separator=None):
separator = separator or "-"
ord_list = ["%x" % ord(c) for c in name if not c.isspace()]
return separator.join(ord_list)
def generate_key(max_rand=None):
max_rand = max_rand or 0xFFFF
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
rand_suffix = "%4X" % random.randint(0, max_rand)
return "%sX%s" % (timestamp, rand_suffix)
# EOF
| zzheng | friday/website/friday/common/dbutils.py | Python | asf20 | 1,328 |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| zzheng | friday/website/friday/manage.py | Python | asf20 | 557 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-04-27.
# $Id$
#
from djangomockup.models.query import QuerySet
class Manager(object):
"""
This class simulates the Django Manager interface, through which database query operations are
provided to models. To each model class, a manager called objects is added.
"""
def __init__(self, model):
super(Manager, self).__init__()
self.model = model
def get(self, **kwargs):
"""
Returns the instance by primary key. Expected keyword arguments are: 'pk' or 'id'.
If no instance is found, this function raises model's DoesNotExist exception.
"""
if len(kwargs) != 1:
raise TypeError("get() takes 1 argument (%d given)" % len(kwargs))
if "pk" in kwargs:
instance = self.model.get_by_key_name(kwargs["pk"])
elif "id" in kwargs:
instance = self.model.get_by_id(kwargs["id"])
else:
raise TypeError("get() got an unexpected keyword argument '%s'" % kwargs.items()[0])
if instance is None:
raise self.model.DoesNotExist()
return instance
def get_query_set(self):
return QuerySet(self.model)
def all(self):
return self.get_query_set()
def filter(self, **kwargs):
return self.get_query_set().filter(**kwargs)
def order_by(self, *fields):
return self.get_query_set().order_by(*fields)
def count(self):
return self.get_query_set().count()
# EOF
| zzheng | friday/website/djangomockup/models/manager.py | Python | asf20 | 1,660 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-04-27.
# $Id$
#
import types
from google.appengine.ext import db
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from djangomockup.models.manager import Manager
from djangomockup.models.signals import pre_save, post_save, pre_delete, post_delete
class ModelMetaclass(db.PropertiedClass):
"""
Metaclass for the combined Django + App Engine model class.
This metaclass inherits from db.PropertiedClass in the Google App Engine library.
This metaclass has two additional purposes:
- Register each model class created with Django (the parent class will take care of registering
it with the appengine libraries).
- Add the (minimum number) of attributes and methods to make Django believe the class is a
normal Django model.
The resulting classes are still not generally useful as Django classes and are intended to be
used by Django only in limited situations such as loading and dumping fixtures.
"""
def __new__(cls, name, bases, attrs):
if name == "Model":
# This metaclass only acts on sub-classes of Model.
return super(ModelMetaclass, cls).__new__(cls, name, bases, attrs)
new_class = super(ModelMetaclass, cls).__new__(cls, name, bases, attrs)
#new_class._meta = ModelOptions(new_class)
new_class.objects = Manager(new_class)
new_class._default_manager = new_class.objects
new_class.DoesNotExist = types.ClassType("DoesNotExist", (ObjectDoesNotExist,), {})
return new_class
class Model(db.Model):
"""
This class simulates some of the Django Model class' behaviors, including:
- provide a 'pk' property, which is the primary key (id or key_name) of the instance.
- provide an 'id' property if the instance's key has an id.
- provide a class attribute 'objects', which is the model manager.
- send signals on saving/deleting an instance.
All model classes should derive from this class.
"""
__metaclass__ = ModelMetaclass
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return unicode(self.key()) == unicode(other.key())
def __ne__(self, other):
return not self.__eq__(other)
@property
def pk(self):
if self.is_saved():
return self.key().id() or self.key().name()
else:
raise AttributeError("%s object has no attribute 'pk'" % self.__class__.__name__)
@property
def id(self):
if self.is_saved() and self.key().id():
return self.key().id()
else:
raise AttributeError("%s object has no attribute 'id'" % self.__class__.__name__)
def save(self):
pre_save.send(sender=self.__class__, instance=self)
created = not self.is_saved()
super(Model, self).put()
post_save.send(sender=self.__class__, instance=self, created=created)
def delete(self):
pre_delete.send(sender=self.__class__, instance=self)
super(Model, self).delete()
post_delete.send(sender=self.__class__, instance=self)
@classmethod
def delete_all(cls):
all_instances = cls.all()
deleted = 0
for instance in all_instances:
instance.delete()
deleted += 1
return deleted
# EOF
| zzheng | friday/website/djangomockup/models/base.py | Python | asf20 | 3,581 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-05-05.
# $Id$
#
from google.appengine.ext import db
class QueryAlreadyExecuted(Exception):
"""
When user tries to filter the query while the query has already been executed.
"""
pass
class QuerySet(object):
"""
Wrapper class around Google App Engine's Query object to simulate Django's QuerySet.
"""
_DEFAULT_LIMIT = 1000
_OPERATORS = {
"exact": "=",
"in": "in",
"gt": ">",
"gte": ">=",
"lt": "<",
"lte": "<=",
}
_IMPLIED_OPERATOR = "="
def __init__(self, model):
super(QuerySet, self).__init__()
self._query = db.Query(model)
self._limit = self._DEFAULT_LIMIT
self._cache = None
def __nonzero__(self):
self._fill_cache()
return bool(self._cache)
def __len__(self):
self._fill_cache()
return len(self._cache)
def __iter__(self):
self._fill_cache()
return self._cache.__iter__()
def __getitem__(self, k):
if not isinstance(k, (slice, int, long)):
raise TypeError("list indices must be integers")
self._fill_cache()
return self._cache[k]
def cursor(self):
"""
Attention: this function is specific to Google App Engine.
"""
self._fill_cache()
if len(self._cache) < self._limit:
return None
return self._query.cursor()
def with_cursor(self, cursor):
"""
Attention: this function is specific to Google App Engine.
"""
self._ensure_query_not_executed("with_cursor")
if cursor:
# We must convert the cursor to str, otherwise, we'll get a BadValueError:
# Invalid cursor XXX: character mapping must return integer, None or unicode.
self._query.with_cursor(str(cursor))
return self
def filter(self, **kwargs):
self._ensure_query_not_executed("filter")
for name, value in kwargs.items():
property_operator = self._parse_field_lookup("filter", name)
self._query.filter(property_operator, value)
return self
def order_by(self, *fields):
self._ensure_query_not_executed("order_by")
for field in fields:
self._query.order(field)
return self
def set_limit(self, limit):
self._ensure_query_not_executed("set_limit")
self._limit = limit
return self
def count(self):
self._fill_cache()
return len(self._cache)
def _fill_cache(self):
if self._cache is None:
self._cache = self._query.fetch(limit=self._limit)
def _ensure_query_not_executed(self, operation_to_apply):
if self._cache is not None:
raise QueryAlreadyExecuted("Failed to apply %s on query set." % operation_to_apply)
def _parse_field_lookup(self, func, field_lookup):
split_tuple = field_lookup.split("__")
prop_name = split_tuple[0]
if len(split_tuple) == 1:
operator = self._IMPLIED_OPERATOR
elif len(split_tuple) == 2:
operator = self._OPERATORS.get(split_tuple[1])
else:
operator = None
if not operator:
raise TypeError("%s got an unexpected keyword argument '%s'" % (func, field_lookup))
return "%s %s" % (prop_name, operator)
# EOF
| zzheng | friday/website/djangomockup/models/query.py | Python | asf20 | 3,633 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-04-27.
# $Id$
#
from djangomockup.models.base import Model
# EOF
| zzheng | friday/website/djangomockup/models/__init__.py | Python | asf20 | 207 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-04-27.
# $Id$
#
from django.dispatch import Signal
pre_save = Signal(providing_args=["instance"])
post_save = Signal(providing_args=["instance", "created"])
pre_delete = Signal(providing_args=["instance"])
post_delete = Signal(providing_args=["instance"])
# EOF
| zzheng | friday/website/djangomockup/models/signals.py | Python | asf20 | 418 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-04-27.
# $Id$
#
__version__ = "0.1"
def get_version():
"""
Returns the djangomockup version number.
"""
return __version__
# EOF
| zzheng | friday/website/djangomockup/__init__.py | Python | asf20 | 298 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2009-12-11.
# $Id$
#
from __future__ import absolute_import # PEP 328
from google.appengine.api import mail
def is_email_valid(email):
return mail.is_email_valid(email)
def send_mail(subject, message, from_email, recipient_list, fail_silently=False):
mail.send_mail(
sender=from_email,
to=recipient_list,
subject=subject,
body=message
)
# EOF
| zzheng | friday/website/djangomockup/mail.py | Python | asf20 | 545 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2010-02-05.
# $Id$
#
"""
Bootstrap script for running a Django (version 1.1) application on Google App Engine.
Notes:
* This module should be imported before any part of Django is imported.
* This module should be imported after the 'DJANGO_SETTINGS_MODULE' variable is set.
References:
* `Running Django on Google App Engine <http://code.google.com/appengine/articles/django.html>`_
* `Third-party Python Libraries on Google App Engine <http://code.google.com/appengine/docs/python/tools/libraries.html>`_
"""
#
# Select Django version.
#
from google.appengine.dist import use_library
use_library("django", "1.1")
#
# Force Django to reload its settings.
#
from django.conf import settings
settings._target = None
#
# Update Django signal handlers (for Django version 1.1).
#
import logging
import django.db
from django.core.signals import got_request_exception
def log_exception(*args, **kwds):
logging.exception("Exception in request:")
got_request_exception.disconnect(django.db._rollback_on_exception)
got_request_exception.connect(log_exception)
#
# Done.
#
_bootstrap_done = True
# EOF
| zzheng | friday/website/djangomockup/bootstrap.py | Python | asf20 | 1,294 |
# Initialize the autoconf system for the specified tool, version and mailing list
AC_INIT(iperf, 3.0a4, iperf-users@lists.sourceforge.net)
# Specify where the auxiliary files created by configure should go. The config
# directory is picked so that they don't clutter up more useful directories.
AC_CONFIG_AUX_DIR(config)
# Initialize the automake system
AM_INIT_AUTOMAKE
AM_CONFIG_HEADER(src/config.h)
AC_CANONICAL_HOST
# Checks for tools: c compiler, ranlib (used for creating static libraries),
# symlinks and libtool
AC_PROG_CC
AC_PROG_RANLIB
AC_PROG_LN_S
AC_PROG_LIBTOOL
# Sets a conditional makefile variable so that certain Makefile tasks will be
# performed only on linux (currently, add -luuid to LD_FLAGS)
AM_CONDITIONAL(LINUX, [case $host_os in linux*) true;; *) false;; esac])
# Checks for header files.
AC_HEADER_STDC
# Check for systems which need -lsocket and -lnsl
#AX_LIB_SOCKET_NSL
# Solaris puts nanosleep in -lrt
AC_SEARCH_LIBS(nanosleep, [rt], [], [
echo "nanosleep() required for timing operations."
exit 1
])
# Solaris puts hstrerror in -lresolv
AC_SEARCH_LIBS(hstrerror, [resolv], [], [
echo "nanosleep() required for timing operations."
exit 1
])
# Checks for typedefs, structures, and compiler characteristics.
AC_C_CONST
AC_OUTPUT([Makefile src/Makefile])
| zz1126wnx-iperf3 | configure.ac | M4Sugar | bsd | 1,297 |
#!/bin/sh
#
# $Id: bootstrap.sh 446 2008-04-21 04:07:15Z boote $
#
#########################################################################
# #
# Copyright (C) 2003 #
# Internet2 #
# All Rights Reserved #
# #
#########################################################################
#
# File: bootstrap
#
# Author: Jeff Boote
# Internet2
#
# Date: Tue Sep 16 14:21:57 MDT 2003
#
# Description:
# This script is used to bootstrap the autobuild
# process.
#
# RUNNING THIS SCRIPT IS NOT RECOMMENDED
# (You should just use the "configure" script
# that was bundled with the distribution if
# at all possible.)
#
case "$1" in
ac257)
alias autoconf=autoconf257
alias autoheader=autoheader257
alias automake=automake17
alias aclocal=aclocal17
export AUTOCONF=autoconf257
;;
*)
;;
esac
set -x
glibtoolize --copy --force --automake
aclocal -I config
autoheader
automake --foreign --add-missing --copy
autoconf
rm -rf config.cache
| zz1126wnx-iperf3 | bootstrap.sh | Shell | bsd | 1,007 |
SUBDIRS = src
| zz1126wnx-iperf3 | Makefile.am | Makefile | bsd | 14 |
IPERFDIR = ..
CC = gcc
CFLAGS = -I$(IPERFDIR)/src
LDFLAGS = -L$(IPERFDIR)/src
LIBS = -liperf
all: mic mis
mic: mic.c $(IPERFDIR)/src/iperf_api.h $(IPERFDIR)/src/libiperf.a
$(CC) $(CFLAGS) mic.c $(LDFLAGS) $(LIBS) -o mic
mis: mis.c $(IPERFDIR)/src/iperf_api.h $(IPERFDIR)/src/libiperf.a
$(CC) $(CFLAGS) mis.c $(LDFLAGS) $(LIBS) -o mis
clean:
-rm -f mic mis *.o *.a a.out core core.* *.core
| zz1126wnx-iperf3 | examples/Makefile | Makefile | bsd | 403 |
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sysexits.h>
#include <stdint.h>
#include <iperf_api.h>
int
main( int argc, char** argv )
{
char* argv0;
int port;
struct iperf_test *test;
argv0 = strrchr( argv[0], '/' );
if ( argv0 != (char*) 0 )
++argv0;
else
argv0 = argv[0];
if ( argc != 2 ) {
fprintf( stderr, "usage: %s [port]\n", argv0 );
exit( EXIT_FAILURE );
}
port = atoi( argv[1] );
test = iperf_new_test();
if ( test == NULL ) {
fprintf( stderr, "%s: failed to create test\n", argv0 );
exit( EXIT_FAILURE );
}
iperf_defaults( test );
iperf_set_test_role( test, 's' );
iperf_set_test_server_port( test, port );
for (;;) {
if ( iperf_run_server( test ) < 0 )
fprintf( stderr, "%s: error - %s\n\n", argv0, iperf_strerror( i_errno ) );
iperf_reset_test( test );
}
iperf_free_test( test );
exit( EXIT_SUCCESS );
}
| zz1126wnx-iperf3 | examples/mis.c | C | bsd | 956 |
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sysexits.h>
#include <stdint.h>
#include <iperf_api.h>
int
main( int argc, char** argv )
{
char* argv0;
char* host;
int port;
struct iperf_test *test;
argv0 = strrchr( argv[0], '/' );
if ( argv0 != (char*) 0 )
++argv0;
else
argv0 = argv[0];
if ( argc != 3 ) {
fprintf( stderr, "usage: %s [host] [port]\n", argv0 );
exit( EXIT_FAILURE );
}
host = argv[1];
port = atoi( argv[2] );
test = iperf_new_test();
if ( test == NULL ) {
fprintf( stderr, "%s: failed to create test\n", argv0 );
exit( EXIT_FAILURE );
}
iperf_defaults( test );
/* This main program doesn't use SIGALRM, so the iperf API may use it. */
iperf_set_test_may_use_sigalrm(test, 1);
iperf_set_test_role( test, 'c' );
iperf_set_test_server_hostname( test, host );
iperf_set_test_server_port( test, port );
if ( iperf_run_client( test ) < 0 ) {
fprintf( stderr, "%s: error - %s\n", argv0, iperf_strerror( i_errno ) );
exit( EXIT_FAILURE );
}
iperf_free_test( test );
exit( EXIT_SUCCESS );
}
| zz1126wnx-iperf3 | examples/mic.c | C | bsd | 1,154 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#ifndef __IPERF_H
#define __IPERF_H
#include <sys/time.h>
#include <sys/types.h>
#include <stdint.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include "timer.h"
#include "queue.h"
#include "cjson.h"
typedef uint64_t iperf_size_t;
struct iperf_interval_results
{
iperf_size_t bytes_transferred; /* bytes transfered in this interval */
struct timeval interval_start_time;
struct timeval interval_end_time;
float interval_duration;
#if defined(linux) || defined(__FreeBSD__)
struct tcp_info tcpInfo; /* getsockopt(TCP_INFO) for Linux and FreeBSD */
int this_retrans;
#else
/* Just placeholders, never accessed. */
char *tcpInfo;
int this_retrans;
#endif
TAILQ_ENTRY(iperf_interval_results) irlistentries;
void *custom_data;
};
struct iperf_stream_result
{
iperf_size_t bytes_received;
iperf_size_t bytes_sent;
iperf_size_t bytes_received_this_interval;
iperf_size_t bytes_sent_this_interval;
struct timeval start_time;
struct timeval end_time;
TAILQ_HEAD(irlisthead, iperf_interval_results) interval_results;
void *data;
};
#define COOKIE_SIZE 37 /* size of an ascii uuid */
struct iperf_settings
{
int domain; /* AF_INET or AF_INET6 */
int socket_bufsize; /* window size for TCP */
int blksize; /* size of read/writes (-l) */
uint64_t rate; /* target data rate, UDP only */
int mss; /* for TCP MSS */
int ttl; /* IP TTL option */
int tos; /* type of service bit */
iperf_size_t bytes; /* number of bytes to send */
char unit_format; /* -f */
};
struct iperf_test;
struct iperf_stream
{
struct iperf_test* test;
/* configurable members */
int local_port;
int remote_port;
int socket;
int id;
/* XXX: is settings just a pointer to the same struct in iperf_test? if not,
should it be? */
struct iperf_settings *settings; /* pointer to structure settings */
/* non configurable members */
struct iperf_stream_result *result; /* structure pointer to result */
Timer *send_timer;
int udp_green_light;
int buffer_fd; /* data to send, file descriptor */
char *buffer; /* data to send, mmapped */
/*
* for udp measurements - This can be a structure outside stream, and
* stream can have a pointer to this
*/
int packet_count;
double jitter;
double prev_transit;
int outoforder_packets;
int cnt_error;
uint64_t target;
struct sockaddr_storage local_addr;
struct sockaddr_storage remote_addr;
int (*rcv) (struct iperf_stream * stream);
int (*snd) (struct iperf_stream * stream);
// struct iperf_stream *next;
SLIST_ENTRY(iperf_stream) streams;
void *data;
};
struct protocol {
int id;
char *name;
int (*accept)(struct iperf_test *);
int (*listen)(struct iperf_test *);
int (*connect)(struct iperf_test *);
int (*send)(struct iperf_stream *);
int (*recv)(struct iperf_stream *);
int (*init)(struct iperf_test *);
SLIST_ENTRY(protocol) protocols;
};
struct iperf_test
{
char role; /* c' lient or 's' erver */
struct protocol *protocol;
char state;
char *server_hostname; /* -c option */
char *bind_address; /* -B option */
int server_port;
int duration; /* total duration of test (-t flag) */
int ctrl_sck;
int listener;
int prot_listener;
/* boolean variables for Options */
int daemon; /* -D option */
int debug; /* -d option - debug mode */
int no_delay; /* -N option */
int output_format; /* -O option */
int reverse; /* -R option */
int verbose; /* -V option - verbose mode */
int json_output; /* -J option - JSON output */
int zerocopy; /* -Z option - use sendfile */
int multisend;
int may_use_sigalrm;
/* Select related parameters */
int max_fd;
fd_set read_set; /* set of read sockets */
fd_set write_set; /* set of write sockets */
/* Interval related members */
double stats_interval;
double reporter_interval;
void (*stats_callback) (struct iperf_test *);
void (*reporter_callback) (struct iperf_test *);
Timer *timer;
int done;
Timer *stats_timer;
Timer *reporter_timer;
double cpu_util; /* cpu utilization of the test */
double remote_cpu_util; /* cpu utilization for the remote host/client */
int num_streams; /* total streams in the test (-P) */
iperf_size_t bytes_sent;
char cookie[COOKIE_SIZE];
// struct iperf_stream *streams; /* pointer to list of struct stream */
SLIST_HEAD(slisthead, iperf_stream) streams;
struct iperf_settings *settings;
SLIST_HEAD(plisthead, protocol) protocols;
/* callback functions */
void (*on_new_stream)(struct iperf_stream *);
void (*on_test_start)(struct iperf_test *);
void (*on_connect)(struct iperf_test *);
void (*on_test_finish)(struct iperf_test *);
/* cJSON handles for use when in -J mode */\
cJSON *json_top;
cJSON *json_start;
cJSON *json_intervals;
cJSON *json_end;
};
/* default settings */
#define PORT 5201 /* default port to listen on (don't use the same port as iperf2) */
#define uS_TO_NS 1000
#define SEC_TO_US 1000000LL
#define RATE (1024 * 1024) /* 1 Mbps */
#define DURATION 10 /* seconds */
#define SEC_TO_NS 1000000000LL /* too big for enum/const on some platforms */
#define MAX_RESULT_STRING 4096
/* constants for command line arg sanity checks */
#define MB (1024 * 1024)
#define MAX_TCP_BUFFER (128 * MB)
#define MAX_BLOCKSIZE MB
#define MAX_INTERVAL 60
#define MAX_TIME 3600
#define MAX_MSS (9 * 1024)
#define MAX_STREAMS 128
#endif /* !__IPERF_H */
| zz1126wnx-iperf3 | src/iperf.h | C | bsd | 6,886 |
/*---------------------------------------------------------------
* Copyright (c) 1999,2000,2001,2002,2003
* The Board of Trustees of the University of Illinois
* All Rights Reserved.
*---------------------------------------------------------------
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software (Iperf) and associated
* documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
*
* Redistributions of source code must retain the above
* copyright notice, this list of conditions and
* the following disclaimers.
*
*
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimers in the documentation and/or other materials
* provided with the distribution.
*
*
* Neither the names of the University of Illinois, NCSA,
* nor the names of its contributors may be used to endorse
* or promote products derived from this Software without
* specific prior written permission.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE CONTIBUTORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
* ________________________________________________________________
* National Laboratory for Applied Network Research
* National Center for Supercomputing Applications
* University of Illinois at Urbana-Champaign
* http://www.ncsa.uiuc.edu
* ________________________________________________________________
*
* Locale.c
* by Ajay Tirumala <tirumala@ncsa.uiuc.edu>
* & Mark Gates <mgates@nlanr.net>
* -------------------------------------------------------------------
* Strings and other stuff that is locale specific.
* ------------------------------------------------------------------- */
#include "version.h"
#ifdef __cplusplus
extern "C"
{
#endif
/* -------------------------------------------------------------------
* usage
* ------------------------------------------------------------------- */
const char usage_shortstr[] = "Usage: iperf [-s|-c host] [options]\n"
"Try `iperf --help' for more information.\n";
const char usage_longstr[] = "Usage: iperf [-s|-c host] [options]\n"
" iperf [-h|--help] [-v|--version]\n\n"
"Server or Client:\n"
" -p, --port # server port to listen on/connect to\n"
" -f, --format [kmgKMG] format to report: Kbits, Mbits, KBytes, MBytes\n"
" -i, --interval # seconds between periodic bandwidth reports\n"
" -V, --verbose more detailed output\n"
" -J, --json output in JSON format\n"
" -d, --debug debug mode\n"
" -v, --version show version information and quit\n"
" -h, --help show this message and quit\n"
"Server specific:\n"
" -s, --server run in server mode\n"
"Client specific:\n"
" -c, --client <host> run in client mode, connecting to <host>\n"
" -u, --udp use UDP rather than TCP\n"
" -b, --bandwidth #[KMG] for UDP, bandwidth to send at in bits/sec\n"
" (default %d Mbit/sec)\n"
" -t, --time # time in seconds to transmit for (default %d secs)\n"
" -n, --num #[KMG] number of bytes to transmit (instead of -t)\n"
" -l, --len #[KMG] length of buffer to read or write\n"
" (default %d KB for TCP, %d KB for UDP)\n"
" -P, --parallel # number of parallel client streams to run\n"
" -R, --reverse run in reverse mode (server sends, client receives)\n"
" -w, --window #[KMG] TCP window size (socket buffer size)\n"
" -B, --bind <host> bind to a specific interface or multicast address\n"
" -M, --set-mss # set TCP maximum segment size (MTU - 40 bytes)\n"
" -N, --nodelay set TCP no delay, disabling Nagle's Algorithm\n"
" -4, --version4 only use IPv4\n"
" -6, --version6 only use IPv6\n"
" -S, --tos N set the IP 'type of service'\n"
" -Z, --zerocopy use a 'zero copy' method of sending data\n"
#ifdef NOT_YET_SUPPORTED /* still working on these */
" -D, --daemon run the server as a daemon\n"
#endif
"\n"
"[KMG] indicates options that support a K/M/G suffix for kilo-, mega-, or giga-\n"
"Report bugs to <iperf-users@lists.sourceforge.net>\n";
#ifdef OBSOLETE /* from old iperf: no longer supported. Add some of these back someday */
"-d, --dualtest Do a bidirectional test simultaneously\n"
"-L, --listenport # port to recieve bidirectional tests back on\n"
"-I, --stdin input the data to be transmitted from stdin\n"
"-F, --fileinput <name> input the data to be transmitted from a file\n"
"-r, --tradeoff Do a bidirectional test individually\n"
"-T, --ttl # time-to-live, for multicast (default 1)\n"
"-x, --reportexclude [CDMSV] exclude C(connection) D(data) M(multicast) S(settings) V(server) reports\n"
"-y, --reportstyle C report as a Comma-Separated Values\n"
#endif
const char version[] = "iperf version " IPERF_VERSION " (" IPERF_VERSION_DATE ")";
/* -------------------------------------------------------------------
* settings
* ------------------------------------------------------------------- */
const char seperator_line[] =
"------------------------------------------------------------\n";
const char server_port[] =
"Server listening on %s port %d\n";
const char client_port[] =
"Client connecting to %s, %s port %d\n";
const char bind_address[] =
"Binding to local address %s\n";
const char multicast_ttl[] =
"Setting multicast TTL to %d\n";
const char join_multicast[] =
"Joining multicast group %s\n";
const char client_datagram_size[] =
"Sending %d byte datagrams\n";
const char server_datagram_size[] =
"Receiving %d byte datagrams\n";
const char tcp_window_size[] =
"TCP window size";
const char udp_buffer_size[] =
"UDP buffer size";
const char window_default[] =
"(default)";
const char wait_server_threads[] =
"Waiting for server threads to complete. Interrupt again to force quit.\n";
const char test_start_time[] =
"Starting Test: protocol: %s, %d streams, %d byte blocks, %d second test\n";
const char test_start_bytes[] =
"Starting Test: protocol: %s, %d streams, %d byte blocks, %llu bytes to send\n";
/* -------------------------------------------------------------------
* reports
* ------------------------------------------------------------------- */
const char report_read_lengths[] =
"[%3d] Read lengths occurring in more than 5%% of reads:\n";
const char report_read_length_times[] =
"[%3d] %5d bytes read %5d times (%.3g%%)\n";
const char report_bw_header[] =
"[ ID] Interval Transfer Bandwidth\n";
const char report_bw_retrans_header[] =
"[ ID] Interval Transfer Bandwidth Retransmits\n";
const char report_bw_udp_header[] =
"[ ID] Interval Transfer Bandwidth Jitter Lost/Total \
Datagrams\n";
const char report_bw_format[] =
"[%3d] %6.2f-%-6.2f sec %ss %ss/sec\n";
const char report_bw_retrans_format[] =
"[%3d] %6.2f-%-6.2f sec %ss %ss/sec %ld\n";
const char report_bw_udp_format[] =
"[%3d] %6.2f-%-6.2f sec %ss %ss/sec %5.3f ms %d/%d (%.2g%%)\n";
const char report_sum_bw_format[] =
"[SUM] %6.2f-%-6.2f sec %ss %ss/sec\n";
const char report_sum_bw_retrans_format[] =
"[SUM] %6.2f-%-6.2f sec %ss %ss/sec %ld\n";
const char report_sum_bw_udp_format[] =
"[SUM] %6.2f-%-6.2f sec %ss %ss/sec %5.3f ms %d/%d (%.2g%%)\n";
const char report_bw_separator[] =
"- - - - - - - - - - - - - - - - - - - - - - - - -\n";
const char report_outoforder[] =
"[%3d] %4.1f-%4.1f sec %d datagrams received out-of-order\n";
const char report_sum_outoforder[] =
"[SUM] %4.1f-%4.1f sec %d datagrams received out-of-order\n";
const char report_peer[] =
"[%3d] local %s port %u connected with %s port %u\n";
const char report_mss_unsupported[] =
"[%3d] MSS and MTU size unknown (TCP_MAXSEG not supported by OS?)\n";
const char report_mss[] =
"[%3d] MSS size %d bytes (MTU %d bytes, %s)\n";
const char report_datagrams[] =
"[%3d] Sent %d datagrams\n";
const char report_sum_datagrams[] =
"[SUM] Sent %d datagrams\n";
const char server_reporting[] =
"[%3d] Server Report:\n";
const char reportCSV_peer[] =
"%s,%u,%s,%u";
#if defined(linux)
const char report_tcpInfo[] =
"event=TCP_Info CWND=%u SND_SSTHRESH=%u RCV_SSTHRESH=%u UNACKED=%u SACK=%u LOST=%u RETRANS=%u FACK=%u RTT=%u REORDERING=%u\n";
#endif
#if defined(__FreeBSD__)
const char report_tcpInfo[] =
"event=TCP_Info CWND=%u RCV_WIND=%u SND_SSTHRESH=%u RTT=%u\n";
#endif
#ifdef HAVE_QUAD_SUPPORT
#ifdef HAVE_PRINTF_QD
const char reportCSV_bw_format[] =
"%s,%s,%d,%.1f-%.1f,%qd,%qd\n";
const char reportCSV_bw_udp_format[] =
"%s,%s,%d,%.1f-%.1f,%qd,%qd,%.3f,%d,%d,%.3f,%d\n";
#else // HAVE_PRINTF_QD
const char reportCSV_bw_format[] =
"%s,%s,%d,%.1f-%.1f,%lld,%lld\n";
const char reportCSV_bw_udp_format[] =
"%s,%s,%d,%.1f-%.1f,%lld,%lld,%.3f,%d,%d,%.3f,%d\n";
#endif // HAVE_PRINTF_QD
#else // HAVE_QUAD_SUPPORT
#ifdef WIN32
const char reportCSV_bw_format[] =
"%s,%s,%d,%.1f-%.1f,%I64d,%I64d\n";
const char reportCSV_bw_udp_format[] =
"%s,%s,%d,%.1f-%.1f,%I64d,%I64d,%.3f,%d,%d,%.3f,%d\n";
#else
const char reportCSV_bw_format[] =
"%s,%s,%d,%.1f-%.1f,%d,%d\n";
const char reportCSV_bw_udp_format[] =
"%s,%s,%d,%.1f-%.1f,%d,%d,%.3f,%d,%d,%.3f,%d\n";
#endif //WIN32
#endif //HAVE_QUAD_SUPPORT
/* -------------------------------------------------------------------
* warnings
* ------------------------------------------------------------------- */
const char warn_window_requested[] =
" (WARNING: requested %s)";
const char warn_window_small[] = "\
WARNING: TCP window size set to %d bytes. A small window size\n\
will give poor performance. See the Iperf documentation.\n";
const char warn_delay_large[] =
"WARNING: delay too large, reducing from %.1f to 1.0 seconds.\n";
const char warn_no_pathmtu[] =
"WARNING: Path MTU Discovery may not be enabled.\n";
const char warn_no_ack[]=
"[%3d] WARNING: did not receive ack of last datagram after %d tries.\n";
const char warn_ack_failed[]=
"[%3d] WARNING: ack of last datagram failed after %d tries.\n";
const char warn_fileopen_failed[]=
"WARNING: Unable to open file stream for transfer\n\
Using default data stream. \n";
const char unable_to_change_win[]=
"WARNING: Unable to change the window size\n";
const char opt_estimate[]=
"Optimal Estimate\n";
const char report_interval_small[] =
"WARNING: interval too small, increasing from %3.2f to 0.5 seconds.\n";
const char warn_invalid_server_option[] =
"WARNING: option -%c is not valid for server mode\n";
const char warn_invalid_client_option[] =
"WARNING: option -%c is not valid for client mode\n";
const char warn_invalid_compatibility_option[] =
"WARNING: option -%c is not valid in compatibility mode\n";
const char warn_implied_udp[] =
"WARNING: option -%c implies udp testing\n";
const char warn_implied_compatibility[] =
"WARNING: option -%c has implied compatibility mode\n";
const char warn_buffer_too_small[] =
"WARNING: the UDP buffer was increased to %d for proper operation\n";
const char warn_invalid_single_threaded[] =
"WARNING: option -%c is not valid in single threaded versions\n";
const char warn_invalid_report_style[] =
"WARNING: unknown reporting style \"%s\", switching to default\n";
const char warn_invalid_report[] =
"WARNING: unknown reporting type \"%c\", ignored\n valid options are:\n\t exclude: C(connection) D(data) M(multicast) S(settings) V(server) report\n\n";
#ifdef __cplusplus
} /* end extern "C" */
#endif
| zz1126wnx-iperf3 | src/locale.c | C | bsd | 13,369 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <sys/time.h>
#include <sys/select.h>
#include "iperf.h"
#include "iperf_api.h"
#include "iperf_tcp.h"
#include "net.h"
/* iperf_tcp_recv
*
* receives the data for TCP
*/
int
iperf_tcp_recv(struct iperf_stream *sp)
{
int r;
r = Nread(sp->socket, sp->buffer, sp->settings->blksize, Ptcp);
if (r < 0)
return r;
sp->result->bytes_received += r;
sp->result->bytes_received_this_interval += r;
return r;
}
/* iperf_tcp_send
*
* sends the data for TCP
*/
int
iperf_tcp_send(struct iperf_stream *sp)
{
int r;
if (sp->test->zerocopy)
r = Nsendfile(sp->buffer_fd, sp->socket, sp->buffer, sp->settings->blksize);
else
r = Nwrite(sp->socket, sp->buffer, sp->settings->blksize, Ptcp);
if (r < 0)
return r;
sp->result->bytes_sent += r;
sp->result->bytes_sent_this_interval += r;
return r;
}
/* iperf_tcp_accept
*
* accept a new TCP stream connection
*/
int
iperf_tcp_accept(struct iperf_test * test)
{
int s;
int rbuf = ACCESS_DENIED;
char cookie[COOKIE_SIZE];
socklen_t len;
struct sockaddr_storage addr;
len = sizeof(addr);
if ((s = accept(test->listener, (struct sockaddr *) &addr, &len)) < 0) {
i_errno = IESTREAMCONNECT;
return -1;
}
if (Nread(s, cookie, COOKIE_SIZE, Ptcp) < 0) {
i_errno = IERECVCOOKIE;
return -1;
}
if (strcmp(test->cookie, cookie) != 0) {
if (Nwrite(s, (char*) &rbuf, sizeof(char), Ptcp) < 0) {
i_errno = IESENDMESSAGE;
return -1;
}
close(s);
}
return s;
}
/* iperf_tcp_listen
*
* start up a listener for TCP stream connections
*/
int
iperf_tcp_listen(struct iperf_test *test)
{
struct addrinfo hints, *res;
char portstr[6];
int s, opt;
s = test->listener;
if (test->no_delay || test->settings->mss || test->settings->socket_bufsize) {
FD_CLR(s, &test->read_set);
close(s);
snprintf(portstr, 6, "%d", test->server_port);
memset(&hints, 0, sizeof(hints));
hints.ai_family = (test->settings->domain == AF_UNSPEC ? AF_INET6 : test->settings->domain);
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if (getaddrinfo(test->bind_address, portstr, &hints, &res) != 0) {
i_errno = IESTREAMLISTEN;
return -1;
}
if ((s = socket(res->ai_family, SOCK_STREAM, 0)) < 0) {
i_errno = IESTREAMLISTEN;
return -1;
}
if (test->no_delay) {
opt = 1;
if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof(opt)) < 0) {
i_errno = IESETNODELAY;
return -1;
}
}
// XXX: Setting MSS is very buggy!
if ((opt = test->settings->mss)) {
if (setsockopt(s, IPPROTO_TCP, TCP_MAXSEG, &opt, sizeof(opt)) < 0) {
i_errno = IESETMSS;
return -1;
}
}
if ((opt = test->settings->socket_bufsize)) {
if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt)) < 0) {
i_errno = IESETBUF;
return -1;
}
if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt)) < 0) {
i_errno = IESETBUF;
return -1;
}
}
opt = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
i_errno = IEREUSEADDR;
return -1;
}
if (test->settings->domain == AF_UNSPEC || test->settings->domain == AF_INET6) {
if (test->settings->domain == AF_UNSPEC)
opt = 0;
else if (test->settings->domain == AF_INET6)
opt = 1;
setsockopt(s, SOL_SOCKET, IPV6_V6ONLY, (char *) &opt, sizeof(opt));
}
if (bind(s, (struct sockaddr *) res->ai_addr, res->ai_addrlen) < 0) {
close(s);
i_errno = IESTREAMLISTEN;
return -1;
}
freeaddrinfo(res);
if (listen(s, 5) < 0) {
i_errno = IESTREAMLISTEN;
return -1;
}
test->listener = s;
}
return s;
}
/* iperf_tcp_connect
*
* connect to a TCP stream listener
*/
int
iperf_tcp_connect(struct iperf_test *test)
{
struct addrinfo hints, *local_res, *server_res;
char portstr[6];
int s, opt;
if (test->bind_address) {
memset(&hints, 0, sizeof(hints));
hints.ai_family = test->settings->domain;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(test->bind_address, NULL, &hints, &local_res) != 0) {
i_errno = IESTREAMCONNECT;
return -1;
}
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = test->settings->domain;
hints.ai_socktype = SOCK_STREAM;
snprintf(portstr, sizeof(portstr), "%d", test->server_port);
if (getaddrinfo(test->server_hostname, portstr, &hints, &server_res) != 0) {
i_errno = IESTREAMCONNECT;
return -1;
}
if ((s = socket(server_res->ai_family, SOCK_STREAM, 0)) < 0) {
i_errno = IESTREAMCONNECT;
return -1;
}
if (test->bind_address) {
if (bind(s, (struct sockaddr *) local_res->ai_addr, local_res->ai_addrlen) < 0) {
i_errno = IESTREAMCONNECT;
return -1;
}
freeaddrinfo(local_res);
}
/* Set socket options */
if (test->no_delay) {
opt = 1;
if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof(opt)) < 0) {
i_errno = IESETNODELAY;
return -1;
}
}
if ((opt = test->settings->mss)) {
if (setsockopt(s, IPPROTO_TCP, TCP_MAXSEG, &opt, sizeof(opt)) < 0) {
i_errno = IESETMSS;
return -1;
}
}
if ((opt = test->settings->socket_bufsize)) {
if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt)) < 0) {
i_errno = IESETBUF;
return -1;
}
if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt)) < 0) {
i_errno = IESETBUF;
return -1;
}
}
if (connect(s, (struct sockaddr *) server_res->ai_addr, server_res->ai_addrlen) < 0 && errno != EINPROGRESS) {
i_errno = IESTREAMCONNECT;
return -1;
}
freeaddrinfo(server_res);
/* Send cookie for verification */
if (Nwrite(s, test->cookie, COOKIE_SIZE, Ptcp) < 0) {
i_errno = IESENDCOOKIE;
return -1;
}
return s;
}
| zz1126wnx-iperf3 | src/iperf_tcp.c | C | bsd | 7,086 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#ifndef __IPERF_API_H
#define __IPERF_API_H
#include <setjmp.h>
struct iperf_test;
struct iperf_stream_result;
struct iperf_interval_results;
struct iperf_stream;
/* default settings */
#define Ptcp SOCK_STREAM
#define Pudp SOCK_DGRAM
#define DEFAULT_UDP_BLKSIZE 8192
#define DEFAULT_TCP_BLKSIZE (128 * 1024) /* default read/write block size */
/* states */
#define TEST_START 1
#define TEST_RUNNING 2
#define RESULT_REQUEST 3
#define TEST_END 4
#define STREAM_BEGIN 5
#define STREAM_RUNNING 6
#define STREAM_END 7
#define ALL_STREAMS_END 8
#define PARAM_EXCHANGE 9
#define CREATE_STREAMS 10
#define SERVER_TERMINATE 11
#define CLIENT_TERMINATE 12
#define EXCHANGE_RESULTS 13
#define DISPLAY_RESULTS 14
#define IPERF_START 15
#define IPERF_DONE 16
#define ACCESS_DENIED (-1)
#define SERVER_ERROR (-2)
/* Getter routines for some fields inside iperf_test. */
int iperf_get_control_socket( struct iperf_test* ipt );
int iperf_get_test_duration( struct iperf_test* ipt );
char iperf_get_test_role( struct iperf_test* ipt );
int iperf_get_test_blksize( struct iperf_test* ipt );
uint64_t iperf_get_test_rate( struct iperf_test* ipt );
int iperf_get_test_socket_bufsize( struct iperf_test* ipt );
double iperf_get_test_reporter_interval( struct iperf_test* ipt );
double iperf_get_test_stats_interval( struct iperf_test* ipt );
int iperf_get_test_num_streams( struct iperf_test* ipt );
int iperf_get_test_server_port( struct iperf_test* ipt );
char* iperf_get_test_server_hostname( struct iperf_test* ipt );
int iperf_get_test_protocol_id( struct iperf_test* ipt );
int iperf_get_test_json_output( struct iperf_test* ipt );
int iperf_get_test_zerocopy( struct iperf_test* ipt );
int iperf_get_test_may_use_sigalrm( struct iperf_test* ipt );
/* Setter routines for some fields inside iperf_test. */
void iperf_set_control_socket( struct iperf_test* ipt, int ctrl_sck );
void iperf_set_test_duration( struct iperf_test* ipt, int duration );
void iperf_set_test_reporter_interval( struct iperf_test* ipt, double reporter_interval );
void iperf_set_test_stats_interval( struct iperf_test* ipt, double stats_interval );
void iperf_set_test_state( struct iperf_test* ipt, char state );
void iperf_set_test_blksize( struct iperf_test* ipt, int blksize );
void iperf_set_test_rate( struct iperf_test* ipt, uint64_t rate );
void iperf_set_test_server_port( struct iperf_test* ipt, int server_port );
void iperf_set_test_socket_bufsize( struct iperf_test* ipt, int socket_bufsize );
void iperf_set_test_num_streams( struct iperf_test* ipt, int num_streams );
void iperf_set_test_role( struct iperf_test* ipt, char role );
void iperf_set_test_server_hostname( struct iperf_test* ipt, char* server_hostname );
void iperf_set_test_json_output( struct iperf_test* ipt, int json_output );
int iperf_has_zerocopy( void );
void iperf_set_test_zerocopy( struct iperf_test* ipt, int zerocopy );
void iperf_set_test_may_use_sigalrm( struct iperf_test* ipt, int may_use_sigalrm );
/**
* exchange_parameters - handles the param_Exchange part for client
*
*/
int iperf_exchange_parameters(struct iperf_test * test);
/**
* add_to_interval_list -- adds new interval to the interval_list
*
*/
void add_to_interval_list(struct iperf_stream_result * rp, struct iperf_interval_results *temp);
/**
* connect_msg -- displays connection message
* denoting senfer/receiver details
*
*/
void connect_msg(struct iperf_stream * sp);
/**
* iperf_stats_callback -- handles the statistic gathering
*
*/
void iperf_stats_callback(struct iperf_test * test);
/**
* iperf_reporter_callback -- handles the report printing
*
*/
void iperf_reporter_callback(struct iperf_test * test);
/**
* iperf_new_test -- return a new iperf_test with default values
*
* returns NULL on failure
*
*/
struct iperf_test *iperf_new_test();
int iperf_defaults(struct iperf_test * testp);
/**
* iperf_free_test -- free resources used by test, calls iperf_free_stream to
* free streams
*
*/
void iperf_free_test(struct iperf_test * testp);
/**
* iperf_new_stream -- return a net iperf_stream with default values
*
* returns NULL on failure
*
*/
struct iperf_stream *iperf_new_stream(struct iperf_test *, int);
/**
* iperf_add_stream -- add a stream to a test
*
*/
void iperf_add_stream(struct iperf_test * test, struct iperf_stream * stream);
/**
* iperf_init_stream -- init resources associated with test
*
*/
int iperf_init_stream(struct iperf_stream *, struct iperf_test *);
/**
* iperf_free_stream -- free resources associated with test
*
*/
void iperf_free_stream(struct iperf_stream * sp);
int has_tcpinfo(void);
int has_tcpinfo_retransmits(void);
void save_tcpinfo(struct iperf_stream *sp, struct iperf_interval_results *irp);
long get_tcpinfo_total_retransmits(struct iperf_interval_results *irp);
void print_tcpinfo(struct iperf_test *test);
void build_tcpinfo_message(struct iperf_interval_results *r, char *message);
int iperf_send(struct iperf_test *, fd_set *) /* __attribute__((hot)) */;
int iperf_recv(struct iperf_test *, fd_set *);
void sig_handler(int);
void usage();
void usage_long();
void warning(char *);
int iperf_exchange_results(struct iperf_test *);
int iperf_init_test(struct iperf_test *);
int iperf_parse_arguments(struct iperf_test *, int, char **);
void iperf_reset_test(struct iperf_test *);
struct protocol *get_protocol(struct iperf_test *, int);
int set_protocol(struct iperf_test *, int);
void iperf_on_new_stream(struct iperf_stream *);
void iperf_on_test_start(struct iperf_test *);
void iperf_on_connect(struct iperf_test *);
void iperf_on_test_finish(struct iperf_test *);
extern jmp_buf env;
/* Client routines. */
int iperf_run_client(struct iperf_test *);
int iperf_connect(struct iperf_test *);
int iperf_create_streams(struct iperf_test *);
int iperf_handle_message_client(struct iperf_test *);
int iperf_client_end(struct iperf_test *);
/* Server routines. */
int iperf_run_server(struct iperf_test *);
int iperf_server_listen(struct iperf_test *);
int iperf_accept(struct iperf_test *);
int iperf_handle_message_server(struct iperf_test *);
void iperf_test_reset(struct iperf_test *);
/* JSON output routines. */
int iperf_json_start(struct iperf_test *);
int iperf_json_finish(struct iperf_test *);
/* Error routines. */
void iperf_err(struct iperf_test *test, const char *format, ...) __attribute__ ((format(printf,2,3)));
void iperf_errexit(struct iperf_test *test, const char *format, ...) __attribute__ ((format(printf,2,3),noreturn));
char *iperf_strerror(int);
extern int i_errno;
enum {
IENONE = 0, // No error
/* Parameter errors */
IESERVCLIENT = 1, // Iperf cannot be both server and client
IENOROLE = 2, // Iperf must either be a client (-c) or server (-s)
IESERVERONLY = 3, // This option is server only
IECLIENTONLY = 4, // This option is client only
IEDURATION = 5, // test duration too long. Maximum value = %dMAX_TIME
IENUMSTREAMS = 6, // Number of parallel streams too large. Maximum value = %dMAX_STREAMS
IEBLOCKSIZE = 7, // Block size too large. Maximum value = %dMAX_BLOCKSIZE
IEBUFSIZE = 8, // Socket buffer size too large. Maximum value = %dMAX_TCP_BUFFER
IEINTERVAL = 9, // Report interval too large. Maxumum value = %dMAX_INTERVAL
IEMSS = 10, // MSS too large. Maximum value = %dMAX_MSS
IENOSENDFILE = 11, // This OS does not support sendfile
/* Test errors */
IENEWTEST = 100, // Unable to create a new test (check perror)
IEINITTEST = 101, // Test initialization failed (check perror)
IELISTEN = 102, // Unable to listen for connections (check perror)
IECONNECT = 103, // Unable to connect to server (check herror/perror) [from netdial]
IEACCEPT = 104, // Unable to accept connection from client (check herror/perror)
IESENDCOOKIE = 105, // Unable to send cookie to server (check perror)
IERECVCOOKIE = 106, // Unable to receive cookie from client (check perror)
IECTRLWRITE = 107, // Unable to write to the control socket (check perror)
IECTRLREAD = 108, // Unable to read from the control socket (check perror)
IECTRLCLOSE = 109, // Control socket has closed unexpectedly
IEMESSAGE = 110, // Received an unknown message
IESENDMESSAGE = 111, // Unable to send control message to client/server (check perror)
IERECVMESSAGE = 112, // Unable to receive control message from client/server (check perror)
IESENDPARAMS = 113, // Unable to send parameters to server (check perror)
IERECVPARAMS = 114, // Unable to receive parameters from client (check perror)
IEPACKAGERESULTS = 115, // Unable to package results (check perror)
IESENDRESULTS = 116, // Unable to send results to client/server (check perror)
IERECVRESULTS = 117, // Unable to receive results from client/server (check perror)
IESELECT = 118, // Select failed (check perror)
IECLIENTTERM = 119, // The client has terminated
IESERVERTERM = 120, // The server has terminated
IEACCESSDENIED = 121, // The server is busy running a test. Try again later.
IESETNODELAY = 122, // Unable to set TCP NODELAY (check perror)
IESETMSS = 123, // Unable to set TCP MSS (check perror)
IESETBUF = 124, // Unable to set socket buffer size (check perror)
IESETTOS = 125, // Unable to set IP TOS (check perror)
IESETCOS = 126, // Unable to set IPv6 traffic class (check perror)
IEREUSEADDR = 127, // Unable to set reuse address on socket (check perror)
IENONBLOCKING = 128, // Unable to set socket to non-blocking (check perror)
IESETWINDOWSIZE = 129, // Unable to set socket window size (check perror)
IEPROTOCOL = 130, // Protocol does not exist
/* Stream errors */
IECREATESTREAM = 200, // Unable to create a new stream (check herror/perror)
IEINITSTREAM = 201, // Unable to initialize stream (check herror/perror)
IESTREAMLISTEN = 202, // Unable to start stream listener (check perror)
IESTREAMCONNECT = 203, // Unable to connect stream (check herror/perror)
IESTREAMACCEPT = 204, // Unable to accepte stream connection (check perror)
IESTREAMWRITE = 205, // Unable to write to stream socket (check perror)
IESTREAMREAD = 206, // Unable to read from stream (check perror)
IESTREAMCLOSE = 207, // Stream has closed unexpectedly
IESTREAMID = 208, // Stream has invalid ID
/* Timer errors */
IENEWTIMER = 300, // Unable to create new timer (check perror)
IEUPDATETIMER = 301, // Unable to update timer (check perror)
};
#endif /* !__IPERF_API_H */
| zz1126wnx-iperf3 | src/iperf_api.h | C | bsd | 11,187 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
/* iperf_server_api.c: Functions to be used by an iperf server
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>
#include <unistd.h>
#include <assert.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <pthread.h>
#include <stdint.h>
#include <netinet/tcp.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sched.h>
#include <setjmp.h>
#include "iperf.h"
#include "iperf_api.h"
#include "iperf_udp.h"
#include "iperf_tcp.h"
#include "iperf_util.h"
#include "timer.h"
#include "net.h"
#include "units.h"
#include "tcp_window_size.h"
#include "iperf_util.h"
#include "locale.h"
int
iperf_server_listen(struct iperf_test *test)
{
if((test->listener = netannounce(test->settings->domain, Ptcp, test->bind_address, test->server_port)) < 0) {
i_errno = IELISTEN;
return -1;
}
if (!test->json_output) {
printf("-----------------------------------------------------------\n");
printf("Server listening on %d\n", test->server_port);
}
// This needs to be changed to reflect if client has different window size
// make sure we got what we asked for
/* XXX: This needs to be moved to the stream listener
if ((x = get_tcp_windowsize(test->listener, SO_RCVBUF)) < 0) {
// Needs to set some sort of error number/message
perror("SO_RCVBUF");
return -1;
}
*/
// XXX: This code needs to be moved to after parameter exhange
/*
char ubuf[UNIT_LEN];
int x;
if (test->protocol->id == Ptcp) {
if (test->settings->socket_bufsize > 0) {
unit_snprintf(ubuf, UNIT_LEN, (double) x, 'A');
if (test->json_output)
printf("TCP window size: %s\n", ubuf);
} else {
if (test->json_output)
printf("Using TCP Autotuning\n");
}
}
*/
if (!test->json_output)
printf("-----------------------------------------------------------\n");
FD_ZERO(&test->read_set);
FD_ZERO(&test->write_set);
FD_SET(test->listener, &test->read_set);
test->max_fd = (test->listener > test->max_fd) ? test->listener : test->max_fd;
return 0;
}
int
iperf_accept(struct iperf_test *test)
{
int s;
int rbuf = ACCESS_DENIED;
char cookie[COOKIE_SIZE];
socklen_t len;
struct sockaddr_storage addr;
len = sizeof(addr);
if ((s = accept(test->listener, (struct sockaddr *) &addr, &len)) < 0) {
i_errno = IEACCEPT;
return -1;
}
if (test->ctrl_sck == -1) {
/* Server free, accept new client */
if (Nread(s, test->cookie, COOKIE_SIZE, Ptcp) < 0) {
i_errno = IERECVCOOKIE;
return -1;
}
FD_SET(s, &test->read_set);
FD_SET(s, &test->write_set);
test->max_fd = (s > test->max_fd) ? s : test->max_fd;
test->ctrl_sck = s;
test->state = PARAM_EXCHANGE;
if (Nwrite(test->ctrl_sck, &test->state, sizeof(char), Ptcp) < 0) {
i_errno = IESENDMESSAGE;
return -1;
}
if (iperf_exchange_parameters(test) < 0) {
return -1;
}
if (test->on_connect) {
test->on_connect(test);
}
} else {
/* XXX: Do we even need to receive cookie if we're just going to deny anyways? */
if (Nread(s, cookie, COOKIE_SIZE, Ptcp) < 0) {
i_errno = IERECVCOOKIE;
return -1;
}
if (Nwrite(s, (char*) &rbuf, sizeof(int), Ptcp) < 0) {
i_errno = IESENDMESSAGE;
return -1;
}
close(s);
}
return 0;
}
/**************************************************************************/
int
iperf_handle_message_server(struct iperf_test *test)
{
int rval;
struct iperf_stream *sp;
// XXX: Need to rethink how this behaves to fit API
if ((rval = Nread(test->ctrl_sck, &test->state, sizeof(char), Ptcp)) <= 0) {
if (rval == 0) {
iperf_err(test, "the client has unexpectedly closed the connection");
i_errno = IECTRLCLOSE;
test->state = IPERF_DONE;
return 0;
} else {
i_errno = IERECVMESSAGE;
return -1;
}
}
switch(test->state) {
case TEST_START:
break;
case TEST_END:
cpu_util(&test->cpu_util);
test->stats_callback(test);
SLIST_FOREACH(sp, &test->streams, streams) {
FD_CLR(sp->socket, &test->read_set);
FD_CLR(sp->socket, &test->write_set);
close(sp->socket);
}
test->state = EXCHANGE_RESULTS;
if (Nwrite(test->ctrl_sck, &test->state, sizeof(char), Ptcp) < 0) {
i_errno = IESENDMESSAGE;
return -1;
}
if (iperf_exchange_results(test) < 0)
return -1;
test->state = DISPLAY_RESULTS;
if (Nwrite(test->ctrl_sck, &test->state, sizeof(char), Ptcp) < 0) {
i_errno = IESENDMESSAGE;
return -1;
}
if (test->on_test_finish)
test->on_test_finish(test);
test->reporter_callback(test);
break;
case IPERF_DONE:
break;
case CLIENT_TERMINATE:
i_errno = IECLIENTTERM;
// XXX: Remove this line below!
iperf_err(test, "the client has terminated");
SLIST_FOREACH(sp, &test->streams, streams) {
FD_CLR(sp->socket, &test->read_set);
FD_CLR(sp->socket, &test->write_set);
close(sp->socket);
}
test->state = IPERF_DONE;
break;
default:
i_errno = IEMESSAGE;
return -1;
}
return 0;
}
/* XXX: This function is not used anymore */
void
iperf_test_reset(struct iperf_test *test)
{
struct iperf_stream *sp;
close(test->ctrl_sck);
/* Free streams */
while (!SLIST_EMPTY(&test->streams)) {
sp = SLIST_FIRST(&test->streams);
SLIST_REMOVE_HEAD(&test->streams, streams);
iperf_free_stream(sp);
}
if (test->timer != NULL) {
tmr_cancel(test->timer);
test->timer = NULL;
}
if (test->stats_timer != NULL) {
tmr_cancel(test->stats_timer);
test->stats_timer = NULL;
}
if (test->reporter_timer != NULL) {
tmr_cancel(test->reporter_timer);
test->reporter_timer = NULL;
}
SLIST_INIT(&test->streams);
test->role = 's';
set_protocol(test, Ptcp);
test->duration = DURATION;
test->state = 0;
test->server_hostname = NULL;
test->ctrl_sck = -1;
test->prot_listener = -1;
test->bytes_sent = 0;
test->reverse = 0;
test->no_delay = 0;
FD_ZERO(&test->read_set);
FD_ZERO(&test->write_set);
FD_SET(test->listener, &test->read_set);
test->max_fd = test->listener;
test->num_streams = 1;
test->settings->socket_bufsize = 0;
test->settings->blksize = DEFAULT_TCP_BLKSIZE;
test->settings->rate = RATE; /* UDP only */
test->settings->mss = 0;
memset(test->cookie, 0, COOKIE_SIZE);
}
int
iperf_run_server(struct iperf_test *test)
{
int result, s, streams_accepted;
fd_set read_set, write_set;
struct iperf_stream *sp;
struct timeval now;
if (test->json_output)
if (iperf_json_start(test) < 0)
return -1;
if (test->json_output) {
cJSON_AddItemToObject(test->json_start, "version", cJSON_CreateString(version));
cJSON_AddItemToObject(test->json_start, "system_info", cJSON_CreateString(get_system_info()));
} else if (test->verbose) {
printf("%s\n", version);
system("uname -a");
}
// Open socket and listen
if (iperf_server_listen(test) < 0) {
return -1;
}
// Begin calculating CPU utilization
cpu_util(NULL);
test->state = IPERF_START;
streams_accepted = 0;
(void) gettimeofday(&now, NULL);
while (test->state != IPERF_DONE) {
memcpy(&read_set, &test->read_set, sizeof(fd_set));
memcpy(&write_set, &test->write_set, sizeof(fd_set));
result = select(test->max_fd + 1, &read_set, &write_set, NULL, tmr_timeout(&now));
if (result < 0 && errno != EINTR) {
i_errno = IESELECT;
return -1;
}
if (result > 0) {
if (FD_ISSET(test->listener, &read_set)) {
if (test->state != CREATE_STREAMS) {
if (iperf_accept(test) < 0) {
return -1;
}
FD_CLR(test->listener, &read_set);
}
}
if (FD_ISSET(test->ctrl_sck, &read_set)) {
if (iperf_handle_message_server(test) < 0)
return -1;
FD_CLR(test->ctrl_sck, &read_set);
}
if (test->state == CREATE_STREAMS) {
if (FD_ISSET(test->prot_listener, &read_set)) {
if ((s = test->protocol->accept(test)) < 0)
return -1;
if (!is_closed(s)) {
sp = iperf_new_stream(test, s);
if (!sp)
return -1;
FD_SET(s, &test->read_set);
FD_SET(s, &test->write_set);
test->max_fd = (s > test->max_fd) ? s : test->max_fd;
streams_accepted++;
if (test->on_new_stream)
test->on_new_stream(sp);
}
FD_CLR(test->prot_listener, &read_set);
}
if (streams_accepted == test->num_streams) {
if (test->protocol->id != Ptcp) {
FD_CLR(test->prot_listener, &test->read_set);
close(test->prot_listener);
} else {
if (test->no_delay || test->settings->mss || test->settings->socket_bufsize) {
FD_CLR(test->listener, &test->read_set);
close(test->listener);
if ((s = netannounce(test->settings->domain, Ptcp, test->bind_address, test->server_port)) < 0) {
i_errno = IELISTEN;
return -1;
}
test->listener = s;
test->max_fd = (s > test->max_fd ? s : test->max_fd);
FD_SET(test->listener, &test->read_set);
}
}
test->prot_listener = -1;
test->state = TEST_START;
if (Nwrite(test->ctrl_sck, &test->state, sizeof(char), Ptcp) < 0) {
i_errno = IESENDMESSAGE;
return -1;
}
if (iperf_init_test(test) < 0)
return -1;
test->state = TEST_RUNNING;
if (Nwrite(test->ctrl_sck, &test->state, sizeof(char), Ptcp) < 0) {
i_errno = IESENDMESSAGE;
return -1;
}
}
}
if (test->state == TEST_RUNNING) {
if (test->reverse) {
// Reverse mode. Server sends.
if (iperf_send(test, &write_set) < 0)
return -1;
} else {
// Regular mode. Server receives.
if (iperf_recv(test, &read_set) < 0)
return -1;
}
/* Run the timers. */
(void) gettimeofday(&now, NULL);
tmr_run(&now);
}
}
}
/* Close open test sockets */
close(test->ctrl_sck);
close(test->listener);
if (test->json_output) {
if (iperf_json_finish(test) < 0)
return -1;
}
return 0;
}
| zz1126wnx-iperf3 | src/iperf_server_api.c | C | bsd | 12,430 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#ifndef __IPERF_UDP_H
#define __IPERF_UDP_H
/**
* iperf_udp_recv -- receives the client data for UDP
*
*returns state of packet received
*
*/
int iperf_udp_recv(struct iperf_stream *);
/**
* iperf_udp_send -- sends the client data for UDP
*
* returns: bytes sent
*
*/
int iperf_udp_send(struct iperf_stream *) /* __attribute__((hot)) */;
/**
* iperf_udp_accept -- accepts a new UDP connection
* on udp_listener_socket
*returns 0 on success
*
*/
int iperf_udp_accept(struct iperf_test *);
int iperf_udp_listen(struct iperf_test *);
int iperf_udp_connect(struct iperf_test *);
int iperf_udp_init(struct iperf_test *);
#endif
| zz1126wnx-iperf3 | src/iperf_udp.h | C | bsd | 990 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
/*
* routines related to collection TCP_INFO using getsockopt()
*
* Brian Tierney, ESnet (bltierney@es.net)
*
* Note that this is only really useful on Linux.
* XXX: only standard on linux versions 2.4 and later
#
* FreeBSD has a limitted implementation that only includes the following:
* tcpi_snd_ssthresh, tcpi_snd_cwnd, tcpi_rcv_space, tcpi_rtt
* Based on information on http://wiki.freebsd.org/8.0TODO, I dont think this will be
* fixed before v8.1 at the earliest.
*
* OSX has no support.
*
* I think MS Windows does support TCP_INFO, but iperf3 does not currently support Windows.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/queue.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <string.h>
#include <netinet/in.h>
#include <errno.h>
#include "iperf.h"
#include "iperf_api.h"
#include "locale.h"
/*************************************************************/
int
has_tcpinfo(void)
{
#if defined(linux) || defined(__FreeBSD__)
return 1;
#else
return 0;
#endif
}
/*************************************************************/
int
has_tcpinfo_retransmits(void)
{
#if defined(linux) && defined(TCP_MD5SIG)
/* TCP_MD5SIG doesn't actually have anything to do with TCP
** retransmits, it just showed up in the same rev of the header
** file. If it's present then struct tcp_info has the
** tcpi_total_retrans field that we need; if not, not.
*/
return 1;
#else
#if defined(__FreeBSD__) && __FreeBSD_version >= 600000
/* return 1; */
return 0; /* FreeBSD retransmit reporting doesn't actually work yet */
#else
return 0;
#endif
#endif
}
/*************************************************************/
void
save_tcpinfo(struct iperf_stream *sp, struct iperf_interval_results *irp)
{
#if defined(linux) || defined(__FreeBSD__)
socklen_t tcp_info_length = sizeof(struct tcp_info);
if (getsockopt(sp->socket, IPPROTO_TCP, TCP_INFO, (void *)&irp->tcpInfo, &tcp_info_length) < 0)
iperf_err(sp->test, "getsockopt - %s", strerror(errno));
#endif
}
/*************************************************************/
long
get_tcpinfo_total_retransmits(struct iperf_interval_results *irp)
{
#if defined(linux) && defined(TCP_MD5SIG)
return irp->tcpInfo.tcpi_total_retrans;
#else
#if defined(__FreeBSD__) && __FreeBSD_version >= 600000
return irp->tcpInfo.__tcpi_retransmits;
#else
return -1;
#endif
#endif
}
#ifdef notdef
/*************************************************************/
//print_tcpinfo(struct iperf_interval_results *r)
void
print_tcpinfo(struct iperf_test *test)
{
#if defined(linux)
long int retransmits = 0;
struct iperf_stream *sp;
SLIST_FOREACH(sp, &test->streams, streams) {
retransmits += TAILQ_LAST(&sp->result->interval_results, irlisthead)->tcpInfo.tcpi_retransmits;
}
printf("TCP Info\n");
printf(" Retransmits: %ld\n", retransmits);
/* old test print_tcpinfo code
printf(report_tcpInfo, r->tcpInfo.tcpi_snd_cwnd, r->tcpInfo.tcpi_snd_ssthresh,
r->tcpInfo.tcpi_rcv_ssthresh, r->tcpInfo.tcpi_unacked, r->tcpInfo.tcpi_sacked,
r->tcpInfo.tcpi_lost, r->tcpInfo.tcpi_retrans, r->tcpInfo.tcpi_fackets,
r->tcpInfo.tcpi_rtt, r->tcpInfo.tcpi_reordering);
*/
#endif
#if defined(__FreeBSD__)
/*
printf(report_tcpInfo, r->tcpInfo.tcpi_snd_cwnd, r->tcpInfo.tcpi_rcv_space,
r->tcpInfo.tcpi_snd_ssthresh, r->tcpInfo.tcpi_rtt);
*/
#endif
}
#endif
/*************************************************************/
void
build_tcpinfo_message(struct iperf_interval_results *r, char *message)
{
#if defined(linux)
sprintf(message, report_tcpInfo, r->tcpInfo.tcpi_snd_cwnd, r->tcpInfo.tcpi_snd_ssthresh,
r->tcpInfo.tcpi_rcv_ssthresh, r->tcpInfo.tcpi_unacked, r->tcpInfo.tcpi_sacked,
r->tcpInfo.tcpi_lost, r->tcpInfo.tcpi_retrans, r->tcpInfo.tcpi_fackets,
r->tcpInfo.tcpi_rtt, r->tcpInfo.tcpi_reordering);
#endif
#if defined(__FreeBSD__)
sprintf(message, report_tcpInfo, r->tcpInfo.tcpi_snd_cwnd,
r->tcpInfo.tcpi_rcv_space, r->tcpInfo.tcpi_snd_ssthresh, r->tcpInfo.tcpi_rtt);
#endif
}
| zz1126wnx-iperf3 | src/tcp_info.c | C | bsd | 4,474 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#ifndef __IPERF_UTIL_H
#define __IPERF_UTIL_H
#include "cjson.h"
void make_cookie(char *);
int is_closed(int);
double timeval_to_double(struct timeval *tv);
int timeval_equals(struct timeval *tv0, struct timeval *tv1);
double timeval_diff(struct timeval *tv0, struct timeval *tv1);
int delay(int64_t ns);
void cpu_util(double *);
char* get_system_info(void);
cJSON* iperf_json_printf(const char *format, ...);
#endif
| zz1126wnx-iperf3 | src/iperf_util.h | C | bsd | 769 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <stdint.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdint.h>
#include <netinet/tcp.h>
#include "iperf.h"
#include "iperf_api.h"
#include "units.h"
#include "locale.h"
#include "net.h"
int iperf_run(struct iperf_test *);
/**************************************************************************/
int
main(int argc, char **argv)
{
struct iperf_test *test;
// XXX: Setting the process affinity requires root on most systems.
// Is this a feature we really need?
#ifdef TEST_PROC_AFFINITY
/* didnt seem to work.... */
/*
* increasing the priority of the process to minimise packet generation
* delay
*/
int rc = setpriority(PRIO_PROCESS, 0, -15);
if (rc < 0) {
perror("setpriority:");
fprintf(stderr, "setting priority to valid level\n");
rc = setpriority(PRIO_PROCESS, 0, 0);
}
/* setting the affinity of the process */
cpu_set_t cpu_set;
int affinity = -1;
int ncores = 1;
sched_getaffinity(0, sizeof(cpu_set_t), &cpu_set);
if (errno)
perror("couldn't get affinity:");
if ((ncores = sysconf(_SC_NPROCESSORS_CONF)) <= 0)
err("sysconf: couldn't get _SC_NPROCESSORS_CONF");
CPU_ZERO(&cpu_set);
CPU_SET(affinity, &cpu_set);
if (sched_setaffinity(0, sizeof(cpu_set_t), &cpu_set) != 0)
err("couldn't change CPU affinity");
#endif
test = iperf_new_test();
if (!test)
iperf_errexit(NULL, "create new test error - %s", iperf_strerror(i_errno));
iperf_defaults(test); /* sets defaults */
/* This main program doesn't use SIGALRM, so the iperf API may use it. */
iperf_set_test_may_use_sigalrm(test, 1);
// XXX: Check signal for errors?
signal(SIGINT, sig_handler);
if (setjmp(env)) {
if (test->ctrl_sck >= 0) {
test->state = (test->role == 'c') ? CLIENT_TERMINATE : SERVER_TERMINATE;
if (Nwrite(test->ctrl_sck, &test->state, sizeof(char), Ptcp) < 0) {
i_errno = IESENDMESSAGE;
return -1;
}
}
exit(1);
}
if (iperf_parse_arguments(test, argc, argv) < 0) {
iperf_err(test, "parameter error - %s", iperf_strerror(i_errno));
fprintf(stderr, "\n");
usage_long();
exit(1);
}
if (iperf_run(test) < 0)
iperf_errexit(test, "error - %s", iperf_strerror(i_errno));
iperf_free_test(test);
return 0;
}
/**************************************************************************/
int
iperf_run(struct iperf_test * test)
{
switch (test->role) {
case 's':
for (;;) {
if (iperf_run_server(test) < 0) {
iperf_err(test, "error - %s", iperf_strerror(i_errno));
fprintf(stderr, "\n");
}
iperf_reset_test(test);
}
break;
case 'c':
if (iperf_run_client(test) < 0)
iperf_errexit(test, "error - %s", iperf_strerror(i_errno));
break;
default:
usage();
break;
}
return 0;
}
| zz1126wnx-iperf3 | src/main.c | C | bsd | 3,665 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#ifndef IPERF_LOCALE_H
#define IPERF_LOCALE_H
extern const char usage_shortstr[];
extern const char usage_longstr[];
extern const char version[];
extern const char seperator_line[];
extern const char server_port[] ;
extern const char client_port[] ;
extern const char bind_address[] ;
extern const char multicast_ttl[] ;
extern const char join_multicast[] ;
extern const char client_datagram_size[] ;
extern const char server_datagram_size[] ;
extern const char tcp_window_size[] ;
extern const char udp_buffer_size[] ;
extern const char window_default[] ;
extern const char wait_server_threads[] ;
extern const char test_start_time[];
extern const char test_start_bytes[];
extern const char report_read_lengths[] ;
extern const char report_read_length_times[] ;
extern const char report_bw_header[] ;
extern const char report_bw_retrans_header[] ;
extern const char report_bw_udp_header[] ;
extern const char report_bw_format[] ;
extern const char report_bw_retrans_format[] ;
extern const char report_bw_udp_format[] ;
extern const char report_sum_bw_format[] ;
extern const char report_sum_bw_retrans_format[] ;
extern const char report_sum_bw_udp_format[] ;
extern const char report_bw_separator[] ;
extern const char report_outoforder[] ;
extern const char report_sum_outoforder[] ;
extern const char report_peer[] ;
extern const char report_mss_unsupported[] ;
extern const char report_mss[] ;
extern const char report_datagrams[] ;
extern const char report_sum_datagrams[] ;
extern const char server_reporting[] ;
extern const char reportCSV_peer[] ;
extern const char report_tcpInfo[] ;
extern const char report_tcpInfo[] ;
extern const char warn_window_requested[] ;
extern const char warn_window_small[] ;
extern const char warn_delay_large[] ;
extern const char warn_no_pathmtu[] ;
extern const char warn_no_ack[];
extern const char warn_ack_failed[];
extern const char warn_fileopen_failed[];
extern const char unable_to_change_win[];
extern const char opt_estimate[];
extern const char report_interval_small[] ;
extern const char warn_invalid_server_option[] ;
extern const char warn_invalid_client_option[] ;
extern const char warn_invalid_compatibility_option[] ;
extern const char warn_implied_udp[] ;
extern const char warn_implied_compatibility[] ;
extern const char warn_buffer_too_small[] ;
extern const char warn_invalid_single_threaded[] ;
extern const char warn_invalid_report_style[] ;
extern const char warn_invalid_report[] ;
#endif
| zz1126wnx-iperf3 | src/locale.h | C | bsd | 2,822 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "iperf.h"
#include "units.h"
int
main(int argc, char **argv)
{
iperf_size_t llu;
double d;
char s[11];
assert(1024.0 * 0.5 == unit_atof("0.5K"));
assert(1024.0 == unit_atof("1K"));
assert(1024.0 * 1024.0 == unit_atof("1M"));
assert(4.0 * 1024.0 * 1024.0 * 1024.0 == unit_atof("4G"));
assert(1000.0 * 0.5 == unit_atof("0.5k"));
assert(1000.0 == unit_atof("1k"));
assert(1000.0 * 1000.0 == unit_atof("1m"));
assert(4.0 * 1000.0 * 1000.0 * 1000.0 == unit_atof("4g"));
assert(1024 * 0.5 == unit_atoi("0.5K"));
assert(1024 == unit_atoi("1K"));
assert(1024 * 1024 == unit_atoi("1M"));
d = 4.0 * 1024 * 1024 * 1024;
llu = (iperf_size_t) d;
assert(llu == unit_atoi("4G"));
assert(1000 * 0.5 == unit_atoi("0.5k"));
assert(1000 == unit_atoi("1k"));
assert(1000 * 1000 == unit_atoi("1m"));
d = 4.0 * 1000 * 1000 * 1000;
llu = (iperf_size_t) d;
assert(llu == unit_atoi("4g"));
unit_snprintf(s, 11, 1024.0, 'A');
assert(strncmp(s, "1.00 KByte", 11) == 0);
unit_snprintf(s, 11, 1024.0 * 1024.0, 'A');
assert(strncmp(s, "1.00 MByte", 11) == 0);
unit_snprintf(s, 11, 1000.0, 'k');
assert(strncmp(s, "8.00 Kbit", 11) == 0);
unit_snprintf(s, 11, 1000.0 * 1000.0, 'a');
assert(strncmp(s, "8.00 Mbit", 11) == 0);
d = 4.0 * 1024 * 1024 * 1024;
unit_snprintf(s, 11, d, 'A');
assert(strncmp(s, "4.00 GByte", 11) == 0);
unit_snprintf(s, 11, d, 'a');
assert(strncmp(s, "34.4 Gbit", 11) == 0);
return 0;
}
| zz1126wnx-iperf3 | src/t_units.c | C | bsd | 1,980 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
/* iperf_util.c
*
* Iperf utility functions
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/time.h>
#include <time.h>
#include <errno.h>
#include "config.h"
#include "cjson.h"
/* make_cookie
*
* Generate and return a cookie string
*
* Iperf uses this function to create test "cookies" which
* server as unique test identifiers. These cookies are also
* used for the authentication of stream connections.
*/
void
make_cookie(char *cookie)
{
static int randomized = 0;
char hostname[500];
struct timeval tv;
char temp[1000];
if ( ! randomized )
srandom((int) time(0) ^ getpid());
/* Generate a string based on hostname, time, randomness, and filler. */
(void) gethostname(hostname, sizeof(hostname));
(void) gettimeofday(&tv, 0);
(void) snprintf(temp, sizeof(temp), "%s.%ld.%06ld.%08lx%08lx.%s", hostname, (unsigned long int) tv.tv_sec, (unsigned long int) tv.tv_usec, (unsigned long int) random(), (unsigned long int) random(), "1234567890123456789012345678901234567890");
/* Now truncate it to 36 bytes and terminate. */
memcpy(cookie, temp, 36);
cookie[36] = '\0';
}
/* is_closed
*
* Test if the file descriptor fd is closed.
*
* Iperf uses this function to test whether a TCP stream socket
* is closed, because accepting and denying an invalid connection
* in iperf_tcp_accept is not considered an error.
*/
int
is_closed(int fd)
{
struct timeval tv;
fd_set readset;
FD_ZERO(&readset);
FD_SET(fd, &readset);
tv.tv_sec = 0;
tv.tv_usec = 0;
if (select(fd+1, &readset, NULL, NULL, &tv) < 0) {
if (errno == EBADF)
return 1;
}
return 0;
}
double
timeval_to_double(struct timeval * tv)
{
double d;
d = tv->tv_sec + tv->tv_usec / 1000000;
return d;
}
int
timeval_equals(struct timeval * tv0, struct timeval * tv1)
{
if ( tv0->tv_sec == tv1->tv_sec && tv0->tv_usec == tv1->tv_usec )
return 1;
else
return 0;
}
double
timeval_diff(struct timeval * tv0, struct timeval * tv1)
{
double time1, time2;
time1 = tv0->tv_sec + (tv0->tv_usec / 1000000.0);
time2 = tv1->tv_sec + (tv1->tv_usec / 1000000.0);
time1 = time1 - time2;
if (time1 < 0)
time1 = -time1;
return time1;
}
int
delay(int64_t ns)
{
struct timespec req, rem;
req.tv_sec = 0;
while (ns >= 1000000000L) {
ns -= 1000000000L;
req.tv_sec += 1;
}
req.tv_nsec = ns;
while (nanosleep(&req, &rem) == -1)
if (EINTR == errno)
memcpy(&req, &rem, sizeof rem);
else
return -1;
return 0;
}
# ifdef DELAY_SELECT_METHOD
int
delay(int us)
{
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = us;
(void) select(1, (fd_set *) 0, (fd_set *) 0, (fd_set *) 0, &tv);
return 1;
}
#endif
void
cpu_util(double *pcpu)
{
static struct timeval last;
static clock_t clast;
struct timeval temp;
clock_t ctemp;
double timediff;
if (pcpu == NULL) {
gettimeofday(&last, NULL);
clast = clock();
return;
}
gettimeofday(&temp, NULL);
ctemp = clock();
timediff = ((temp.tv_sec * 1000000.0 + temp.tv_usec) -
(last.tv_sec * 1000000.0 + last.tv_usec));
*pcpu = ((ctemp - clast) / timediff) * 100;
}
char*
get_system_info(void)
{
FILE* fp;
static char buf[1000];
fp = popen("uname -a", "r");
if (fp == NULL)
return NULL;
fgets(buf, sizeof(buf), fp);
pclose(fp);
return buf;
}
/* Helper routine for building cJSON objects in a printf-like manner.
**
** Sample call:
** j = iperf_json_printf("foo: %b bar: %d bletch: %f eep: %s", b, i, f, s);
**
** The four formatting characters and the types they expect are:
** %b boolean int
** %d integer int64_t
** %f floating point double
** %s string char *
** If the values you're passing in are not these exact types, you must
** cast them, there is no automatic type coercion/widening here.
**
** The colons mark the end of field names, and blanks are ignored.
**
** This routine is not particularly robust, but it's not part of the API,
** it's just for internal iperf3 use.
*/
cJSON*
iperf_json_printf(const char *format, ...)
{
cJSON* o;
va_list argp;
const char *cp;
char name[100];
char* np;
cJSON* j;
o = cJSON_CreateObject();
if (o == NULL)
return NULL;
va_start(argp, format);
np = name;
for (cp = format; *cp != '\0'; ++cp) {
switch (*cp) {
case ' ':
break;
case ':':
*np = '\0';
break;
case '%':
++cp;
switch (*cp) {
case 'b':
j = cJSON_CreateBool(va_arg(argp, int));
break;
case 'd':
j = cJSON_CreateInt(va_arg(argp, int64_t));
break;
case 'f':
j = cJSON_CreateFloat(va_arg(argp, double));
break;
case 's':
j = cJSON_CreateString(va_arg(argp, char *));
break;
default:
return NULL;
}
if (j == NULL)
return NULL;
cJSON_AddItemToObject(o, name, j);
np = name;
break;
default:
*np++ = *cp;
break;
}
}
va_end(argp);
return o;
}
| zz1126wnx-iperf3 | src/iperf_util.c | C | bsd | 5,616 |
/*---------------------------------------------------------------
* Copyright (c) 1999,2000,2001,2002,2003
* The Board of Trustees of the University of Illinois
* All Rights Reserved.
*---------------------------------------------------------------
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software (Iperf) and associated
* documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
*
* Redistributions of source code must retain the above
* copyright notice, this list of conditions and
* the following disclaimers.
*
*
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimers in the documentation and/or other materials
* provided with the distribution.
*
*
* Neither the names of the University of Illinois, NCSA,
* nor the names of its contributors may be used to endorse
* or promote products derived from this Software without
* specific prior written permission.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE CONTIBUTORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
* ________________________________________________________________
* National Laboratory for Applied Network Research
* National Center for Supercomputing Applications
* University of Illinois at Urbana-Champaign
* http://www.ncsa.uiuc.edu
* ________________________________________________________________
*
* tcp_window_size.c
* by Mark Gates <mgates@nlanr.net>
* -------------------------------------------------------------------
* set/getsockopt
* ------------------------------------------------------------------- */
/*
* imported into iperfjd branch: 3 Feb 2009 jdugan
*
* made variable names more sane
* removed some cruft
*/
#include <stdio.h>
#include <sys/socket.h>
#include <assert.h>
/* -------------------------------------------------------------------
* If bufsize > 0, set the TCP window size (via the socket buffer
* sizes) for sock. Otherwise leave it as the system default.
*
* This must be called prior to calling listen() or connect() on
* the socket, for TCP window sizes > 64 KB to be effective.
*
* This now works on UNICOS also, by setting TCP_WINSHIFT.
* This now works on AIX, by enabling RFC1323.
* returns -1 on error, 0 on no error.
* -------------------------------------------------------------------
*/
int
set_tcp_windowsize(int sock, int bufsize, int dir)
{
int rc;
int newbufsize;
assert(sock >= 0);
if (bufsize > 0)
{
/*
* note: results are verified after connect() or listen(), since
* some OS's don't show the corrected value until then.
*/
// printf("Setting TCP buffer to size: %d\n", bufsize);
newbufsize = bufsize;
rc = setsockopt(sock, SOL_SOCKET, dir, (char *) &newbufsize, sizeof newbufsize);
if (rc < 0)
return rc;
} else {
// printf(" Using default TCP buffer size and assuming OS will do autotuning\n");
}
return 0;
}
/* -------------------------------------------------------------------
* returns the TCP window size (on the sending buffer, SO_SNDBUF),
* or -1 on error.
* ------------------------------------------------------------------- */
int
get_tcp_windowsize(int sock, int dir)
{
int bufsize = 0;
int rc;
socklen_t len;
/* send buffer -- query for buffer size */
len = sizeof bufsize;
rc = getsockopt(sock, SOL_SOCKET, dir, (char *) &bufsize, &len);
if (rc < 0)
return rc;
return bufsize;
}
| zz1126wnx-iperf3 | src/tcp_window_size.c | C | bsd | 4,234 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include "timer.h"
static int flag;
static void
timer_proc( TimerClientData client_data, struct timeval* nowP )
{
flag = 1;
}
int
main(int argc, char **argv)
{
struct Timer *tp;
flag = 0;
tp = tmr_create((struct timeval*) 0, timer_proc, JunkClientData, 3000000, 0);
sleep(2);
tmr_run((struct timeval*) 0);
if (flag)
{
printf("timer should not have expired\n");
exit(-1);
}
sleep(1);
tmr_run((struct timeval*) 0);
if (!flag)
{
printf("timer should have expired\n");
exit(-2);
}
tmr_destroy();
exit(0);
}
| zz1126wnx-iperf3 | src/t_timer.c | C | bsd | 1,006 |
lib_LIBRARIES = libiperf.a # Build and install a static iperf library
bin_PROGRAMS = iperf3 # Build and install an iperf binary
noinst_PROGRAMS = t_timer t_units t_uuid iperf3_profile # Build, but don't install the test programs and a profiled version of iperf3
include_HEADERS = iperf_api.h # Defines the headers that get installed with the program
# Specify the source files and flags for the iperf library
libiperf_a_SOURCES = \
cjson.c \
cjson.h \
iperf.h \
iperf_api.c \
iperf_api.h \
iperf_error.c \
iperf_client_api.c \
iperf_server_api.c \
iperf_tcp.c \
iperf_tcp.h \
iperf_udp.c \
iperf_udp.h \
iperf_util.c \
iperf_util.h \
locale.c \
locale.h \
net.c \
net.h \
tcp_info.c \
tcp_window_size.c \
tcp_window_size.h \
timer.c \
timer.h \
units.c \
units.h \
version.h
# Specify the sources and various flags for the iperf binary
iperf3_SOURCES = main.c
iperf3_CFLAGS = -g -Wall
iperf3_LDADD = libiperf.a
iperf3_LDFLAGS = -g
# Specify the sources and various flags for the profiled iperf binary. This
# binary recompiles all the source files to make sure they are all profiled.
iperf3_profile_SOURCES = main.c \
$(libiperf_a_SOURCES)
iperf3_profile_CFLAGS = -pg -g -Wall
iperf3_profile_LDADD = libiperf.a
iperf3_profile_LDFLAGS = -pg -g
# Specify the sources and various flags for the test cases
t_timer_SOURCES = t_timer.c
t_timer_CFLAGS = -g -Wall
t_timer_LDFLAGS = iperf_error.o
t_timer_LDADD = libiperf.a
t_units_SOURCES = t_units.c
t_units_CFLAGS = -g -Wall
t_units_LDFLAGS =
t_units_LDADD = libiperf.a
t_uuid_SOURCES = t_uuid.c
t_uuid_CFLAGS = -g -Wall
t_uuid_LDFLAGS =
t_uuid_LDADD = libiperf.a
# Specify which tests to run during a "make check"
TESTS = \
t_timer \
t_units \
t_uuid
dist_man_MANS = iperf3.1 libiperf.3
| zz1126wnx-iperf3 | src/Makefile.am | Makefile | bsd | 2,734 |
.TH IPERF 1 "July 2010" ESnet "User Manuals"
.SH NAME
iperf3 \- perform network throughput tests
.SH SYNOPSIS
.B iperf3 -s [
.I options
.B ]
.br
.B iperf3 -c
.I server
.B [
.I options
.B ]
.SH DESCRIPTION
iperf3 is a tool for performing network throughput measurements. It can test
either TCP or UDP throughput. To perform an iperf3 test the user must
establish both a server and a client.
.SH "GENERAL OPTIONS"
.TP
.BR -p ", " --port " \fIn\fR"
set server port to listen on/connect to to \fIn\fR (default 5201)
.TP
.BR -f ", " --format " "
[kmKM] format to report: Kbits, Mbits, KBytes, MBytes
.TP
.BR -i ", " --interval " \fIn\fR"
pause \fIn\fR seconds between periodic bandwidth reports
.TP
.BR -V ", " --verbose " "
give more detailed output
.TP
.BR -J ", " --json " "
output in JSON format
.TP
.BR -d ", " --debug " "
debug mode
.TP
.BR -v ", " --version " "
show version information and quit
.TP
.BR -h ", " --help " "
show a help synopsis
.SH "SERVER SPECIFIC OPTIONS"
.TP
.BR -s ", " --server " "
run in server mode
.SH "CLIENT SPECIFIC OPTIONS"
.TP
.BR -c ", " --client " \fIhost\fR"
run in client mode, connecting to the specified server
.TP
.BR -u ", " --udp
use UDP rather than TCP
.TP
.BR -b ", " --bandwidth " \fIn\fR[KM]"
set target bandwidth to \fIn\fR bits/sec (default 1 Mbit/sec). Requires UDP mode (-u)
.TP
.BR -t ", " --time " \fIn\fR"
time in seconds to transmit for (default 10 secs)
.TP
.BR -n ", " --bytes " \fIn\fR[KM]"
number of bytes to transmit (instead of -t)
.TP
.BR -l ", " --length " \fIn\fR[KM]"
length of buffer to read or write (default 128 KB for TCP, 8KB for UDP)
.TP
.BR -P ", " --parallel " \fIn\fR"
number of parallel client streams to run
.TP
.BR -R ", " --reverse
run in reverse mode (server sends, client receives)
.TP
.BR -w ", " --window " \fIn\fR[KM]"
TCP window size (socket buffer size)
.TP
.BR -B ", " --bind " \fIn\fR[KM]"
bind to a specific interface or multicast address
.TP
.BR -M ", " --set-mss " \fIn\fR"
set TCP maximum segment size (MTU - 40 bytes)
.TP
.BR -N ", " --no-delay " "
set TCP no delay, disabling Nagle's Algorithm
.TP
.BR -4 ", " --version4 " "
only use IPv4
.TP
.BR -6 ", " --version6 " "
only use IPv6
.TP
.BR -S ", " --tos " \fIn\fR"
set the IP 'type of service'
.TP
.BR -Z ", " --zerocopy " "
Use a "zero copy" method of sending data, such as sendfile(2),
instead of the usual write(2).
.SH AUTHORS
Iperf was originally written by Mark Gates and Alex Warshavsky.
Man page and maintence by Jon Dugan <jdugan at x1024 dot net>.
Other contributions from Ajay Tirumala, Jim Ferguson,
Feng Qin,
Kevin Gibbs,
John Estabrook <jestabro at ncsa.uiuc.edu>,
Andrew Gallatin <gallatin at gmail.com>,
Stephen Hemminger <shemminger at linux-foundation.org>
.SH "SEE ALSO"
libiperf(3),
http://code.google.com/p/iperf/
| zz1126wnx-iperf3 | src/iperf3.1 | Roff Manpage | bsd | 2,789 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*
* Based on timers.c by Jef Poskanzer. Used with permission.
*/
#include <sys/types.h>
#include <stdlib.h>
#include "timer.h"
static Timer* timers = NULL;
static Timer* free_timers = NULL;
TimerClientData JunkClientData;
/* This is an efficiency tweak. All the routines that need to know the
** current time get passed a pointer to a struct timeval. If it's non-NULL
** it gets used, otherwise we do our own gettimeofday() to fill it in.
** This lets the caller avoid extraneous gettimeofday()s when efficiency
** is needed, and not bother with the extra code when efficiency doesn't
** matter too much.
*/
static void
getnow( struct timeval* nowP, struct timeval* nowP2 )
{
if ( nowP != NULL )
*nowP2 = *nowP;
else
(void) gettimeofday( nowP2, NULL );
}
static void
list_add( Timer* t )
{
Timer* t2;
Timer* t2prev;
if ( timers == NULL ) {
/* The list is empty. */
timers = t;
t->prev = t->next = NULL;
} else {
if ( t->time.tv_sec < timers->time.tv_sec ||
( t->time.tv_sec == timers->time.tv_sec &&
t->time.tv_usec < timers->time.tv_usec ) ) {
/* The new timer goes at the head of the list. */
t->prev = NULL;
t->next = timers;
timers->prev = t;
timers = t;
} else {
/* Walk the list to find the insertion point. */
for ( t2prev = timers, t2 = timers->next; t2 != NULL;
t2prev = t2, t2 = t2->next ) {
if ( t->time.tv_sec < t2->time.tv_sec ||
( t->time.tv_sec == t2->time.tv_sec &&
t->time.tv_usec < t2->time.tv_usec ) ) {
/* Found it. */
t2prev->next = t;
t->prev = t2prev;
t->next = t2;
t2->prev = t;
return;
}
}
/* Oops, got to the end of the list. Add to tail. */
t2prev->next = t;
t->prev = t2prev;
t->next = NULL;
}
}
}
static void
list_remove( Timer* t )
{
if ( t->prev == NULL )
timers = t->next;
else
t->prev->next = t->next;
if ( t->next != NULL )
t->next->prev = t->prev;
}
static void
list_resort( Timer* t )
{
/* Remove the timer from the list. */
list_remove( t );
/* And add it back in, sorted correctly. */
list_add( t );
}
static void
add_usecs( struct timeval* t, int64_t usecs )
{
t->tv_sec += usecs / 1000000L;
t->tv_usec += usecs % 1000000L;
if ( t->tv_usec >= 1000000L ) {
t->tv_sec += t->tv_usec / 1000000L;
t->tv_usec %= 1000000L;
}
}
Timer*
tmr_create(
struct timeval* nowP, TimerProc* timer_proc, TimerClientData client_data,
int64_t usecs, int periodic )
{
struct timeval now;
Timer* t;
getnow( nowP, &now );
if ( free_timers != NULL ) {
t = free_timers;
free_timers = t->next;
} else {
t = (Timer*) malloc( sizeof(Timer) );
if ( t == NULL )
return NULL;
}
t->timer_proc = timer_proc;
t->client_data = client_data;
t->usecs = usecs;
t->periodic = periodic;
t->time = now;
add_usecs( &t->time, usecs );
/* Add the new timer to the active list. */
list_add( t );
return t;
}
struct timeval*
tmr_timeout( struct timeval* nowP )
{
struct timeval now;
int64_t usecs;
static struct timeval timeout;
getnow( nowP, &now );
/* Since the list is sorted, we only need to look at the first timer. */
if ( timers == NULL )
return NULL;
usecs = ( timers->time.tv_sec - now.tv_sec ) * 1000000LL +
( timers->time.tv_usec - now.tv_usec );
if ( usecs <= 0 )
usecs = 0;
timeout.tv_sec = usecs / 1000000LL;
timeout.tv_usec = usecs % 1000000LL;
return &timeout;
}
void
tmr_run( struct timeval* nowP )
{
struct timeval now;
Timer* t;
Timer* next;
getnow( nowP, &now );
for ( t = timers; t != NULL; t = next ) {
next = t->next;
/* Since the list is sorted, as soon as we find a timer
** that isn't ready yet, we are done.
*/
if ( t->time.tv_sec > now.tv_sec ||
( t->time.tv_sec == now.tv_sec &&
t->time.tv_usec > now.tv_usec ) )
break;
(t->timer_proc)( t->client_data, &now );
if ( t->periodic ) {
/* Reschedule. */
add_usecs( &t->time, t->usecs );
list_resort( t );
} else
tmr_cancel( t );
}
}
void
tmr_reset( struct timeval* nowP, Timer* t )
{
struct timeval now;
getnow( nowP, &now );
t->time = now;
add_usecs( &t->time, t->usecs );
list_resort( t );
}
void
tmr_cancel( Timer* t )
{
/* Remove it from the active list. */
list_remove( t );
/* And put it on the free list. */
t->next = free_timers;
free_timers = t;
t->prev = NULL;
}
void
tmr_cleanup( void )
{
Timer* t;
while ( free_timers != NULL ) {
t = free_timers;
free_timers = t->next;
free( (void*) t );
}
}
void
tmr_destroy( void )
{
while ( timers != NULL )
tmr_cancel( timers );
tmr_cleanup();
}
| zz1126wnx-iperf3 | src/timer.c | C | bsd | 5,133 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#ifndef __NET_H
#define __NET_H
int netdial(int domain, int proto, char *local, char *server, int port);
int netannounce(int domain, int proto, char *local, int port);
int Nread(int fd, char *buf, size_t count, int prot);
int Nwrite(int fd, const char *buf, size_t count, int prot) /* __attribute__((hot)) */;
int has_sendfile(void);
int Nsendfile(int fromfd, int tofd, const char *buf, size_t count) /* __attribute__((hot)) */;
int getsock_tcp_mss(int inSock);
int set_tcp_options(int sock, int no_delay, int mss);
int setnonblocking(int fd, int nonblocking);
int getsockdomain(int sock);
#define NET_SOFTERROR -1
#define NET_HARDERROR -2
unsigned long long htonll(unsigned long long);
unsigned long long ntohll(unsigned long long);
/* XXX: Need a better check for byte order */
#if BYTE_ORDER == BIG_ENDIAN
#define HTONLL(n) (n)
#define NTOHLL(n) (n)
#else
#define HTONLL(n) ((((unsigned long long)(n) & 0xFF) << 56) | \
(((unsigned long long)(n) & 0xFF00) << 40) | \
(((unsigned long long)(n) & 0xFF0000) << 24) | \
(((unsigned long long)(n) & 0xFF000000) << 8) | \
(((unsigned long long)(n) & 0xFF00000000) >> 8) | \
(((unsigned long long)(n) & 0xFF0000000000) >> 24) | \
(((unsigned long long)(n) & 0xFF000000000000) >> 40) | \
(((unsigned long long)(n) & 0xFF00000000000000) >> 56))
#define NTOHLL(n) ((((unsigned long long)(n) & 0xFF) << 56) | \
(((unsigned long long)(n) & 0xFF00) << 40) | \
(((unsigned long long)(n) & 0xFF0000) << 24) | \
(((unsigned long long)(n) & 0xFF000000) << 8) | \
(((unsigned long long)(n) & 0xFF00000000) >> 8) | \
(((unsigned long long)(n) & 0xFF0000000000) >> 24) | \
(((unsigned long long)(n) & 0xFF000000000000) >> 40) | \
(((unsigned long long)(n) & 0xFF00000000000000) >> 56))
#endif
#define htonll(n) HTONLL(n)
#define ntohll(n) NTOHLL(n)
#endif
| zz1126wnx-iperf3 | src/net.h | C | bsd | 2,403 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*
* Based on timers.h by Jef Poskanzer. Used with permission.
*/
#ifndef __TIMER_H
#define __TIMER_H
#include <sys/time.h>
/* TimerClientData is an opaque value that tags along with a timer. The
** client can use it for whatever, and it gets passed to the callback when
** the timer triggers.
*/
typedef union
{
void* p;
int i;
long l;
} TimerClientData;
extern TimerClientData JunkClientData; /* for use when you don't care */
/* The TimerProc gets called when the timer expires. It gets passed
** the TimerClientData associated with the timer, and a timeval in case
** it wants to schedule another timer.
*/
typedef void TimerProc( TimerClientData client_data, struct timeval* nowP );
/* The Timer struct. */
typedef struct TimerStruct
{
TimerProc* timer_proc;
TimerClientData client_data;
int64_t usecs;
int periodic;
struct timeval time;
struct TimerStruct* prev;
struct TimerStruct* next;
int hash;
} Timer;
/* Set up a timer, either periodic or one-shot. Returns (Timer*) 0 on errors. */
extern Timer* tmr_create(
struct timeval* nowP, TimerProc* timer_proc, TimerClientData client_data,
int64_t usecs, int periodic );
/* Returns a timeout indicating how long until the next timer triggers. You
** can just put the call to this routine right in your select(). Returns
** (struct timeval*) 0 if no timers are pending.
*/
extern struct timeval* tmr_timeout( struct timeval* nowP ) /* __attribute__((hot)) */;
/* Run the list of timers. Your main program needs to call this every so often,
** or as indicated by tmr_timeout().
*/
extern void tmr_run( struct timeval* nowP ) /* __attribute__((hot)) */;
/* Reset the clock on a timer, to current time plus the original timeout. */
extern void tmr_reset( struct timeval* nowP, Timer* timer );
/* Deschedule a timer. Note that non-periodic timers are automatically
** descheduled when they run, so you don't have to call this on them.
*/
extern void tmr_cancel( Timer* timer );
/* Clean up the timers package, freeing any unused storage. */
extern void tmr_cleanup( void );
/* Cancel all timers and free storage, usually in preparation for exitting. */
extern void tmr_destroy( void );
#endif /* __TIMER_H */
| zz1126wnx-iperf3 | src/timer.h | C | bsd | 2,568 |
/*
Copyright (c) 2009 Dave Gamble
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON__h
#define cJSON__h
#ifdef __cplusplus
extern "C"
{
#endif
/* cJSON Types: */
#define cJSON_False 0
#define cJSON_True 1
#define cJSON_NULL 2
#define cJSON_Number 3
#define cJSON_String 4
#define cJSON_Array 5
#define cJSON_Object 6
#define cJSON_IsReference 256
/* The cJSON structure: */
typedef struct cJSON {
struct cJSON *next, *prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
int type; /* The type of the item, as above. */
char *valuestring; /* The item's string, if type==cJSON_String */
int64_t valueint; /* The item's number, if type==cJSON_Number */
double valuefloat; /* The item's number, if type==cJSON_Number */
char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;
typedef struct cJSON_Hooks {
void *(*malloc_fn)(size_t sz );
void (*free_fn)( void *ptr );
} cJSON_Hooks;
/* Supply malloc, realloc and free functions to cJSON */
extern void cJSON_InitHooks( cJSON_Hooks* hooks );
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse( const char *value );
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
extern char *cJSON_Print( cJSON *item );
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char *cJSON_PrintUnformatted( cJSON *item );
/* Delete a cJSON entity and all subentities. */
extern void cJSON_Delete( cJSON *c );
/* Returns the number of items in an array (or object). */
extern int cJSON_GetArraySize( cJSON *array );
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem( cJSON *array, int item );
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem( cJSON *object, const char *string );
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
extern const char *cJSON_GetErrorPtr( void );
/* These calls create a cJSON item of the appropriate type. */
extern cJSON *cJSON_CreateNull( void );
extern cJSON *cJSON_CreateTrue( void );
extern cJSON *cJSON_CreateFalse( void );
extern cJSON *cJSON_CreateBool( int b );
extern cJSON *cJSON_CreateInt( int64_t num );
extern cJSON *cJSON_CreateFloat( double num );
extern cJSON *cJSON_CreateString( const char *string );
extern cJSON *cJSON_CreateArray( void );
extern cJSON *cJSON_CreateObject( void );
/* These utilities create an Array of count items. */
extern cJSON *cJSON_CreateIntArray( int64_t *numbers, int count );
extern cJSON *cJSON_CreateFloatArray( double *numbers, int count );
extern cJSON *cJSON_CreateStringArray( const char **strings, int count );
/* Append item to the specified array/object. */
extern void cJSON_AddItemToArray( cJSON *array, cJSON *item );
extern void cJSON_AddItemToObject( cJSON *object, const char *string, cJSON *item );
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
extern void cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item );
extern void cJSON_AddItemReferenceToObject( cJSON *object, const char *string, cJSON *item );
/* Remove/Detatch items from Arrays/Objects. */
extern cJSON *cJSON_DetachItemFromArray( cJSON *array, int which );
extern void cJSON_DeleteItemFromArray( cJSON *array, int which );
extern cJSON *cJSON_DetachItemFromObject( cJSON *object, const char *string );
extern void cJSON_DeleteItemFromObject( cJSON *object, const char *string );
/* Update array items. */
extern void cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *newitem );
extern void cJSON_ReplaceItemInObject( cJSON *object, const char *string, cJSON *newitem );
#define cJSON_AddNullToObject( object, name ) cJSON_AddItemToObject( object, name, cJSON_CreateNull() )
#define cJSON_AddTrueToObject( object, name ) cJSON_AddItemToObject( object, name, cJSON_CreateTrue() )
#define cJSON_AddFalseToObject( object, name ) cJSON_AddItemToObject( object, name, cJSON_CreateFalse() )
#define cJSON_AddIntToObject( object, name, n ) cJSON_AddItemToObject( object, name, cJSON_CreateInt( n ) )
#define cJSON_AddFloatToObject( object, name, n ) cJSON_AddItemToObject( object, name, cJSON_CreateFloat( n ) )
#define cJSON_AddStringToObject( object, name, s ) cJSON_AddItemToObject( object, name, cJSON_CreateString( s ) )
#ifdef __cplusplus
}
#endif
#endif
| zz1126wnx-iperf3 | src/cjson.h | C | bsd | 5,993 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#ifndef IPERF_TCP_H
#define IPERF_TCP_H
/**
* iperf_tcp_accept -- accepts a new TCP connection
* on tcp_listener_socket for TCP data and param/result
* exchange messages
*returns 0 on success
*
*/
int iperf_tcp_accept(struct iperf_test *);
/**
* iperf_tcp_recv -- receives the data for TCP
* and the Param/result message exchange
*returns state of packet received
*
*/
int iperf_tcp_recv(struct iperf_stream *);
/**
* iperf_tcp_send -- sends the client data for TCP
* and the Param/result message exchanges
* returns: bytes sent
*
*/
int iperf_tcp_send(struct iperf_stream *) /* __attribute__((hot)) */;
int iperf_tcp_listen(struct iperf_test *);
int iperf_tcp_connect(struct iperf_test *);
#endif
| zz1126wnx-iperf3 | src/iperf_tcp.h | C | bsd | 1,080 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#define IPERF_VERSION "3.0-BETA5"
#define IPERF_VERSION_DATE "28 March 2013"
| zz1126wnx-iperf3 | src/version.h | C | bsd | 418 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <assert.h>
#include <netdb.h>
#include <string.h>
#include <sys/fcntl.h>
#ifdef linux
#include <sys/sendfile.h>
#else
#ifdef __FreeBSD__
#include <sys/uio.h>
#else
#if defined(__APPLE__) && defined(__MACH__) /* OS X */
#include <sys/uio.h>
#endif
#endif
#endif
#include "iperf_util.h"
#include "net.h"
#include "timer.h"
/* netdial and netannouce code comes from libtask: http://swtch.com/libtask/
* Copyright: http://swtch.com/libtask/COPYRIGHT
*/
/* make connection to server */
int
netdial(int domain, int proto, char *local, char *server, int port)
{
struct addrinfo hints, *local_res, *server_res;
int s;
if (local) {
memset(&hints, 0, sizeof(hints));
hints.ai_family = domain;
hints.ai_socktype = proto;
if (getaddrinfo(local, NULL, &hints, &local_res) != 0)
return -1;
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = domain;
hints.ai_socktype = proto;
if (getaddrinfo(server, NULL, &hints, &server_res) != 0)
return -1;
s = socket(server_res->ai_family, proto, 0);
if (s < 0)
return -1;
if (local) {
if (bind(s, (struct sockaddr *) local_res->ai_addr, local_res->ai_addrlen) < 0)
return -1;
freeaddrinfo(local_res);
}
((struct sockaddr_in *) server_res->ai_addr)->sin_port = htons(port);
if (connect(s, (struct sockaddr *) server_res->ai_addr, server_res->ai_addrlen) < 0 && errno != EINPROGRESS)
return -1;
freeaddrinfo(server_res);
return s;
}
/***************************************************************/
int
netannounce(int domain, int proto, char *local, int port)
{
struct addrinfo hints, *res;
char portstr[6];
int s, opt;
snprintf(portstr, 6, "%d", port);
memset(&hints, 0, sizeof(hints));
hints.ai_family = (domain == AF_UNSPEC ? AF_INET6 : domain);
hints.ai_socktype = proto;
hints.ai_flags = AI_PASSIVE;
if (getaddrinfo(local, portstr, &hints, &res) != 0)
return -1;
s = socket(res->ai_family, proto, 0);
if (s < 0)
return -1;
opt = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *) &opt, sizeof(opt));
if (domain == AF_UNSPEC || domain == AF_INET6) {
if (domain == AF_UNSPEC)
opt = 0;
else if (domain == AF_INET6)
opt = 1;
setsockopt(s, SOL_SOCKET, IPV6_V6ONLY, (char *) &opt, sizeof(opt));
}
if (bind(s, (struct sockaddr *) res->ai_addr, res->ai_addrlen) < 0) {
close(s);
return -1;
}
freeaddrinfo(res);
if (proto == SOCK_STREAM) {
if (listen(s, 5) < 0) {
return -1;
}
}
return s;
}
/*******************************************************************/
/* reads 'count' bytes from a socket */
/********************************************************************/
int
Nread(int fd, char *buf, size_t count, int prot)
{
register ssize_t r;
register size_t nleft = count;
while (nleft > 0) {
r = read(fd, buf, nleft);
if (r < 0) {
if (errno == EINTR)
r = 0;
else
return NET_HARDERROR;
} else if (r == 0)
break;
nleft -= r;
buf += r;
}
return count - nleft;
}
/*
* N W R I T E
*/
int
Nwrite(int fd, const char *buf, size_t count, int prot)
{
register ssize_t r;
register size_t nleft = count;
while (nleft > 0) {
r = write(fd, buf, nleft);
if (r < 0) {
switch (errno) {
case EINTR:
return count - nleft;
case EAGAIN:
case ENOBUFS:
return NET_SOFTERROR;
default:
return NET_HARDERROR;
}
} else if (r == 0)
return NET_SOFTERROR;
nleft -= r;
buf += r;
}
return count;
}
int
has_sendfile(void)
{
#ifdef linux
return 1;
#else
#ifdef __FreeBSD__
return 1;
#else
#if defined(__APPLE__) && defined(__MACH__) /* OS X */
return 1;
#else
return 0;
#endif
#endif
#endif
}
/*
* N S E N D F I L E
*/
int
Nsendfile(int fromfd, int tofd, const char *buf, size_t count)
{
off_t offset;
#if defined(__FreeBSD__) || (defined(__APPLE__) && defined(__MACH__))
off_t sent;
#endif
register size_t nleft;
register ssize_t r;
nleft = count;
while (nleft > 0) {
offset = count - nleft;
#ifdef linux
r = sendfile(tofd, fromfd, &offset, nleft);
#else
#ifdef __FreeBSD__
r = sendfile(fromfd, tofd, offset, nleft, NULL, &sent, 0);
if (r == 0)
r = sent;
#else
#if defined(__APPLE__) && defined(__MACH__) /* OS X */
sent = nleft;
r = sendfile(fromfd, tofd, offset, &sent, NULL, 0);
if (r == 0)
r = sent;
#else
/* Shouldn't happen. */
r = -1;
errno = ENOSYS;
#endif
#endif
#endif
if (r < 0) {
switch (errno) {
case EINTR:
return count - nleft;
case EAGAIN:
case ENOBUFS:
case ENOMEM:
return NET_SOFTERROR;
default:
return NET_HARDERROR;
}
} else if (r == 0)
return NET_SOFTERROR;
nleft -= r;
}
return count;
}
/*************************************************************************/
/**
* getsock_tcp_mss - Returns the MSS size for TCP
*
*/
int
getsock_tcp_mss(int inSock)
{
int mss = 0;
int rc;
socklen_t len;
assert(inSock >= 0); /* print error and exit if this is not true */
/* query for mss */
len = sizeof(mss);
rc = getsockopt(inSock, IPPROTO_TCP, TCP_MAXSEG, (char *)&mss, &len);
return mss;
}
/*************************************************************/
/* sets TCP_NODELAY and TCP_MAXSEG if requested */
// XXX: This function is not being used.
int
set_tcp_options(int sock, int no_delay, int mss)
{
socklen_t len;
int rc;
int new_mss;
if (no_delay == 1) {
len = sizeof(no_delay);
rc = setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&no_delay, len);
if (rc == -1) {
perror("TCP_NODELAY");
return -1;
}
}
#ifdef TCP_MAXSEG
if (mss > 0) {
len = sizeof(new_mss);
assert(sock != -1);
/* set */
new_mss = mss;
len = sizeof(new_mss);
rc = setsockopt(sock, IPPROTO_TCP, TCP_MAXSEG, (char *)&new_mss, len);
if (rc == -1) {
perror("setsockopt");
return -1;
}
/* verify results */
rc = getsockopt(sock, IPPROTO_TCP, TCP_MAXSEG, (char *)&new_mss, &len);
if (new_mss != mss) {
perror("setsockopt value mismatch");
return -1;
}
}
#endif
return 0;
}
/****************************************************************************/
int
setnonblocking(int fd, int nonblocking)
{
int flags, newflags;
flags = fcntl(fd, F_GETFL, 0);
if (flags < 0) {
perror("fcntl(F_GETFL)");
return -1;
}
if (nonblocking)
newflags = flags | (int) O_NONBLOCK;
else
newflags = flags & ~((int) O_NONBLOCK);
if (newflags != flags)
if (fcntl(fd, F_SETFL, newflags) < 0) {
perror("fcntl(F_SETFL)");
return -1;
}
return 0;
}
/****************************************************************************/
int
getsockdomain(int sock)
{
struct sockaddr sa;
socklen_t len;
if (getsockname(sock, &sa, &len) < 0)
return -1;
return sa.sa_family;
}
| zz1126wnx-iperf3 | src/net.c | C | bsd | 7,829 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#include <errno.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/uio.h>
#include <arpa/inet.h>
#include "iperf.h"
#include "iperf_api.h"
#include "iperf_util.h"
#include "locale.h"
#include "net.h"
#include "timer.h"
int
iperf_create_streams(struct iperf_test *test)
{
int i, s;
struct iperf_stream *sp;
for (i = 0; i < test->num_streams; ++i) {
if ((s = test->protocol->connect(test)) < 0)
return -1;
FD_SET(s, &test->read_set);
FD_SET(s, &test->write_set);
test->max_fd = (test->max_fd < s) ? s : test->max_fd;
sp = iperf_new_stream(test, s);
if (!sp)
return -1;
/* Perform the new stream callback */
if (test->on_new_stream)
test->on_new_stream(sp);
}
return 0;
}
int
iperf_handle_message_client(struct iperf_test *test)
{
int rval, perr;
if ((rval = read(test->ctrl_sck, &test->state, sizeof(char))) <= 0) {
if (rval == 0) {
i_errno = IECTRLCLOSE;
return -1;
} else {
i_errno = IERECVMESSAGE;
return -1;
}
}
switch (test->state) {
case PARAM_EXCHANGE:
if (iperf_exchange_parameters(test) < 0)
return -1;
if (test->on_connect)
test->on_connect(test);
break;
case CREATE_STREAMS:
if (iperf_create_streams(test) < 0)
return -1;
break;
case TEST_START:
if (iperf_init_test(test) < 0)
return -1;
break;
case TEST_RUNNING:
break;
case EXCHANGE_RESULTS:
if (iperf_exchange_results(test) < 0)
return -1;
break;
case DISPLAY_RESULTS:
if (test->on_test_finish)
test->on_test_finish(test);
iperf_client_end(test);
break;
case IPERF_DONE:
break;
case SERVER_TERMINATE:
i_errno = IESERVERTERM;
return -1;
case ACCESS_DENIED:
i_errno = IEACCESSDENIED;
return -1;
case SERVER_ERROR:
if (Nread(test->ctrl_sck, (char*) &i_errno, sizeof(i_errno), Ptcp) < 0) {
i_errno = IECTRLREAD;
return -1;
}
i_errno = ntohl(i_errno);
if (Nread(test->ctrl_sck, (char*) &perr, sizeof(perr), Ptcp) < 0) {
i_errno = IECTRLREAD;
return -1;
}
errno = ntohl(perr);
return -1;
default:
i_errno = IEMESSAGE;
return -1;
}
return 0;
}
/* iperf_connect -- client to server connection function */
int
iperf_connect(struct iperf_test *test)
{
FD_ZERO(&test->read_set);
FD_ZERO(&test->write_set);
make_cookie(test->cookie);
/* Create and connect the control channel */
if (test->ctrl_sck < 0)
test->ctrl_sck = netdial(test->settings->domain, Ptcp, test->bind_address, test->server_hostname, test->server_port);
if (test->ctrl_sck < 0) {
i_errno = IECONNECT;
return -1;
}
if (Nwrite(test->ctrl_sck, test->cookie, COOKIE_SIZE, Ptcp) < 0) {
i_errno = IESENDCOOKIE;
return -1;
}
FD_SET(test->ctrl_sck, &test->read_set);
FD_SET(test->ctrl_sck, &test->write_set);
test->max_fd = (test->ctrl_sck > test->max_fd) ? test->ctrl_sck : test->max_fd;
return 0;
}
int
iperf_client_end(struct iperf_test *test)
{
struct iperf_stream *sp;
/* Close all stream sockets */
SLIST_FOREACH(sp, &test->streams, streams) {
close(sp->socket);
}
/* show final summary */
test->reporter_callback(test);
test->state = IPERF_DONE;
if (Nwrite(test->ctrl_sck, &test->state, sizeof(char), Ptcp) < 0) {
i_errno = IESENDMESSAGE;
return -1;
}
return 0;
}
static int sigalrm_triggered;
static void
sigalrm_handler(int sig)
{
sigalrm_triggered = 1;
}
int
iperf_run_client(struct iperf_test * test)
{
int concurrency_model;
int startup;
#define CM_SELECT 1
#define CM_SIGALRM 2
int result;
fd_set read_set, write_set;
struct timeval now;
if (test->json_output)
if (iperf_json_start(test) < 0)
return -1;
if (test->json_output) {
cJSON_AddItemToObject(test->json_start, "version", cJSON_CreateString(version));
cJSON_AddItemToObject(test->json_start, "system_info", cJSON_CreateString(get_system_info()));
} else if (test->verbose) {
printf("%s\n", version);
system("uname -a");
}
/* Start the client and connect to the server */
if (iperf_connect(test) < 0) {
return -1;
}
/* Begin calculating CPU utilization */
cpu_util(NULL);
startup = 1;
concurrency_model = CM_SELECT; /* always start in select mode */
(void) gettimeofday(&now, NULL);
while (test->state != IPERF_DONE) {
if (concurrency_model == CM_SELECT) {
memcpy(&read_set, &test->read_set, sizeof(fd_set));
memcpy(&write_set, &test->write_set, sizeof(fd_set));
result = select(test->max_fd + 1, &read_set, &write_set, NULL, tmr_timeout(&now));
if (result < 0 && errno != EINTR) {
i_errno = IESELECT;
return -1;
}
if (result > 0) {
if (FD_ISSET(test->ctrl_sck, &read_set)) {
if (iperf_handle_message_client(test) < 0) {
return -1;
}
FD_CLR(test->ctrl_sck, &read_set);
}
}
}
if (test->state == TEST_RUNNING) {
/* Is this our first time in TEST_RUNNING mode? */
if (startup) {
startup = 0;
/* Can we switch to SIGALRM mode? There are a bunch of
** cases where either it won't work or it's ill-advised.
*/
if (test->may_use_sigalrm &&
(test->protocol->id != Pudp || test->settings->rate == 0) &&
(test->stats_interval == 0 || test->stats_interval > 1) &&
(test->reporter_interval == 0 || test->reporter_interval > 1) &&
! test->reverse) {
concurrency_model = CM_SIGALRM;
test->multisend = 1;
signal(SIGALRM, sigalrm_handler);
sigalrm_triggered = 0;
alarm(1);
}
}
if (test->reverse) {
// Reverse mode. Client receives.
if (iperf_recv(test, &read_set) < 0) {
return -1;
}
} else {
// Regular mode. Client sends.
if (iperf_send(test, concurrency_model == CM_SIGALRM ? NULL : &write_set) < 0) {
return -1;
}
}
if (concurrency_model == CM_SELECT ||
(concurrency_model == CM_SIGALRM && sigalrm_triggered)) {
/* Run the timers. */
(void) gettimeofday(&now, NULL);
tmr_run(&now);
if (concurrency_model == CM_SIGALRM) {
sigalrm_triggered = 0;
alarm(1);
}
}
/* Is the test done yet? */
if (test->settings->bytes == 0) {
if (!test->done)
continue; /* not done */
} else {
if (test->bytes_sent < test->settings->bytes)
continue; /* not done */
}
/* Yes, done! Send TEST_END. */
cpu_util(&test->cpu_util);
test->stats_callback(test);
test->state = TEST_END;
if (Nwrite(test->ctrl_sck, &test->state, sizeof(char), Ptcp) < 0) {
i_errno = IESENDMESSAGE;
return -1;
}
/* And if we were doing SIGALRM, go back to select for the end. */
concurrency_model = CM_SELECT;
}
}
if (test->json_output) {
if (iperf_json_finish(test) < 0)
return -1;
} else
printf("\niperf Done.\n");
return 0;
}
| zz1126wnx-iperf3 | src/iperf_client_api.c | C | bsd | 7,942 |
.TH LIBIPERF 3 "March 2013" ESnet "User Manuals"
.SH NAME
libiperf \- API for iperf3 network throughput tester
.SH SYNOPSIS
#include <iperf_api.h>
.br
-liperf
.SH DESCRIPTION
.PP
Libiperf gives you access to all the functionality of the iperf3
network testing tool.
You can build it directly into your own program, instead of having
to run it as a shell command.
.SH CALLS
Initialization / termination:
.nf
struct iperf_test *iperf_new_test();
int iperf_defaults(struct iperf_test *t);
void iperf_free_test(struct iperf_test *t);
.fi
Setting test parameters:
.nf
void iperf_set_test_role( struct iperf_test *pt, char role );
void iperf_set_test_server_hostname( struct iperf_test *t, char *server_hos
void iperf_set_test_server_port( struct iperf_test *t, int server_port );
void iperf_set_test_duration( struct iperf_test *t, int duration );
void iperf_set_test_blksize( struct iperf_test *t, int blksize );
void iperf_set_test_num_streams( struct iperf_test *t, int num_streams );
void iperf_set_test_json_output( struct iperf_test *t, int json_output );
int iperf_has_zerocopy( void );
void iperf_set_test_zerocopy( struct iperf_test* t, int zerocopy );
.fi
Running a test:
.nf
int iperf_run_client(struct iperf_test *);
int iperf_run_server(struct iperf_test *);
void iperf_test_reset(struct iperf_test *);
.fi
Error reporting:
.nf
void iperf_err(struct iperf_test *t, const char *format, ...);
char *iperf_strerror(int);
extern int i_errno;
.fi
This is not a complete list of the available calls.
See the include file for more.
.SH EXAMPLES
Here's some sample code that runs an iperf client:
.nf
struct iperf_test *test;
test = iperf_new_test();
if ( test == NULL ) {
fprintf( stderr, "%s: failed to create test\n", argv0 );
exit( EXIT_FAILURE );
}
iperf_defaults( test );
iperf_set_test_role( test, 'c' );
iperf_set_test_server_hostname( test, host );
iperf_set_test_server_port( test, port );
if ( iperf_run_client( test ) < 0 ) {
fprintf( stderr, "%s: error - %s\n", argv0, iperf_strerror( i_errno ) );
exit( EXIT_FAILURE );
}
iperf_free_test( test );
.fi
And here's a server:
.nf
struct iperf_test *test;
test = iperf_new_test();
if ( test == NULL ) {
fprintf( stderr, "%s: failed to create test\n", argv0 );
exit( EXIT_FAILURE );
}
iperf_defaults( test );
iperf_set_test_role( test, 's' );
iperf_set_test_server_port( test, port );
for (;;) {
if ( iperf_run_server( test ) < 0 )
fprintf( stderr, "%s: error - %s\n\n", argv0, iperf_strerror( i_errn
o ) );
iperf_reset_test( test );
}
iperf_free_test( test );
.fi
These are not complete programs, just excerpts.
The full runnable source code can be found in the examples subdirectory
of the iperf3 source tree.
.SH AUTHORS
Iperf was originally written by Mark Gates and Alex Warshavsky.
Man page and maintence by Jon Dugan <jdugan at x1024 dot net>.
Other contributions from Ajay Tirumala, Jim Ferguson,
Feng Qin,
Kevin Gibbs,
John Estabrook <jestabro at ncsa.uiuc.edu>,
Andrew Gallatin <gallatin at gmail.com>,
Stephen Hemminger <shemminger at linux-foundation.org>
.SH "SEE ALSO"
iperf3(1),
http://code.google.com/p/iperf/
| zz1126wnx-iperf3 | src/libiperf.3 | Roff Manpage | bsd | 3,321 |
/*
Copyright (c) 2009 Dave Gamble
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* cJSON */
/* JSON parser in C. */
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
#include <sys/types.h>
#include "cjson.h"
#ifndef LLONG_MAX
#define LLONG_MAX 9223372036854775807LL
#endif
#ifndef LLONG_MIN
#define LLONG_MIN (-LLONG_MAX - 1LL)
#endif
static const char *ep;
const char *cJSON_GetErrorPtr( void )
{
return ep;
}
static int cJSON_strcasecmp( const char *s1, const char *s2 )
{
if ( ! s1 )
return ( s1 == s2 ) ? 0 : 1;
if ( ! s2 )
return 1;
for ( ; tolower(*s1) == tolower(*s2); ++s1, ++s2)
if( *s1 == 0 )
return 0;
return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
}
static void *(*cJSON_malloc)( size_t ) = malloc;
static void (*cJSON_free)( void * ) = free;
void cJSON_InitHooks(cJSON_Hooks* hooks)
{
if ( ! hooks ) {
/* Reset hooks. */
cJSON_malloc = malloc;
cJSON_free = free;
return;
}
cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc;
cJSON_free = (hooks->free_fn) ? hooks->free_fn : free;
}
static char* cJSON_strdup( const char* str )
{
size_t len;
char* copy;
len = strlen( str ) + 1;
if ( ! ( copy = (char*) cJSON_malloc( len ) ) )
return 0;
memcpy( copy, str, len );
return copy;
}
/* Internal constructor. */
static cJSON *cJSON_New_Item( void )
{
cJSON* node = (cJSON*) cJSON_malloc( sizeof(cJSON) );
if ( node )
memset( node, 0, sizeof(cJSON) );
return node;
}
/* Delete a cJSON structure. */
void cJSON_Delete( cJSON *c )
{
cJSON *next;
while ( c ) {
next = c->next;
if ( ! ( c->type & cJSON_IsReference ) && c->child )
cJSON_Delete( c->child );
if ( ! ( c->type & cJSON_IsReference ) && c->valuestring )
cJSON_free( c->valuestring );
if ( c->string )
cJSON_free( c->string );
cJSON_free( c );
c = next;
}
}
static double ipow( double n, int exp )
{
double r;
if ( exp < 0 )
return 1.0 / ipow( n, -exp );
r = 1;
while ( exp > 0 ) {
if ( exp & 1 )
r *= n;
exp >>= 1;
n *= n;
}
return r;
}
/* Parse the input text to generate a number, and populate the result into item. */
static const char *parse_number( cJSON *item, const char *num )
{
int64_t i = 0;
double f = 0;
int isint = 1;
int sign = 1, scale = 0, subscale = 0, signsubscale = 1;
/* Could use sscanf for this? */
if ( *num == '-' ) {
/* Has sign. */
sign = -1;
++num;
}
if ( *num == '0' )
/* Is zero. */
++num;
if ( *num >= '1' && *num<='9' ) {
/* Number. */
do {
i = ( i * 10 ) + ( *num - '0' );
f = ( f * 10.0 ) + ( *num - '0' );
++num;
} while ( *num >= '0' && *num <= '9' );
}
if ( *num == '.' && num[1] >= '0' && num[1] <= '9' ) {
/* Fractional part. */
isint = 0;
++num;
do {
f = ( f * 10.0 ) + ( *num++ - '0' );
scale--;
} while ( *num >= '0' && *num <= '9' );
}
if ( *num == 'e' || *num == 'E' ) {
/* Exponent. */
isint = 0;
++num;
if ( *num == '+' )
++num;
else if ( *num == '-' ) {
/* With sign. */
signsubscale = -1;
++num;
}
while ( *num >= '0' && *num <= '9' )
subscale = ( subscale * 10 ) + ( *num++ - '0' );
}
/* Put it together. */
if ( isint ) {
/* Int: number = +/- number */
i = sign * i;
item->valueint = i;
item->valuefloat = i;
} else {
/* Float: number = +/- number.fraction * 10^+/- exponent */
f = sign * f * ipow( 10.0, scale + subscale * signsubscale );
item->valueint = f;
item->valuefloat = f;
}
item->type = cJSON_Number;
return num;
}
/* Render the number nicely from the given item into a string. */
static char *print_number( cJSON *item )
{
char *str;
double f, f2;
int64_t i;
str = (char*) cJSON_malloc( 64 );
if ( str ) {
f = item->valuefloat;
i = f;
f2 = i;
if ( f2 == f && item->valueint >= LLONG_MIN && item->valueint <= LLONG_MAX )
sprintf( str, "%lld", (long long) item->valueint );
else
sprintf( str, "%g", item->valuefloat );
}
return str;
}
/* Parse the input text into an unescaped cstring, and populate item. */
static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
static const char *parse_string( cJSON *item, const char *str )
{
const char *ptr = str + 1;
char *ptr2;
char *out;
int len = 0;
unsigned uc, uc2;
if ( *str != '\"' ) {
/* Not a string! */
ep = str;
return 0;
}
/* Skip escaped quotes. */
while ( *ptr != '\"' && *ptr && ++len )
if ( *ptr++ == '\\' )
ptr++;
if ( ! ( out = (char*) cJSON_malloc( len + 1 ) ) )
return 0;
ptr = str + 1;
ptr2 = out;
while ( *ptr != '\"' && *ptr ) {
if ( *ptr != '\\' )
*ptr2++ = *ptr++;
else {
ptr++;
switch ( *ptr ) {
case 'b': *ptr2++ ='\b'; break;
case 'f': *ptr2++ ='\f'; break;
case 'n': *ptr2++ ='\n'; break;
case 'r': *ptr2++ ='\r'; break;
case 't': *ptr2++ ='\t'; break;
case 'u':
/* Transcode utf16 to utf8. */
/* Get the unicode char. */
sscanf( ptr + 1,"%4x", &uc );
ptr += 4;
/* Check for invalid. */
if ( ( uc >= 0xDC00 && uc <= 0xDFFF ) || uc == 0 )
break;
/* UTF16 surrogate pairs. */
if ( uc >= 0xD800 && uc <= 0xDBFF ) {
if ( ptr[1] != '\\' || ptr[2] != 'u' )
/* Missing second-half of surrogate. */
break;
sscanf( ptr + 3, "%4x", &uc2 );
ptr += 6;
if ( uc2 < 0xDC00 || uc2 > 0xDFFF )
/* Invalid second-half of surrogate. */
break;
uc = 0x10000 | ( ( uc & 0x3FF ) << 10 ) | ( uc2 & 0x3FF );
}
len = 4;
if ( uc < 0x80 )
len = 1;
else if ( uc < 0x800 )
len = 2;
else if ( uc < 0x10000 )
len = 3;
ptr2 += len;
switch ( len ) {
case 4: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6;
case 3: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6;
case 2: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6;
case 1: *--ptr2 = ( uc | firstByteMark[len] );
}
ptr2 += len;
break;
default: *ptr2++ = *ptr; break;
}
++ptr;
}
}
*ptr2 = 0;
if ( *ptr == '\"' )
++ptr;
item->valuestring = out;
item->type = cJSON_String;
return ptr;
}
/* Render the cstring provided to an escaped version that can be printed. */
static char *print_string_ptr( const char *str )
{
const char *ptr;
char *ptr2, *out;
int len = 0;
unsigned char token;
if ( ! str )
return cJSON_strdup( "" );
ptr = str;
while ( ( token = *ptr ) && ++len ) {
if ( strchr( "\"\\\b\f\n\r\t", token ) )
++len;
else if ( token < 32 )
len += 5;
++ptr;
}
if ( ! ( out = (char*) cJSON_malloc( len + 3 ) ) )
return 0;
ptr2 = out;
ptr = str;
*ptr2++ = '\"';
while ( *ptr ) {
if ( (unsigned char) *ptr > 31 && *ptr != '\"' && *ptr != '\\' )
*ptr2++ = *ptr++;
else {
*ptr2++ = '\\';
switch ( token = *ptr++ ) {
case '\\': *ptr2++ = '\\'; break;
case '\"': *ptr2++ = '\"'; break;
case '\b': *ptr2++ = 'b'; break;
case '\f': *ptr2++ = 'f'; break;
case '\n': *ptr2++ = 'n'; break;
case '\r': *ptr2++ = 'r'; break;
case '\t': *ptr2++ = 't'; break;
default:
/* Escape and print. */
sprintf( ptr2, "u%04x", token );
ptr2 += 5;
break;
}
}
}
*ptr2++ = '\"';
*ptr2++ = 0;
return out;
}
/* Invote print_string_ptr (which is useful) on an item. */
static char *print_string( cJSON *item )
{
return print_string_ptr( item->valuestring );
}
/* Predeclare these prototypes. */
static const char *parse_value( cJSON *item, const char *value );
static char *print_value( cJSON *item, int depth, int fmt );
static const char *parse_array( cJSON *item, const char *value );
static char *print_array( cJSON *item, int depth, int fmt );
static const char *parse_object( cJSON *item, const char *value );
static char *print_object( cJSON *item, int depth, int fmt );
/* Utility to jump whitespace and cr/lf. */
static const char *skip( const char *in )
{
while ( in && *in && (unsigned char) *in <= 32 )
in++;
return in;
}
/* Parse an object - create a new root, and populate. */
cJSON *cJSON_Parse( const char *value )
{
cJSON *c;
ep = 0;
if ( ! ( c = cJSON_New_Item() ) )
return 0; /* memory fail */
if ( ! parse_value( c, skip( value ) ) ) {
cJSON_Delete( c );
return 0;
}
return c;
}
/* Render a cJSON item/entity/structure to text. */
char *cJSON_Print( cJSON *item )
{
return print_value( item, 0, 1 );
}
char *cJSON_PrintUnformatted( cJSON *item )
{
return print_value( item, 0, 0 );
}
/* Parser core - when encountering text, process appropriately. */
static const char *parse_value( cJSON *item, const char *value )
{
if ( ! value )
return 0; /* Fail on null. */
if ( ! strncmp( value, "null", 4 ) ) {
item->type = cJSON_NULL;
return value + 4;
}
if ( ! strncmp( value, "false", 5 ) ) {
item->type = cJSON_False;
return value + 5;
}
if ( ! strncmp( value, "true", 4 ) ) {
item->type = cJSON_True;
item->valueint = 1;
return value + 4;
}
if ( *value == '\"' )
return parse_string( item, value );
if ( *value == '-' || ( *value >= '0' && *value <= '9' ) )
return parse_number( item, value );
if ( *value == '[' )
return parse_array( item, value );
if ( *value == '{' )
return parse_object( item, value );
/* Fail. */
ep = value;
return 0;
}
/* Render a value to text. */
static char *print_value( cJSON *item, int depth, int fmt )
{
char *out = 0;
if ( ! item )
return 0;
switch ( ( item->type ) & 255 ) {
case cJSON_NULL: out = cJSON_strdup( "null" ); break;
case cJSON_False: out = cJSON_strdup( "false" ); break;
case cJSON_True: out = cJSON_strdup( "true" ); break;
case cJSON_Number: out = print_number( item ); break;
case cJSON_String: out = print_string( item ); break;
case cJSON_Array: out = print_array( item, depth, fmt ); break;
case cJSON_Object: out = print_object( item, depth, fmt ); break;
}
return out;
}
/* Build an array from input text. */
static const char *parse_array( cJSON *item, const char *value )
{
cJSON *child;
if ( *value != '[' ) {
/* Not an array! */
ep = value;
return 0;
}
item->type = cJSON_Array;
value = skip( value + 1 );
if ( *value == ']' )
return value + 1; /* empty array. */
if ( ! ( item->child = child = cJSON_New_Item() ) )
return 0; /* memory fail */
if ( ! ( value = skip( parse_value( child, skip( value ) ) ) ) )
return 0;
while ( *value == ',' ) {
cJSON *new_item;
if ( ! ( new_item = cJSON_New_Item() ) )
return 0; /* memory fail */
child->next = new_item;
new_item->prev = child;
child = new_item;
if ( ! ( value = skip( parse_value( child, skip( value+1 ) ) ) ) )
return 0; /* memory fail */
}
if ( *value == ']' )
return value + 1; /* end of array */
/* Malformed. */
ep = value;
return 0;
}
/* Render an array to text */
static char *print_array( cJSON *item, int depth, int fmt )
{
char **entries;
char *out = 0, *ptr, *ret;
int len = 5;
cJSON *child = item->child;
int numentries = 0, i = 0, fail = 0;
/* How many entries in the array? */
while ( child ) {
++numentries;
child = child->next;
}
/* Allocate an array to hold the values for each. */
if ( ! ( entries = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) )
return 0;
memset( entries, 0, numentries * sizeof(char*) );
/* Retrieve all the results. */
child = item->child;
while ( child && ! fail ) {
ret = print_value( child, depth + 1, fmt );
entries[i++] = ret;
if ( ret )
len += strlen( ret ) + 2 + ( fmt ? 1 : 0 );
else
fail = 1;
child = child -> next;
}
/* If we didn't fail, try to malloc the output string. */
if ( ! fail ) {
out = (char*) cJSON_malloc( len );
if ( ! out )
fail = 1;
}
/* Handle failure. */
if ( fail ) {
for ( i = 0; i < numentries; ++i )
if ( entries[i] )
cJSON_free( entries[i] );
cJSON_free( entries );
return 0;
}
/* Compose the output array. */
*out = '[';
ptr = out + 1;
*ptr = 0;
for ( i = 0; i < numentries; ++i ) {
strcpy( ptr, entries[i] );
ptr += strlen( entries[i] );
if ( i != numentries - 1 ) {
*ptr++ = ',';
if ( fmt )
*ptr++ = ' ';
*ptr = 0;
}
cJSON_free( entries[i] );
}
cJSON_free( entries );
*ptr++ = ']';
*ptr++ = 0;
return out;
}
/* Build an object from the text. */
static const char *parse_object( cJSON *item, const char *value )
{
cJSON *child;
if ( *value != '{' ) {
/* Not an object! */
ep = value;
return 0;
}
item->type = cJSON_Object;
value =skip( value + 1 );
if ( *value == '}' )
return value + 1; /* empty array. */
if ( ! ( item->child = child = cJSON_New_Item() ) )
return 0;
if ( ! ( value = skip( parse_string( child, skip( value ) ) ) ) )
return 0;
child->string = child->valuestring;
child->valuestring = 0;
if ( *value != ':' ) {
/* Fail! */
ep = value;
return 0;
}
if ( ! ( value = skip( parse_value( child, skip( value + 1 ) ) ) ) )
return 0;
while ( *value == ',' ) {
cJSON *new_item;
if ( ! ( new_item = cJSON_New_Item() ) )
return 0; /* memory fail */
child->next = new_item;
new_item->prev = child;
child = new_item;
if ( ! ( value = skip( parse_string( child, skip( value + 1 ) ) ) ) )
return 0;
child->string = child->valuestring;
child->valuestring = 0;
if ( *value != ':' ) {
/* Fail! */
ep = value;
return 0;
}
if ( ! ( value = skip( parse_value( child, skip( value + 1 ) ) ) ) )
return 0;
}
if ( *value == '}' )
return value + 1; /* end of array */
/* Malformed. */
ep = value;
return 0;
}
/* Render an object to text. */
static char *print_object( cJSON *item, int depth, int fmt )
{
char **entries = 0, **names = 0;
char *out = 0, *ptr, *ret, *str;
int len = 7, i = 0, j;
cJSON *child = item->child;
int numentries = 0, fail = 0;
/* Count the number of entries. */
while ( child ) {
++numentries;
child = child->next;
}
/* Allocate space for the names and the objects. */
if ( ! ( entries = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) )
return 0;
if ( ! ( names = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) ) {
cJSON_free( entries );
return 0;
}
memset( entries, 0, sizeof(char*) * numentries );
memset( names, 0, sizeof(char*) * numentries );
/* Collect all the results into our arrays. */
child = item->child;
++depth;
if ( fmt )
len += depth;
while ( child ) {
names[i] = str = print_string_ptr( child->string );
entries[i++] = ret = print_value( child, depth, fmt );
if ( str && ret )
len += strlen( ret ) + strlen( str ) + 2 + ( fmt ? 2 + depth : 0 );
else
fail = 1;
child = child->next;
}
/* Try to allocate the output string. */
if ( ! fail ) {
out = (char*) cJSON_malloc( len );
if ( ! out )
fail = 1;
}
/* Handle failure. */
if ( fail ) {
for ( i = 0; i < numentries; ++i ) {
if ( names[i] )
cJSON_free( names[i] );
if ( entries[i] )
cJSON_free( entries[i] );
}
cJSON_free( names );
cJSON_free( entries );
return 0;
}
/* Compose the output. */
*out = '{';
ptr = out + 1;
if ( fmt )
*ptr++ = '\n';
*ptr = 0;
for ( i = 0; i < numentries; ++i ) {
if ( fmt )
for ( j = 0; j < depth; ++j )
*ptr++ = '\t';
strcpy( ptr, names[i] );
ptr += strlen( names[i] );
*ptr++ = ':';
if ( fmt )
*ptr++ = '\t';
strcpy( ptr, entries[i] );
ptr += strlen( entries[i] );
if ( i != numentries - 1 )
*ptr++ = ',';
if ( fmt )
*ptr++ = '\n';
*ptr = 0;
cJSON_free( names[i] );
cJSON_free( entries[i] );
}
cJSON_free( names );
cJSON_free( entries );
if ( fmt )
for ( i = 0; i < depth - 1; ++i )
*ptr++ = '\t';
*ptr++ = '}';
*ptr++ = 0;
return out;
}
int cJSON_GetArraySize( cJSON *array )
{
cJSON *c = array->child;
int i = 0;
while ( c ) {
++i;
c = c->next;
}
return i;
}
cJSON *cJSON_GetArrayItem( cJSON *array, int item )
{
cJSON *c = array->child;
while ( c && item > 0 ) {
--item;
c = c->next;
}
return c;
}
cJSON *cJSON_GetObjectItem( cJSON *object, const char *string )
{
cJSON *c = object->child;
while ( c && cJSON_strcasecmp( c->string, string ) )
c = c->next;
return c;
}
/* Utility for array list handling. */
static void suffix_object( cJSON *prev, cJSON *item )
{
prev->next = item;
item->prev = prev;
}
/* Utility for handling references. */
static cJSON *create_reference( cJSON *item )
{
cJSON *ref;
if ( ! ( ref = cJSON_New_Item() ) )
return 0;
memcpy( ref, item, sizeof(cJSON) );
ref->string = 0;
ref->type |= cJSON_IsReference;
ref->next = ref->prev = 0;
return ref;
}
/* Add item to array/object. */
void cJSON_AddItemToArray( cJSON *array, cJSON *item )
{
cJSON *c = array->child;
if ( ! item )
return;
if ( ! c ) {
array->child = item;
} else {
while ( c && c->next )
c = c->next;
suffix_object( c, item );
}
}
void cJSON_AddItemToObject( cJSON *object, const char *string, cJSON *item )
{
if ( ! item )
return;
if ( item->string )
cJSON_free( item->string );
item->string = cJSON_strdup( string );
cJSON_AddItemToArray( object, item );
}
void cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item )
{
cJSON_AddItemToArray( array, create_reference( item ) );
}
void cJSON_AddItemReferenceToObject( cJSON *object, const char *string, cJSON *item )
{
cJSON_AddItemToObject( object, string, create_reference( item ) );
}
cJSON *cJSON_DetachItemFromArray( cJSON *array, int which )
{
cJSON *c = array->child;
while ( c && which > 0 ) {
c = c->next;
--which;
}
if ( ! c )
return 0;
if ( c->prev )
c->prev->next = c->next;
if ( c->next ) c->next->prev = c->prev;
if ( c == array->child )
array->child = c->next;
c->prev = c->next = 0;
return c;
}
void cJSON_DeleteItemFromArray( cJSON *array, int which )
{
cJSON_Delete( cJSON_DetachItemFromArray( array, which ) );
}
cJSON *cJSON_DetachItemFromObject( cJSON *object, const char *string )
{
int i = 0;
cJSON *c = object->child;
while ( c && cJSON_strcasecmp( c->string, string ) ) {
++i;
c = c->next;
}
if ( c )
return cJSON_DetachItemFromArray( object, i );
return 0;
}
void cJSON_DeleteItemFromObject( cJSON *object, const char *string )
{
cJSON_Delete( cJSON_DetachItemFromObject( object, string ) );
}
/* Replace array/object items with new ones. */
void cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *newitem )
{
cJSON *c = array->child;
while ( c && which > 0 ) {
c = c->next;
--which;
}
if ( ! c )
return;
newitem->next = c->next;
newitem->prev = c->prev;
if ( newitem->next )
newitem->next->prev = newitem;
if ( c == array->child )
array->child = newitem;
else
newitem->prev->next = newitem;
c->next = c->prev = 0;
cJSON_Delete( c );
}
void cJSON_ReplaceItemInObject( cJSON *object, const char *string, cJSON *newitem )
{
int i = 0;
cJSON *c = object->child;
while ( c && cJSON_strcasecmp( c->string, string ) ) {
++i;
c = c->next;
}
if ( c ) {
newitem->string = cJSON_strdup( string );
cJSON_ReplaceItemInArray( object, i, newitem );
}
}
/* Create basic types: */
cJSON *cJSON_CreateNull( void )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = cJSON_NULL;
return item;
}
cJSON *cJSON_CreateTrue( void )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = cJSON_True;
return item;
}
cJSON *cJSON_CreateFalse( void )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = cJSON_False;
return item;
}
cJSON *cJSON_CreateBool( int b )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = b ? cJSON_True : cJSON_False;
return item;
}
cJSON *cJSON_CreateInt( int64_t num )
{
cJSON *item = cJSON_New_Item();
if ( item ) {
item->type = cJSON_Number;
item->valuefloat = num;
item->valueint = num;
}
return item;
}
cJSON *cJSON_CreateFloat( double num )
{
cJSON *item = cJSON_New_Item();
if ( item ) {
item->type = cJSON_Number;
item->valuefloat = num;
item->valueint = num;
}
return item;
}
cJSON *cJSON_CreateString( const char *string )
{
cJSON *item = cJSON_New_Item();
if ( item ) {
item->type = cJSON_String;
item->valuestring = cJSON_strdup( string );
}
return item;
}
cJSON *cJSON_CreateArray( void )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = cJSON_Array;
return item;
}
cJSON *cJSON_CreateObject( void )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = cJSON_Object;
return item;
}
/* Create Arrays. */
cJSON *cJSON_CreateIntArray( int64_t *numbers, int count )
{
int i;
cJSON *n = 0, *p = 0, *a = cJSON_CreateArray();
for ( i = 0; a && i < count; ++i ) {
n = cJSON_CreateInt( numbers[i] );
if ( ! i )
a->child = n;
else
suffix_object( p, n );
p = n;
}
return a;
}
cJSON *cJSON_CreateFloatArray( double *numbers, int count )
{
int i;
cJSON *n = 0, *p = 0, *a = cJSON_CreateArray();
for ( i = 0; a && i < count; ++i ) {
n = cJSON_CreateFloat( numbers[i] );
if ( ! i )
a->child = n;
else
suffix_object( p, n );
p = n;
}
return a;
}
cJSON *cJSON_CreateStringArray( const char **strings, int count )
{
int i;
cJSON *n = 0, *p = 0, *a = cJSON_CreateArray();
for ( i = 0; a && i < count; ++i ) {
n = cJSON_CreateString( strings[i] );
if ( ! i )
a->child = n;
else
suffix_object( p, n );
p = n;
}
return a;
}
| zz1126wnx-iperf3 | src/cjson.c | C | bsd | 22,248 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#include <stdio.h>
#include <errno.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include "iperf.h"
#include "iperf_api.h"
/* Do a printf to stderr. */
void
iperf_err(struct iperf_test *test, const char *format, ...)
{
va_list argp;
char str[1000];
va_start(argp, format);
vsnprintf(str, sizeof(str), format, argp);
if (test != NULL && test->json_output && test->json_top != NULL)
cJSON_AddStringToObject(test->json_top, "error", str);
else
fprintf(stderr, "iperf3: %s\n", str);
va_end(argp);
}
/* Do a printf to stderr, then exit. */
void
iperf_errexit(struct iperf_test *test, const char *format, ...)
{
va_list argp;
char str[1000];
va_start(argp, format);
vsnprintf(str, sizeof(str), format, argp);
if (test != NULL && test->json_output && test->json_top != NULL) {
cJSON_AddStringToObject(test->json_top, "error", str);
iperf_json_finish(test);
} else
fprintf(stderr, "iperf3: %s\n", str);
va_end(argp);
exit(1);
}
int i_errno;
char *
iperf_strerror(int i_errno)
{
static char errstr[256];
int len, perr, herr;
perr = herr = 0;
len = sizeof(errstr);
memset(errstr, 0, len);
switch (i_errno) {
case IENONE:
snprintf(errstr, len, "no error");
break;
case IESERVCLIENT:
snprintf(errstr, len, "cannot be both server and client");
break;
case IENOROLE:
snprintf(errstr, len, "must either be a client (-c) or server (-s)");
break;
case IESERVERONLY:
snprintf(errstr, len, "some option you are trying to set is server only");
break;
case IECLIENTONLY:
snprintf(errstr, len, "some option you are trying to set is client only");
break;
case IEDURATION:
snprintf(errstr, len, "test duration too long (maximum = %d seconds)", MAX_TIME);
break;
case IENUMSTREAMS:
snprintf(errstr, len, "number of parallel streams too large (maximum = %d)", MAX_STREAMS);
break;
case IEBLOCKSIZE:
snprintf(errstr, len, "block size too large (maximum = %d bytes)", MAX_BLOCKSIZE);
break;
case IEBUFSIZE:
snprintf(errstr, len, "socket buffer size too large (maximum = %d bytes)", MAX_TCP_BUFFER);
break;
case IEINTERVAL:
snprintf(errstr, len, "report interval too large (maximum = %d seconds)", MAX_INTERVAL);
break;
case IEMSS:
snprintf(errstr, len, "TCP MSS too large (maximum = %d bytes)", MAX_MSS);
break;
case IENOSENDFILE:
snprintf(errstr, len, "this OS does not support sendfile");
break;
case IENEWTEST:
snprintf(errstr, len, "unable to create a new test");
perr = 1;
break;
case IEINITTEST:
snprintf(errstr, len, "test initialization failed");
perr = 1;
break;
case IELISTEN:
snprintf(errstr, len, "unable to start listener for connections");
perr = 1;
break;
case IECONNECT:
snprintf(errstr, len, "unable to connect to server");
perr = 1;
break;
case IEACCEPT:
snprintf(errstr, len, "unable to accept connection from client");
herr = 1;
perr = 1;
break;
case IESENDCOOKIE:
snprintf(errstr, len, "unable to send cookie to server");
perr = 1;
break;
case IERECVCOOKIE:
snprintf(errstr, len, "unable to receive cookie to server");
perr = 1;
break;
case IECTRLWRITE:
snprintf(errstr, len, "unable to write to the control socket");
perr = 1;
break;
case IECTRLREAD:
snprintf(errstr, len, "unable to read from the control socket");
perr = 1;
break;
case IECTRLCLOSE:
snprintf(errstr, len, "control socket has closed unexpectedly");
break;
case IEMESSAGE:
snprintf(errstr, len, "received an unknown control message");
break;
case IESENDMESSAGE:
snprintf(errstr, len, "unable to send control message");
perr = 1;
break;
case IERECVMESSAGE:
snprintf(errstr, len, "unable to receive control message");
perr = 1;
break;
case IESENDPARAMS:
snprintf(errstr, len, "unable to send parameters to server");
perr = 1;
break;
case IERECVPARAMS:
snprintf(errstr, len, "unable to receive parameters from client");
perr = 1;
break;
case IEPACKAGERESULTS:
snprintf(errstr, len, "unable to package results");
perr = 1;
break;
case IESENDRESULTS:
snprintf(errstr, len, "unable to send results");
perr = 1;
break;
case IERECVRESULTS:
snprintf(errstr, len, "unable to receive results");
perr = 1;
break;
case IESELECT:
snprintf(errstr, len, "select failed");
perr = 1;
break;
case IECLIENTTERM:
snprintf(errstr, len, "the client has terminated");
break;
case IESERVERTERM:
snprintf(errstr, len, "the server has terminated");
break;
case IEACCESSDENIED:
snprintf(errstr, len, "the server is busy running a test. try again later");
break;
case IESETNODELAY:
snprintf(errstr, len, "unable to set TCP NODELAY");
perr = 1;
break;
case IESETMSS:
snprintf(errstr, len, "unable to set TCP MSS");
perr = 1;
break;
case IESETBUF:
snprintf(errstr, len, "unable to set socket buffer size");
perr = 1;
break;
case IESETTOS:
snprintf(errstr, len, "unable to set IP TOS");
perr = 1;
break;
case IESETCOS:
snprintf(errstr, len, "unable to set IPv6 traffic class");
perr = 1;
break;
case IEREUSEADDR:
snprintf(errstr, len, "unable to reuse address on socket");
perr = 1;
break;
case IENONBLOCKING:
snprintf(errstr, len, "unable to set socket to non-blocking");
perr = 1;
break;
case IESETWINDOWSIZE:
snprintf(errstr, len, "unable to set socket window size");
perr = 1;
break;
case IEPROTOCOL:
snprintf(errstr, len, "protocol does not exist");
break;
case IECREATESTREAM:
snprintf(errstr, len, "unable to create a new stream");
herr = 1;
perr = 1;
break;
case IEINITSTREAM:
snprintf(errstr, len, "unable to initialize stream");
herr = 1;
perr = 1;
break;
case IESTREAMLISTEN:
snprintf(errstr, len, "unable to start stream listener");
perr = 1;
break;
case IESTREAMCONNECT:
snprintf(errstr, len, "unable to connect stream");
herr = 1;
perr = 1;
break;
case IESTREAMACCEPT:
snprintf(errstr, len, "unable to accept stream connection");
perr = 1;
break;
case IESTREAMWRITE:
snprintf(errstr, len, "unable to write to stream socket");
perr = 1;
break;
case IESTREAMREAD:
snprintf(errstr, len, "unable to read from stream socket");
perr = 1;
break;
case IESTREAMCLOSE:
snprintf(errstr, len, "stream socket has closed unexpectedly");
break;
case IESTREAMID:
snprintf(errstr, len, "stream has an invalid id");
break;
case IENEWTIMER:
snprintf(errstr, len, "unable to create new timer");
perr = 1;
break;
case IEUPDATETIMER:
snprintf(errstr, len, "unable to update timer");
perr = 1;
break;
}
if (herr || perr)
strncat(errstr, ": ", len);
if (h_errno && herr) {
strncat(errstr, hstrerror(h_errno), len);
} else if (errno && perr) {
strncat(errstr, strerror(errno), len);
}
return errstr;
}
| zz1126wnx-iperf3 | src/iperf_error.c | C | bsd | 9,027 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include "iperf_util.h"
int
main(int argc, char **argv)
{
char cookie[37];
make_cookie(cookie);
printf("cookie: '%s'\n", cookie);
if (strlen(cookie) != 36)
{
printf("Not 36 characters long!\n");
exit(-1);
}
exit(0);
}
| zz1126wnx-iperf3 | src/t_uuid.c | C | bsd | 676 |
/* $OpenBSD: queue.h,v 1.32 2007/04/30 18:42:34 pedro Exp $ */
/* $NetBSD: queue.h,v 1.11 1996/05/16 05:17:14 mycroft Exp $ */
/*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)queue.h 8.5 (Berkeley) 8/20/94
*/
#ifndef _SYS_QUEUE_H_
#define _SYS_QUEUE_H_
/*
* This file defines five types of data structures: singly-linked lists,
* lists, simple queues, tail queues, and circular queues.
*
*
* A singly-linked list is headed by a single forward pointer. The elements
* are singly linked for minimum space and pointer manipulation overhead at
* the expense of O(n) removal for arbitrary elements. New elements can be
* added to the list after an existing element or at the head of the list.
* Elements being removed from the head of the list should use the explicit
* macro for this purpose for optimum efficiency. A singly-linked list may
* only be traversed in the forward direction. Singly-linked lists are ideal
* for applications with large datasets and few or no removals or for
* implementing a LIFO queue.
*
* A list is headed by a single forward pointer (or an array of forward
* pointers for a hash table header). The elements are doubly linked
* so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before
* or after an existing element or at the head of the list. A list
* may only be traversed in the forward direction.
*
* A simple queue is headed by a pair of pointers, one the head of the
* list and the other to the tail of the list. The elements are singly
* linked to save space, so elements can only be removed from the
* head of the list. New elements can be added to the list before or after
* an existing element, at the head of the list, or at the end of the
* list. A simple queue may only be traversed in the forward direction.
*
* A tail queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or
* after an existing element, at the head of the list, or at the end of
* the list. A tail queue may be traversed in either direction.
*
* A circle queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or after
* an existing element, at the head of the list, or at the end of the list.
* A circle queue may be traversed in either direction, but has a more
* complex end of list detection.
*
* For details on the use of these macros, see the queue(3) manual page.
*/
#if defined(QUEUE_MACRO_DEBUG) || (defined(_KERNEL) && defined(DIAGNOSTIC))
#define _Q_INVALIDATE(a) (a) = ((void *)-1)
#else
#define _Q_INVALIDATE(a)
#endif
/*
* Singly-linked List definitions.
*/
#define SLIST_HEAD(name, type) \
struct name { \
struct type *slh_first; /* first element */ \
}
#define SLIST_HEAD_INITIALIZER(head) \
{ NULL }
#define SLIST_ENTRY(type) \
struct { \
struct type *sle_next; /* next element */ \
}
/*
* Singly-linked List access methods.
*/
#define SLIST_FIRST(head) ((head)->slh_first)
#define SLIST_END(head) NULL
#define SLIST_EMPTY(head) (SLIST_FIRST(head) == SLIST_END(head))
#define SLIST_NEXT(elm, field) ((elm)->field.sle_next)
#define SLIST_FOREACH(var, head, field) \
for((var) = SLIST_FIRST(head); \
(var) != SLIST_END(head); \
(var) = SLIST_NEXT(var, field))
#define SLIST_FOREACH_PREVPTR(var, varp, head, field) \
for ((varp) = &SLIST_FIRST((head)); \
((var) = *(varp)) != SLIST_END(head); \
(varp) = &SLIST_NEXT((var), field))
/*
* Singly-linked List functions.
*/
#define SLIST_INIT(head) { \
SLIST_FIRST(head) = SLIST_END(head); \
}
#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \
(elm)->field.sle_next = (slistelm)->field.sle_next; \
(slistelm)->field.sle_next = (elm); \
} while (0)
#define SLIST_INSERT_HEAD(head, elm, field) do { \
(elm)->field.sle_next = (head)->slh_first; \
(head)->slh_first = (elm); \
} while (0)
#define SLIST_REMOVE_NEXT(head, elm, field) do { \
(elm)->field.sle_next = (elm)->field.sle_next->field.sle_next; \
} while (0)
#define SLIST_REMOVE_HEAD(head, field) do { \
(head)->slh_first = (head)->slh_first->field.sle_next; \
} while (0)
#define SLIST_REMOVE(head, elm, type, field) do { \
if ((head)->slh_first == (elm)) { \
SLIST_REMOVE_HEAD((head), field); \
} else { \
struct type *curelm = (head)->slh_first; \
\
while (curelm->field.sle_next != (elm)) \
curelm = curelm->field.sle_next; \
curelm->field.sle_next = \
curelm->field.sle_next->field.sle_next; \
_Q_INVALIDATE((elm)->field.sle_next); \
} \
} while (0)
/*
* List definitions.
*/
#define LIST_HEAD(name, type) \
struct name { \
struct type *lh_first; /* first element */ \
}
#define LIST_HEAD_INITIALIZER(head) \
{ NULL }
#define LIST_ENTRY(type) \
struct { \
struct type *le_next; /* next element */ \
struct type **le_prev; /* address of previous next element */ \
}
/*
* List access methods
*/
#define LIST_FIRST(head) ((head)->lh_first)
#define LIST_END(head) NULL
#define LIST_EMPTY(head) (LIST_FIRST(head) == LIST_END(head))
#define LIST_NEXT(elm, field) ((elm)->field.le_next)
#define LIST_FOREACH(var, head, field) \
for((var) = LIST_FIRST(head); \
(var)!= LIST_END(head); \
(var) = LIST_NEXT(var, field))
/*
* List functions.
*/
#define LIST_INIT(head) do { \
LIST_FIRST(head) = LIST_END(head); \
} while (0)
#define LIST_INSERT_AFTER(listelm, elm, field) do { \
if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \
(listelm)->field.le_next->field.le_prev = \
&(elm)->field.le_next; \
(listelm)->field.le_next = (elm); \
(elm)->field.le_prev = &(listelm)->field.le_next; \
} while (0)
#define LIST_INSERT_BEFORE(listelm, elm, field) do { \
(elm)->field.le_prev = (listelm)->field.le_prev; \
(elm)->field.le_next = (listelm); \
*(listelm)->field.le_prev = (elm); \
(listelm)->field.le_prev = &(elm)->field.le_next; \
} while (0)
#define LIST_INSERT_HEAD(head, elm, field) do { \
if (((elm)->field.le_next = (head)->lh_first) != NULL) \
(head)->lh_first->field.le_prev = &(elm)->field.le_next;\
(head)->lh_first = (elm); \
(elm)->field.le_prev = &(head)->lh_first; \
} while (0)
#define LIST_REMOVE(elm, field) do { \
if ((elm)->field.le_next != NULL) \
(elm)->field.le_next->field.le_prev = \
(elm)->field.le_prev; \
*(elm)->field.le_prev = (elm)->field.le_next; \
_Q_INVALIDATE((elm)->field.le_prev); \
_Q_INVALIDATE((elm)->field.le_next); \
} while (0)
#define LIST_REPLACE(elm, elm2, field) do { \
if (((elm2)->field.le_next = (elm)->field.le_next) != NULL) \
(elm2)->field.le_next->field.le_prev = \
&(elm2)->field.le_next; \
(elm2)->field.le_prev = (elm)->field.le_prev; \
*(elm2)->field.le_prev = (elm2); \
_Q_INVALIDATE((elm)->field.le_prev); \
_Q_INVALIDATE((elm)->field.le_next); \
} while (0)
/*
* Simple queue definitions.
*/
#define SIMPLEQ_HEAD(name, type) \
struct name { \
struct type *sqh_first; /* first element */ \
struct type **sqh_last; /* addr of last next element */ \
}
#define SIMPLEQ_HEAD_INITIALIZER(head) \
{ NULL, &(head).sqh_first }
#define SIMPLEQ_ENTRY(type) \
struct { \
struct type *sqe_next; /* next element */ \
}
/*
* Simple queue access methods.
*/
#define SIMPLEQ_FIRST(head) ((head)->sqh_first)
#define SIMPLEQ_END(head) NULL
#define SIMPLEQ_EMPTY(head) (SIMPLEQ_FIRST(head) == SIMPLEQ_END(head))
#define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next)
#define SIMPLEQ_FOREACH(var, head, field) \
for((var) = SIMPLEQ_FIRST(head); \
(var) != SIMPLEQ_END(head); \
(var) = SIMPLEQ_NEXT(var, field))
/*
* Simple queue functions.
*/
#define SIMPLEQ_INIT(head) do { \
(head)->sqh_first = NULL; \
(head)->sqh_last = &(head)->sqh_first; \
} while (0)
#define SIMPLEQ_INSERT_HEAD(head, elm, field) do { \
if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \
(head)->sqh_last = &(elm)->field.sqe_next; \
(head)->sqh_first = (elm); \
} while (0)
#define SIMPLEQ_INSERT_TAIL(head, elm, field) do { \
(elm)->field.sqe_next = NULL; \
*(head)->sqh_last = (elm); \
(head)->sqh_last = &(elm)->field.sqe_next; \
} while (0)
#define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \
if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\
(head)->sqh_last = &(elm)->field.sqe_next; \
(listelm)->field.sqe_next = (elm); \
} while (0)
#define SIMPLEQ_REMOVE_HEAD(head, field) do { \
if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \
(head)->sqh_last = &(head)->sqh_first; \
} while (0)
/*
* Tail queue definitions.
*/
#define TAILQ_HEAD(name, type) \
struct name { \
struct type *tqh_first; /* first element */ \
struct type **tqh_last; /* addr of last next element */ \
}
#define TAILQ_HEAD_INITIALIZER(head) \
{ NULL, &(head).tqh_first }
#define TAILQ_ENTRY(type) \
struct { \
struct type *tqe_next; /* next element */ \
struct type **tqe_prev; /* address of previous next element */ \
}
/*
* tail queue access methods
*/
#define TAILQ_FIRST(head) ((head)->tqh_first)
#define TAILQ_END(head) NULL
#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
#define TAILQ_LAST(head, headname) \
(*(((struct headname *)((head)->tqh_last))->tqh_last))
/* XXX */
#define TAILQ_PREV(elm, headname, field) \
(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
#define TAILQ_EMPTY(head) \
(TAILQ_FIRST(head) == TAILQ_END(head))
#define TAILQ_FOREACH(var, head, field) \
for((var) = TAILQ_FIRST(head); \
(var) != TAILQ_END(head); \
(var) = TAILQ_NEXT(var, field))
#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \
for((var) = TAILQ_LAST(head, headname); \
(var) != TAILQ_END(head); \
(var) = TAILQ_PREV(var, headname, field))
/*
* Tail queue functions.
*/
#define TAILQ_INIT(head) do { \
(head)->tqh_first = NULL; \
(head)->tqh_last = &(head)->tqh_first; \
} while (0)
#define TAILQ_INSERT_HEAD(head, elm, field) do { \
if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \
(head)->tqh_first->field.tqe_prev = \
&(elm)->field.tqe_next; \
else \
(head)->tqh_last = &(elm)->field.tqe_next; \
(head)->tqh_first = (elm); \
(elm)->field.tqe_prev = &(head)->tqh_first; \
} while (0)
#define TAILQ_INSERT_TAIL(head, elm, field) do { \
(elm)->field.tqe_next = NULL; \
(elm)->field.tqe_prev = (head)->tqh_last; \
*(head)->tqh_last = (elm); \
(head)->tqh_last = &(elm)->field.tqe_next; \
} while (0)
#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \
if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\
(elm)->field.tqe_next->field.tqe_prev = \
&(elm)->field.tqe_next; \
else \
(head)->tqh_last = &(elm)->field.tqe_next; \
(listelm)->field.tqe_next = (elm); \
(elm)->field.tqe_prev = &(listelm)->field.tqe_next; \
} while (0)
#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \
(elm)->field.tqe_prev = (listelm)->field.tqe_prev; \
(elm)->field.tqe_next = (listelm); \
*(listelm)->field.tqe_prev = (elm); \
(listelm)->field.tqe_prev = &(elm)->field.tqe_next; \
} while (0)
#define TAILQ_REMOVE(head, elm, field) do { \
if (((elm)->field.tqe_next) != NULL) \
(elm)->field.tqe_next->field.tqe_prev = \
(elm)->field.tqe_prev; \
else \
(head)->tqh_last = (elm)->field.tqe_prev; \
*(elm)->field.tqe_prev = (elm)->field.tqe_next; \
_Q_INVALIDATE((elm)->field.tqe_prev); \
_Q_INVALIDATE((elm)->field.tqe_next); \
} while (0)
#define TAILQ_REPLACE(head, elm, elm2, field) do { \
if (((elm2)->field.tqe_next = (elm)->field.tqe_next) != NULL) \
(elm2)->field.tqe_next->field.tqe_prev = \
&(elm2)->field.tqe_next; \
else \
(head)->tqh_last = &(elm2)->field.tqe_next; \
(elm2)->field.tqe_prev = (elm)->field.tqe_prev; \
*(elm2)->field.tqe_prev = (elm2); \
_Q_INVALIDATE((elm)->field.tqe_prev); \
_Q_INVALIDATE((elm)->field.tqe_next); \
} while (0)
/*
* Circular queue definitions.
*/
#define CIRCLEQ_HEAD(name, type) \
struct name { \
struct type *cqh_first; /* first element */ \
struct type *cqh_last; /* last element */ \
}
#define CIRCLEQ_HEAD_INITIALIZER(head) \
{ CIRCLEQ_END(&head), CIRCLEQ_END(&head) }
#define CIRCLEQ_ENTRY(type) \
struct { \
struct type *cqe_next; /* next element */ \
struct type *cqe_prev; /* previous element */ \
}
/*
* Circular queue access methods
*/
#define CIRCLEQ_FIRST(head) ((head)->cqh_first)
#define CIRCLEQ_LAST(head) ((head)->cqh_last)
#define CIRCLEQ_END(head) ((void *)(head))
#define CIRCLEQ_NEXT(elm, field) ((elm)->field.cqe_next)
#define CIRCLEQ_PREV(elm, field) ((elm)->field.cqe_prev)
#define CIRCLEQ_EMPTY(head) \
(CIRCLEQ_FIRST(head) == CIRCLEQ_END(head))
#define CIRCLEQ_FOREACH(var, head, field) \
for((var) = CIRCLEQ_FIRST(head); \
(var) != CIRCLEQ_END(head); \
(var) = CIRCLEQ_NEXT(var, field))
#define CIRCLEQ_FOREACH_REVERSE(var, head, field) \
for((var) = CIRCLEQ_LAST(head); \
(var) != CIRCLEQ_END(head); \
(var) = CIRCLEQ_PREV(var, field))
/*
* Circular queue functions.
*/
#define CIRCLEQ_INIT(head) do { \
(head)->cqh_first = CIRCLEQ_END(head); \
(head)->cqh_last = CIRCLEQ_END(head); \
} while (0)
#define CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) do { \
(elm)->field.cqe_next = (listelm)->field.cqe_next; \
(elm)->field.cqe_prev = (listelm); \
if ((listelm)->field.cqe_next == CIRCLEQ_END(head)) \
(head)->cqh_last = (elm); \
else \
(listelm)->field.cqe_next->field.cqe_prev = (elm); \
(listelm)->field.cqe_next = (elm); \
} while (0)
#define CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) do { \
(elm)->field.cqe_next = (listelm); \
(elm)->field.cqe_prev = (listelm)->field.cqe_prev; \
if ((listelm)->field.cqe_prev == CIRCLEQ_END(head)) \
(head)->cqh_first = (elm); \
else \
(listelm)->field.cqe_prev->field.cqe_next = (elm); \
(listelm)->field.cqe_prev = (elm); \
} while (0)
#define CIRCLEQ_INSERT_HEAD(head, elm, field) do { \
(elm)->field.cqe_next = (head)->cqh_first; \
(elm)->field.cqe_prev = CIRCLEQ_END(head); \
if ((head)->cqh_last == CIRCLEQ_END(head)) \
(head)->cqh_last = (elm); \
else \
(head)->cqh_first->field.cqe_prev = (elm); \
(head)->cqh_first = (elm); \
} while (0)
#define CIRCLEQ_INSERT_TAIL(head, elm, field) do { \
(elm)->field.cqe_next = CIRCLEQ_END(head); \
(elm)->field.cqe_prev = (head)->cqh_last; \
if ((head)->cqh_first == CIRCLEQ_END(head)) \
(head)->cqh_first = (elm); \
else \
(head)->cqh_last->field.cqe_next = (elm); \
(head)->cqh_last = (elm); \
} while (0)
#define CIRCLEQ_REMOVE(head, elm, field) do { \
if ((elm)->field.cqe_next == CIRCLEQ_END(head)) \
(head)->cqh_last = (elm)->field.cqe_prev; \
else \
(elm)->field.cqe_next->field.cqe_prev = \
(elm)->field.cqe_prev; \
if ((elm)->field.cqe_prev == CIRCLEQ_END(head)) \
(head)->cqh_first = (elm)->field.cqe_next; \
else \
(elm)->field.cqe_prev->field.cqe_next = \
(elm)->field.cqe_next; \
_Q_INVALIDATE((elm)->field.cqe_prev); \
_Q_INVALIDATE((elm)->field.cqe_next); \
} while (0)
#define CIRCLEQ_REPLACE(head, elm, elm2, field) do { \
if (((elm2)->field.cqe_next = (elm)->field.cqe_next) == \
CIRCLEQ_END(head)) \
(head).cqh_last = (elm2); \
else \
(elm2)->field.cqe_next->field.cqe_prev = (elm2); \
if (((elm2)->field.cqe_prev = (elm)->field.cqe_prev) == \
CIRCLEQ_END(head)) \
(head).cqh_first = (elm2); \
else \
(elm2)->field.cqe_prev->field.cqe_next = (elm2); \
_Q_INVALIDATE((elm)->field.cqe_prev); \
_Q_INVALIDATE((elm)->field.cqe_next); \
} while (0)
#endif /* !_SYS_QUEUE_H_ */
| zz1126wnx-iperf3 | src/queue.h | C | bsd | 18,116 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <assert.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <pthread.h>
#include <stdint.h>
#include <netinet/tcp.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/mman.h>
#include <sched.h>
#include <setjmp.h>
#include "net.h"
#include "iperf.h"
#include "iperf_api.h"
#include "iperf_udp.h"
#include "iperf_tcp.h"
#include "timer.h"
#include "cjson.h"
#include "units.h"
#include "tcp_window_size.h"
#include "iperf_util.h"
#include "locale.h"
jmp_buf env; /* to handle longjmp on signal */
/* Forwards. */
static int send_parameters(struct iperf_test *test);
static int get_parameters(struct iperf_test *test);
static int send_results(struct iperf_test *test);
static int get_results(struct iperf_test *test);
static int JSON_write(int fd, cJSON *json);
static void print_interval_results(struct iperf_test *test, struct iperf_stream *sp, cJSON *json_interval_streams);
static cJSON *JSON_read(int fd);
/*************************** Print usage functions ****************************/
void
usage()
{
fputs(usage_shortstr, stderr);
}
void
usage_long()
{
fprintf(stderr, usage_longstr, RATE / (1024*1024), DURATION, DEFAULT_TCP_BLKSIZE / 1024, DEFAULT_UDP_BLKSIZE / 1024);
}
void warning(char *str)
{
fprintf(stderr, "warning: %s\n", str);
}
/************** Getter routines for some fields inside iperf_test *************/
int
iperf_get_control_socket(struct iperf_test *ipt)
{
return ipt->ctrl_sck;
}
int
iperf_get_test_duration(struct iperf_test *ipt)
{
return ipt->duration;
}
uint64_t
iperf_get_test_rate(struct iperf_test *ipt)
{
return ipt->settings->rate;
}
char
iperf_get_test_role(struct iperf_test *ipt)
{
return ipt->role;
}
int
iperf_get_test_blksize(struct iperf_test *ipt)
{
return ipt->settings->blksize;
}
int
iperf_get_test_socket_bufsize(struct iperf_test *ipt)
{
return ipt->settings->socket_bufsize;
}
double
iperf_get_test_reporter_interval(struct iperf_test *ipt)
{
return ipt->reporter_interval;
}
double
iperf_get_test_stats_interval(struct iperf_test *ipt)
{
return ipt->stats_interval;
}
int
iperf_get_test_num_streams(struct iperf_test *ipt)
{
return ipt->num_streams;
}
int
iperf_get_test_server_port(struct iperf_test *ipt)
{
return ipt->server_port;
}
char*
iperf_get_test_server_hostname(struct iperf_test *ipt)
{
return ipt->server_hostname;
}
int
iperf_get_test_protocol_id(struct iperf_test *ipt)
{
return ipt->protocol->id;
}
int
iperf_get_test_json_output(struct iperf_test *ipt)
{
return ipt->json_output;
}
int
iperf_get_test_zerocopy(struct iperf_test *ipt)
{
return ipt->zerocopy;
}
int
iperf_get_test_may_use_sigalrm(struct iperf_test *ipt)
{
return ipt->may_use_sigalrm;
}
/************** Setter routines for some fields inside iperf_test *************/
void
iperf_set_control_socket(struct iperf_test *ipt, int ctrl_sck)
{
ipt->ctrl_sck = ctrl_sck;
}
void
iperf_set_test_duration(struct iperf_test *ipt, int duration)
{
ipt->duration = duration;
}
void
iperf_set_test_reporter_interval(struct iperf_test *ipt, double reporter_interval)
{
ipt->reporter_interval = reporter_interval;
}
void
iperf_set_test_stats_interval(struct iperf_test *ipt, double stats_interval)
{
ipt->stats_interval = stats_interval;
}
void
iperf_set_test_state(struct iperf_test *ipt, char state)
{
ipt->state = state;
}
void
iperf_set_test_blksize(struct iperf_test *ipt, int blksize)
{
ipt->settings->blksize = blksize;
}
void
iperf_set_test_rate(struct iperf_test *ipt, uint64_t rate)
{
ipt->settings->rate = rate;
}
void
iperf_set_test_server_port(struct iperf_test *ipt, int server_port)
{
ipt->server_port = server_port;
}
void
iperf_set_test_socket_bufsize(struct iperf_test *ipt, int socket_bufsize)
{
ipt->settings->socket_bufsize = socket_bufsize;
}
void
iperf_set_test_num_streams(struct iperf_test *ipt, int num_streams)
{
ipt->num_streams = num_streams;
}
void
iperf_set_test_role(struct iperf_test *ipt, char role)
{
ipt->role = role;
}
void
iperf_set_test_server_hostname(struct iperf_test *ipt, char *server_hostname)
{
ipt->server_hostname = strdup( server_hostname );
}
void
iperf_set_test_json_output(struct iperf_test *ipt, int json_output)
{
ipt->json_output = json_output;
}
int
iperf_has_zerocopy( void )
{
return has_sendfile();
}
void
iperf_set_test_zerocopy(struct iperf_test *ipt, int zerocopy)
{
ipt->zerocopy = zerocopy;
}
void
iperf_set_test_may_use_sigalrm(struct iperf_test *ipt, int may_use_sigalrm)
{
ipt->may_use_sigalrm = may_use_sigalrm;
}
/********************** Get/set test protocol structure ***********************/
struct protocol *
get_protocol(struct iperf_test *test, int prot_id)
{
struct protocol *prot;
SLIST_FOREACH(prot, &test->protocols, protocols) {
if (prot->id == prot_id)
break;
}
if (prot == NULL)
i_errno = IEPROTOCOL;
return prot;
}
int
set_protocol(struct iperf_test *test, int prot_id)
{
struct protocol *prot = NULL;
SLIST_FOREACH(prot, &test->protocols, protocols) {
if (prot->id == prot_id) {
test->protocol = prot;
return 0;
}
}
i_errno = IEPROTOCOL;
return -1;
}
/************************** Iperf callback functions **************************/
void
iperf_on_new_stream(struct iperf_stream *sp)
{
connect_msg(sp);
}
void
iperf_on_test_start(struct iperf_test *test)
{
if (test->json_output) {
if (test->settings->bytes)
cJSON_AddItemToObject(test->json_start, "test_start", iperf_json_printf("protocol: %s num_streams: %d blksize: %d bytes: %d", test->protocol->name, (int64_t) test->num_streams, (int64_t) test->settings->blksize, (int64_t) test->settings->bytes));
else
cJSON_AddItemToObject(test->json_start, "test_start", iperf_json_printf("protocol: %s num_streams: %d blksize: %d duration: %d", test->protocol->name, (int64_t) test->num_streams, (int64_t) test->settings->blksize, (int64_t) test->duration));
} else {
if (test->verbose) {
if (test->settings->bytes)
printf(test_start_bytes, test->protocol->name, test->num_streams, test->settings->blksize, test->settings->bytes);
else
printf(test_start_time, test->protocol->name, test->num_streams, test->settings->blksize, test->duration);
}
}
}
void
iperf_on_connect(struct iperf_test *test)
{
char ipr[INET6_ADDRSTRLEN];
int port;
struct sockaddr_storage sa;
struct sockaddr_in *sa_inP;
struct sockaddr_in6 *sa_in6P;
socklen_t len;
int opt;
if (test->role == 'c') {
if (test->json_output)
cJSON_AddItemToObject(test->json_start, "connecting_to", iperf_json_printf("host: %s port: %d", test->server_hostname, (int64_t) test->server_port));
else
printf("Connecting to host %s, port %d\n", test->server_hostname, test->server_port);
} else {
len = sizeof(sa);
getpeername(test->ctrl_sck, (struct sockaddr *) &sa, &len);
if (getsockdomain(test->ctrl_sck) == AF_INET) {
sa_inP = (struct sockaddr_in *) &sa;
inet_ntop(AF_INET, &sa_inP->sin_addr, ipr, sizeof(ipr));
port = ntohs(sa_inP->sin_port);
if (test->json_output)
cJSON_AddItemToObject(test->json_start, "accepted_connection", iperf_json_printf("host: %s port: %d", ipr, (int64_t) port));
else
printf("Accepted connection from %s, port %d\n", ipr, port);
} else {
sa_in6P = (struct sockaddr_in6 *) &sa;
inet_ntop(AF_INET6, &sa_in6P->sin6_addr, ipr, sizeof(ipr));
port = ntohs(sa_in6P->sin6_port);
if (test->json_output)
cJSON_AddItemToObject(test->json_start, "accepted_connection", iperf_json_printf("host: %s port: %d", ipr, (int64_t) port));
else
printf("Accepted connection from %s, port %d\n", ipr, port);
}
}
if (test->json_output) {
cJSON_AddStringToObject(test->json_start, "cookie", test->cookie);
if (test->protocol->id == SOCK_STREAM)
cJSON_AddIntToObject(test->json_start, "tcp_mss", test->settings->mss);
else {
len = sizeof(opt);
getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len);
cJSON_AddIntToObject(test->json_start, "tcp_mss_default", opt);
}
} else if (test->verbose) {
printf(" Cookie: %s\n", test->cookie);
if (test->protocol->id == SOCK_STREAM) {
if (test->settings->mss)
printf(" TCP MSS: %d\n", test->settings->mss);
else {
len = sizeof(opt);
getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len);
printf(" TCP MSS: %d (default)\n", opt);
}
}
}
}
void
iperf_on_test_finish(struct iperf_test *test)
{
}
/******************************************************************************/
int
iperf_parse_arguments(struct iperf_test *test, int argc, char **argv)
{
static struct option longopts[] =
{
{"port", required_argument, NULL, 'p'},
{"format", required_argument, NULL, 'f'},
{"interval", required_argument, NULL, 'i'},
{"daemon", no_argument, NULL, 'D'},
{"verbose", no_argument, NULL, 'V'},
{"json", no_argument, NULL, 'J'},
{"debug", no_argument, NULL, 'd'},
{"version", no_argument, NULL, 'v'},
{"server", no_argument, NULL, 's'},
{"client", required_argument, NULL, 'c'},
{"udp", no_argument, NULL, 'u'},
{"bandwidth", required_argument, NULL, 'b'},
{"time", required_argument, NULL, 't'},
{"bytes", required_argument, NULL, 'n'},
{"length", required_argument, NULL, 'l'},
{"parallel", required_argument, NULL, 'P'},
{"reverse", no_argument, NULL, 'R'},
{"window", required_argument, NULL, 'w'},
{"bind", required_argument, NULL, 'B'},
{"set-mss", required_argument, NULL, 'M'},
{"no-delay", no_argument, NULL, 'N'},
{"version6", no_argument, NULL, '6'},
{"tos", required_argument, NULL, 'S'},
{"zerocopy", no_argument, NULL, 'Z'},
{"help", no_argument, NULL, 'h'},
/* XXX: The following ifdef needs to be split up. linux-congestion is not necessarily supported
* by systems that support tos.
*/
#ifdef ADD_WHEN_SUPPORTED
{"tos", required_argument, NULL, 'S'},
{"linux-congestion", required_argument, NULL, 'L'},
#endif
{NULL, 0, NULL, 0}
};
int flag;
int blksize;
int server_flag, client_flag;
blksize = 0;
server_flag = client_flag = 0;
while ((flag = getopt_long(argc, argv, "p:f:i:DVJdvsc:ub:t:n:l:P:Rw:B:M:N46S:Zh", longopts, NULL)) != -1) {
switch (flag) {
case 'p':
test->server_port = atoi(optarg);
break;
case 'f':
test->settings->unit_format = *optarg;
break;
case 'i':
/* XXX: could potentially want separate stat collection and reporting intervals,
but just set them to be the same for now */
test->stats_interval = atof(optarg);
test->reporter_interval = atof(optarg);
if (test->stats_interval > MAX_INTERVAL) {
i_errno = IEINTERVAL;
return -1;
}
break;
case 'D':
test->daemon = 1;
server_flag = 1;
break;
case 'V':
test->verbose = 1;
break;
case 'J':
test->json_output = 1;
break;
case 'd':
test->debug = 1;
break;
case 'v':
fputs(version, stdout);
system("uname -a");
exit(0);
case 's':
if (test->role == 'c') {
i_errno = IESERVCLIENT;
return -1;
}
test->role = 's';
break;
case 'c':
if (test->role == 's') {
i_errno = IESERVCLIENT;
return -1;
}
test->role = 'c';
test->server_hostname = (char *) malloc(strlen(optarg)+1);
strncpy(test->server_hostname, optarg, strlen(optarg)+1);
break;
case 'u':
set_protocol(test, Pudp);
client_flag = 1;
break;
case 'b':
test->settings->rate = unit_atof(optarg);
client_flag = 1;
break;
case 't':
test->duration = atoi(optarg);
if (test->duration > MAX_TIME) {
i_errno = IEDURATION;
return -1;
}
client_flag = 1;
break;
case 'n':
test->settings->bytes = unit_atoi(optarg);
client_flag = 1;
break;
case 'l':
blksize = unit_atoi(optarg);
client_flag = 1;
break;
case 'P':
test->num_streams = atoi(optarg);
if (test->num_streams > MAX_STREAMS) {
i_errno = IENUMSTREAMS;
return -1;
}
client_flag = 1;
break;
case 'R':
test->reverse = 1;
client_flag = 1;
break;
case 'w':
// XXX: This is a socket buffer, not specific to TCP
test->settings->socket_bufsize = unit_atof(optarg);
if (test->settings->socket_bufsize > MAX_TCP_BUFFER) {
i_errno = IEBUFSIZE;
return -1;
}
client_flag = 1;
break;
case 'B':
test->bind_address = (char *) malloc(strlen(optarg)+1);
strncpy(test->bind_address, optarg, strlen(optarg)+1);
break;
case 'M':
test->settings->mss = atoi(optarg);
if (test->settings->mss > MAX_MSS) {
i_errno = IEMSS;
return -1;
}
client_flag = 1;
break;
case 'N':
test->no_delay = 1;
client_flag = 1;
break;
case '4':
test->settings->domain = AF_INET;
break;
case '6':
test->settings->domain = AF_INET6;
break;
case 'S':
// XXX: Checking for errors in strtol is not portable. Leave as is?
test->settings->tos = strtol(optarg, NULL, 0);
client_flag = 1;
break;
case 'Z':
if (!has_sendfile()) {
i_errno = IENOSENDFILE;
return -1;
}
test->zerocopy = 1;
client_flag = 1;
break;
case 'h':
default:
usage_long();
exit(1);
}
}
/* Check flag / role compatibility. */
if (test->role == 'c' && server_flag) {
i_errno = IESERVERONLY;
return -1;
}
if (test->role == 's' && client_flag) {
i_errno = IECLIENTONLY;
return -1;
}
if (blksize == 0) {
if (test->protocol->id == Pudp)
blksize = DEFAULT_UDP_BLKSIZE;
else
blksize = DEFAULT_TCP_BLKSIZE;
}
if (blksize <= 0 || blksize > MAX_BLOCKSIZE) {
i_errno = IEBLOCKSIZE;
return -1;
}
test->settings->blksize = blksize;
/* For subsequent calls to getopt */
#ifdef __APPLE__
optreset = 1;
#endif
optind = 0;
if ((test->role != 'c') && (test->role != 's')) {
i_errno = IENOROLE;
return -1;
}
return 0;
}
int
iperf_send(struct iperf_test *test, fd_set *write_setP)
{
register int multisend, r;
register struct iperf_stream *sp;
/* Can we do multisend mode? */
if (test->protocol->id == Pudp && test->settings->rate != 0)
multisend = 1; /* nope */
else
multisend = test->multisend;
for (; multisend > 0; --multisend) {
SLIST_FOREACH(sp, &test->streams, streams) {
if (write_setP == NULL || FD_ISSET(sp->socket, write_setP)) {
if ((r = sp->snd(sp)) < 0) {
if (r == NET_SOFTERROR)
break;
i_errno = IESTREAMWRITE;
return r;
}
test->bytes_sent += r;
if (multisend > 1 && test->settings->bytes != 0 && test->bytes_sent >= test->settings->bytes)
break;
}
}
}
if (write_setP != NULL)
SLIST_FOREACH(sp, &test->streams, streams)
if (FD_ISSET(sp->socket, write_setP))
FD_CLR(sp->socket, write_setP);
return 0;
}
int
iperf_recv(struct iperf_test *test, fd_set *read_setP)
{
int r;
struct iperf_stream *sp;
SLIST_FOREACH(sp, &test->streams, streams) {
if (FD_ISSET(sp->socket, read_setP)) {
if ((r = sp->rcv(sp)) < 0) {
i_errno = IESTREAMREAD;
return r;
}
test->bytes_sent += r;
FD_CLR(sp->socket, read_setP);
}
}
return 0;
}
static void
test_timer_proc(TimerClientData client_data, struct timeval *nowP)
{
struct iperf_test *test = client_data.p;
test->done = 1;
test->timer = NULL;
}
static void
stats_timer_proc(TimerClientData client_data, struct timeval *nowP)
{
struct iperf_test *test = client_data.p;
if (test->done)
return;
test->stats_callback(test);
}
static void
reporter_timer_proc(TimerClientData client_data, struct timeval *nowP)
{
struct iperf_test *test = client_data.p;
if (test->done)
return;
test->reporter_callback(test);
}
int
iperf_init_test(struct iperf_test *test)
{
struct iperf_stream *sp;
struct timeval now;
TimerClientData cd;
if (test->protocol->init) {
if (test->protocol->init(test) < 0)
return -1;
}
/* Create timers. */
if (gettimeofday(&now, NULL) < 0) {
i_errno = IEINITTEST;
return -1;
}
if (test->settings->bytes == 0) {
test->done = 0;
cd.p = test;
test->timer = tmr_create(&now, test_timer_proc, cd, test->duration * SEC_TO_US, 0);
if (test->timer == NULL)
return -1;
}
if (test->stats_interval != 0) {
cd.p = test;
test->stats_timer = tmr_create(&now, stats_timer_proc, cd, test->stats_interval * SEC_TO_US, 1);
if (test->stats_timer == NULL)
return -1;
}
if (test->reporter_interval != 0) {
cd.p = test;
test->reporter_timer = tmr_create(&now, reporter_timer_proc, cd, test->reporter_interval * SEC_TO_US, 1);
if (test->reporter_timer == NULL)
return -1;
}
/* Set start time */
SLIST_FOREACH(sp, &test->streams, streams)
sp->result->start_time = now;
if (test->on_test_start)
test->on_test_start(test);
return 0;
}
/**
* iperf_exchange_parameters - handles the param_Exchange part for client
*
*/
int
iperf_exchange_parameters(struct iperf_test *test)
{
int s, msg;
char state;
if (test->role == 'c') {
if (send_parameters(test) < 0)
return -1;
} else {
if (get_parameters(test) < 0)
return -1;
if ((s = test->protocol->listen(test)) < 0) {
state = SERVER_ERROR;
if (Nwrite(test->ctrl_sck, &state, sizeof(state), Ptcp) < 0) {
i_errno = IESENDMESSAGE;
return -1;
}
msg = htonl(i_errno);
if (Nwrite(test->ctrl_sck, (char*) &msg, sizeof(msg), Ptcp) < 0) {
i_errno = IECTRLWRITE;
return -1;
}
msg = htonl(errno);
if (Nwrite(test->ctrl_sck, (char*) &msg, sizeof(msg), Ptcp) < 0) {
i_errno = IECTRLWRITE;
return -1;
}
return -1;
}
FD_SET(s, &test->read_set);
test->max_fd = (s > test->max_fd) ? s : test->max_fd;
test->prot_listener = s;
// Send the control message to create streams and start the test
test->state = CREATE_STREAMS;
if (Nwrite(test->ctrl_sck, &test->state, sizeof(char), Ptcp) < 0) {
i_errno = IESENDMESSAGE;
return -1;
}
}
return 0;
}
/*************************************************************/
int
iperf_exchange_results(struct iperf_test *test)
{
if (test->role == 'c') {
/* Send results to server. */
if (send_results(test) < 0)
return -1;
/* Get server results. */
if (get_results(test) < 0)
return -1;
} else {
/* Get client results. */
if (get_results(test) < 0)
return -1;
/* Send results to client. */
if (send_results(test) < 0)
return -1;
}
return 0;
}
/*************************************************************/
static int
send_parameters(struct iperf_test *test)
{
int r = 0;
cJSON *j;
j = cJSON_CreateObject();
if (j == NULL) {
i_errno = IESENDPARAMS;
r = -1;
} else {
if (test->protocol->id == Ptcp)
cJSON_AddTrueToObject(j, "tcp");
else if (test->protocol->id == Pudp)
cJSON_AddTrueToObject(j, "udp");
if (test->duration)
cJSON_AddIntToObject(j, "time", test->duration);
if (test->settings->bytes)
cJSON_AddIntToObject(j, "num", test->settings->bytes);
if (test->settings->mss)
cJSON_AddIntToObject(j, "MSS", test->settings->mss);
if (test->no_delay)
cJSON_AddTrueToObject(j, "nodelay");
cJSON_AddIntToObject(j, "parallel", test->num_streams);
if (test->reverse)
cJSON_AddTrueToObject(j, "reverse");
if (test->settings->socket_bufsize)
cJSON_AddIntToObject(j, "window", test->settings->socket_bufsize);
if (test->settings->blksize)
cJSON_AddIntToObject(j, "len", test->settings->blksize);
if (test->settings->rate)
cJSON_AddIntToObject(j, "bandwidth", test->settings->rate);
if (test->settings->tos)
cJSON_AddIntToObject(j, "TOS", test->settings->tos);
if (JSON_write(test->ctrl_sck, j) < 0) {
i_errno = IESENDPARAMS;
r = -1;
}
cJSON_Delete(j);
}
return r;
}
/*************************************************************/
static int
get_parameters(struct iperf_test *test)
{
int r = 0;
cJSON *j;
cJSON *j_p;
j = JSON_read(test->ctrl_sck);
if (j == NULL) {
i_errno = IERECVPARAMS;
r = -1;
} else {
if ((j_p = cJSON_GetObjectItem(j, "tcp")) != NULL)
set_protocol(test, Ptcp);
if ((j_p = cJSON_GetObjectItem(j, "udp")) != NULL)
set_protocol(test, Pudp);
if ((j_p = cJSON_GetObjectItem(j, "time")) != NULL)
test->duration = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "num")) != NULL)
test->settings->bytes = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "MSS")) != NULL)
test->settings->mss = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "nodelay")) != NULL)
test->no_delay = 1;
if ((j_p = cJSON_GetObjectItem(j, "parallel")) != NULL)
test->num_streams = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "reverse")) != NULL)
test->reverse = 1;
if ((j_p = cJSON_GetObjectItem(j, "window")) != NULL)
test->settings->socket_bufsize = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "len")) != NULL)
test->settings->blksize = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "bandwidth")) != NULL)
test->settings->rate = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "TOS")) != NULL)
test->settings->tos = j_p->valueint;
cJSON_Delete(j);
}
return r;
}
/*************************************************************/
static int
send_results(struct iperf_test *test)
{
int r = 0;
cJSON *j;
cJSON *j_streams;
struct iperf_stream *sp;
cJSON *j_stream;
iperf_size_t bytes_transferred;
j = cJSON_CreateObject();
if (j == NULL) {
i_errno = IEPACKAGERESULTS;
r = -1;
} else {
cJSON_AddFloatToObject(j, "cpu_util", test->cpu_util);
j_streams = cJSON_CreateArray();
if (j_streams == NULL) {
i_errno = IEPACKAGERESULTS;
r = -1;
} else {
cJSON_AddItemToObject(j, "streams", j_streams);
SLIST_FOREACH(sp, &test->streams, streams) {
j_stream = cJSON_CreateObject();
if (j_stream == NULL) {
i_errno = IEPACKAGERESULTS;
r = -1;
} else {
cJSON_AddItemToArray(j_streams, j_stream);
if (test->role == 'c')
bytes_transferred = (test->reverse ? sp->result->bytes_received : sp->result->bytes_sent);
else
bytes_transferred = (test->reverse ? sp->result->bytes_sent : sp->result->bytes_received);
cJSON_AddIntToObject(j_stream, "id", sp->id);
cJSON_AddIntToObject(j_stream, "bytes", bytes_transferred);
cJSON_AddFloatToObject(j_stream, "jitter", sp->jitter);
cJSON_AddIntToObject(j_stream, "errors", sp->cnt_error);
cJSON_AddIntToObject(j_stream, "packets", sp->packet_count);
}
}
if (r == 0 && JSON_write(test->ctrl_sck, j) < 0) {
i_errno = IESENDRESULTS;
r = -1;
}
}
cJSON_Delete(j);
}
return r;
}
/*************************************************************/
static int
get_results(struct iperf_test *test)
{
int r = 0;
cJSON *j;
cJSON *j_cpu_util;
cJSON *j_streams;
int n, i;
cJSON *j_stream;
cJSON *j_id;
cJSON *j_bytes;
cJSON *j_jitter;
cJSON *j_errors;
cJSON *j_packets;
int sid, cerror, pcount;
double jitter;
iperf_size_t bytes_transferred;
struct iperf_stream *sp;
j = JSON_read(test->ctrl_sck);
if (j == NULL) {
i_errno = IERECVRESULTS;
r = -1;
} else {
j_cpu_util = cJSON_GetObjectItem(j, "cpu_util");
if (j_cpu_util == NULL) {
i_errno = IERECVRESULTS;
r = -1;
} else {
test->remote_cpu_util = j_cpu_util->valuefloat;
j_streams = cJSON_GetObjectItem(j, "streams");
if (j_streams == NULL) {
i_errno = IERECVRESULTS;
r = -1;
} else {
n = cJSON_GetArraySize(j_streams);
for (i=0; i<n; ++i) {
j_stream = cJSON_GetArrayItem(j_streams, i);
if (j_stream == NULL) {
i_errno = IERECVRESULTS;
r = -1;
} else {
j_id = cJSON_GetObjectItem(j_stream, "id");
j_bytes = cJSON_GetObjectItem(j_stream, "bytes");
j_jitter = cJSON_GetObjectItem(j_stream, "jitter");
j_errors = cJSON_GetObjectItem(j_stream, "errors");
j_packets = cJSON_GetObjectItem(j_stream, "packets");
if (j_id == NULL || j_bytes == NULL || j_jitter == NULL || j_errors == NULL || j_packets == NULL) {
i_errno = IERECVRESULTS;
r = -1;
} else {
sid = j_id->valueint;
bytes_transferred = j_bytes->valueint;
jitter = j_jitter->valuefloat;
cerror = j_errors->valueint;
pcount = j_packets->valueint;
SLIST_FOREACH(sp, &test->streams, streams)
if (sp->id == sid) break;
if (sp == NULL) {
i_errno = IESTREAMID;
r = -1;
} else {
if ((test->role == 'c' && !test->reverse) || (test->role == 's' && test->reverse)) {
sp->jitter = jitter;
sp->cnt_error = cerror;
sp->packet_count = pcount;
sp->result->bytes_received = bytes_transferred;
} else
sp->result->bytes_sent = bytes_transferred;
}
}
}
}
}
}
cJSON_Delete(j);
}
return r;
}
/*************************************************************/
static int
JSON_write(int fd, cJSON *json)
{
unsigned int hsize, nsize;
char *str;
int r = 0;
str = cJSON_PrintUnformatted(json);
if (str == NULL)
r = -1;
else {
hsize = strlen(str);
nsize = htonl(hsize);
if (Nwrite(fd, (char*) &nsize, sizeof(nsize), Ptcp) < 0)
r = -1;
else {
if (Nwrite(fd, str, hsize, Ptcp) < 0)
r = -1;
}
free(str);
}
return r;
}
/*************************************************************/
static cJSON *
JSON_read(int fd)
{
unsigned int hsize, nsize;
char *str;
cJSON *json = NULL;
if (Nread(fd, (char*) &nsize, sizeof(nsize), Ptcp) >= 0) {
hsize = ntohl(nsize);
str = (char *) malloc((hsize+1) * sizeof(char)); /* +1 for EOS */
if (str != NULL) {
if (Nread(fd, str, hsize, Ptcp) >= 0) {
str[hsize] = '\0'; /* add the EOS */
json = cJSON_Parse(str);
}
}
free(str);
}
return json;
}
/*************************************************************/
/**
* add_to_interval_list -- adds new interval to the interval_list
*/
void
add_to_interval_list(struct iperf_stream_result * rp, struct iperf_interval_results * new)
{
struct iperf_interval_results *irp;
irp = (struct iperf_interval_results *) malloc(sizeof(struct iperf_interval_results));
memcpy(irp, new, sizeof(struct iperf_interval_results));
TAILQ_INSERT_TAIL(&rp->interval_results, irp, irlistentries);
}
/************************************************************/
/**
* connect_msg -- displays connection message
* denoting sender/receiver details
*
*/
void
connect_msg(struct iperf_stream *sp)
{
char ipl[INET6_ADDRSTRLEN], ipr[INET6_ADDRSTRLEN];
int lport, rport;
if (getsockdomain(sp->socket) == AF_INET) {
inet_ntop(AF_INET, (void *) &((struct sockaddr_in *) &sp->local_addr)->sin_addr, ipl, sizeof(ipl));
inet_ntop(AF_INET, (void *) &((struct sockaddr_in *) &sp->remote_addr)->sin_addr, ipr, sizeof(ipr));
lport = ntohs(((struct sockaddr_in *) &sp->local_addr)->sin_port);
rport = ntohs(((struct sockaddr_in *) &sp->remote_addr)->sin_port);
} else {
inet_ntop(AF_INET6, (void *) &((struct sockaddr_in6 *) &sp->local_addr)->sin6_addr, ipl, sizeof(ipl));
inet_ntop(AF_INET6, (void *) &((struct sockaddr_in6 *) &sp->remote_addr)->sin6_addr, ipr, sizeof(ipr));
lport = ntohs(((struct sockaddr_in6 *) &sp->local_addr)->sin6_port);
rport = ntohs(((struct sockaddr_in6 *) &sp->remote_addr)->sin6_port);
}
if (sp->test->json_output)
cJSON_AddItemToObject(sp->test->json_start, "connected", iperf_json_printf("socket: %d local_host: %s local_port: %d remote_host: %s remote_port: %d", (int64_t) sp->socket, ipl, (int64_t) lport, ipr, (int64_t) rport));
else
printf("[%3d] local %s port %d connected to %s port %d\n", sp->socket, ipl, lport, ipr, rport);
}
/**************************************************************************/
struct iperf_test *
iperf_new_test()
{
struct iperf_test *test;
test = (struct iperf_test *) malloc(sizeof(struct iperf_test));
if (!test) {
i_errno = IENEWTEST;
return NULL;
}
/* initialize everything to zero */
memset(test, 0, sizeof(struct iperf_test));
test->settings = (struct iperf_settings *) malloc(sizeof(struct iperf_settings));
memset(test->settings, 0, sizeof(struct iperf_settings));
return test;
}
/**************************************************************************/
int
iperf_defaults(struct iperf_test *testp)
{
testp->duration = DURATION;
testp->server_port = PORT;
testp->ctrl_sck = -1;
testp->prot_listener = -1;
testp->stats_callback = iperf_stats_callback;
testp->reporter_callback = iperf_reporter_callback;
testp->stats_interval = 0;
testp->reporter_interval = 0;
testp->num_streams = 1;
testp->settings->domain = AF_UNSPEC;
testp->settings->unit_format = 'a';
testp->settings->socket_bufsize = 0; /* use autotuning */
testp->settings->blksize = DEFAULT_TCP_BLKSIZE;
testp->settings->rate = RATE; /* UDP only */
testp->settings->mss = 0;
testp->settings->bytes = 0;
memset(testp->cookie, 0, COOKIE_SIZE);
testp->multisend = 10; /* arbitrary */
testp->may_use_sigalrm = 0;
/* Set up protocol list */
SLIST_INIT(&testp->streams);
SLIST_INIT(&testp->protocols);
struct protocol *tcp, *udp;
tcp = (struct protocol *) malloc(sizeof(struct protocol));
if (!tcp)
return -1;
memset(tcp, 0, sizeof(struct protocol));
udp = (struct protocol *) malloc(sizeof(struct protocol));
if (!udp)
return -1;
memset(udp, 0, sizeof(struct protocol));
tcp->id = Ptcp;
tcp->name = "TCP";
tcp->accept = iperf_tcp_accept;
tcp->listen = iperf_tcp_listen;
tcp->connect = iperf_tcp_connect;
tcp->send = iperf_tcp_send;
tcp->recv = iperf_tcp_recv;
tcp->init = NULL;
SLIST_INSERT_HEAD(&testp->protocols, tcp, protocols);
udp->id = Pudp;
udp->name = "UDP";
udp->accept = iperf_udp_accept;
udp->listen = iperf_udp_listen;
udp->connect = iperf_udp_connect;
udp->send = iperf_udp_send;
udp->recv = iperf_udp_recv;
udp->init = iperf_udp_init;
SLIST_INSERT_AFTER(tcp, udp, protocols);
set_protocol(testp, Ptcp);
testp->on_new_stream = iperf_on_new_stream;
testp->on_test_start = iperf_on_test_start;
testp->on_connect = iperf_on_connect;
testp->on_test_finish = iperf_on_test_finish;
return 0;
}
/**************************************************************************/
void
iperf_free_test(struct iperf_test *test)
{
struct protocol *prot;
struct iperf_stream *sp;
/* Free streams */
while (!SLIST_EMPTY(&test->streams)) {
sp = SLIST_FIRST(&test->streams);
SLIST_REMOVE_HEAD(&test->streams, streams);
iperf_free_stream(sp);
}
free(test->server_hostname);
free(test->bind_address);
free(test->settings);
if (test->timer != NULL)
tmr_cancel(test->timer);
if (test->stats_timer != NULL)
tmr_cancel(test->stats_timer);
if (test->reporter_timer != NULL)
tmr_cancel(test->reporter_timer);
/* Free protocol list */
while (!SLIST_EMPTY(&test->protocols)) {
prot = SLIST_FIRST(&test->protocols);
SLIST_REMOVE_HEAD(&test->protocols, protocols);
free(prot);
}
/* XXX: Why are we setting these values to NULL? */
// test->streams = NULL;
test->stats_callback = NULL;
test->reporter_callback = NULL;
free(test);
}
void
iperf_reset_test(struct iperf_test *test)
{
struct iperf_stream *sp;
/* Free streams */
while (!SLIST_EMPTY(&test->streams)) {
sp = SLIST_FIRST(&test->streams);
SLIST_REMOVE_HEAD(&test->streams, streams);
iperf_free_stream(sp);
}
if (test->timer != NULL) {
tmr_cancel(test->timer);
test->timer = NULL;
}
if (test->stats_timer != NULL) {
tmr_cancel(test->stats_timer);
test->stats_timer = NULL;
}
if (test->reporter_timer != NULL) {
tmr_cancel(test->reporter_timer);
test->reporter_timer = NULL;
}
SLIST_INIT(&test->streams);
test->role = 's';
set_protocol(test, Ptcp);
test->duration = DURATION;
test->state = 0;
test->server_hostname = NULL;
test->ctrl_sck = -1;
test->prot_listener = -1;
test->bytes_sent = 0;
test->reverse = 0;
test->no_delay = 0;
FD_ZERO(&test->read_set);
FD_ZERO(&test->write_set);
test->num_streams = 1;
test->settings->socket_bufsize = 0;
test->settings->blksize = DEFAULT_TCP_BLKSIZE;
test->settings->rate = RATE; /* UDP only */
test->settings->mss = 0;
memset(test->cookie, 0, COOKIE_SIZE);
test->multisend = 10; /* arbitrary */
}
/**************************************************************************/
/**
* iperf_stats_callback -- handles the statistic gathering for both the client and server
*
* XXX: This function needs to be updated to reflect the new code
*/
void
iperf_stats_callback(struct iperf_test *test)
{
struct iperf_stream *sp;
struct iperf_stream_result *rp = NULL;
struct iperf_interval_results *irp, temp;
int prev_total_retransmits;
SLIST_FOREACH(sp, &test->streams, streams) {
rp = sp->result;
if ((test->role == 'c' && !test->reverse) || (test->role == 's' && test->reverse))
temp.bytes_transferred = rp->bytes_sent_this_interval;
else
temp.bytes_transferred = rp->bytes_received_this_interval;
irp = TAILQ_FIRST(&rp->interval_results);
/* result->end_time contains timestamp of previous interval */
if ( irp != NULL ) /* not the 1st interval */
memcpy(&temp.interval_start_time, &rp->end_time, sizeof(struct timeval));
else /* or use timestamp from beginning */
memcpy(&temp.interval_start_time, &rp->start_time, sizeof(struct timeval));
/* now save time of end of this interval */
gettimeofday(&rp->end_time, NULL);
memcpy(&temp.interval_end_time, &rp->end_time, sizeof(struct timeval));
temp.interval_duration = timeval_diff(&temp.interval_start_time, &temp.interval_end_time);
//temp.interval_duration = timeval_diff(&temp.interval_start_time, &temp.interval_end_time);
if (test->protocol->id == Ptcp && has_tcpinfo()) {
save_tcpinfo(sp, &temp);
if (has_tcpinfo_retransmits()) {
irp = TAILQ_LAST(&rp->interval_results, irlisthead);
if (irp == NULL)
prev_total_retransmits = 0;
else
prev_total_retransmits = get_tcpinfo_total_retransmits(irp);
temp.this_retrans = get_tcpinfo_total_retransmits(&temp) - prev_total_retransmits;
}
}
add_to_interval_list(rp, &temp);
rp->bytes_sent_this_interval = rp->bytes_received_this_interval = 0;
}
}
static void
iperf_print_intermediate(struct iperf_test *test)
{
char ubuf[UNIT_LEN];
char nbuf[UNIT_LEN];
struct iperf_stream *sp = NULL;
struct iperf_interval_results *irp;
iperf_size_t bytes = 0;
double bandwidth;
long retransmits = 0;
double start_time, end_time;
cJSON *json_interval;
cJSON *json_interval_streams;
if (test->json_output) {
json_interval = cJSON_CreateObject();
if (json_interval == NULL)
return;
cJSON_AddItemToArray(test->json_intervals, json_interval);
json_interval_streams = cJSON_CreateArray();
if (json_interval_streams == NULL)
return;
cJSON_AddItemToObject(json_interval, "streams", json_interval_streams);
} else {
json_interval = NULL;
json_interval_streams = NULL;
}
SLIST_FOREACH(sp, &test->streams, streams) {
print_interval_results(test, sp, json_interval_streams);
/* sum up all streams */
irp = TAILQ_LAST(&sp->result->interval_results, irlisthead);
if (irp == NULL) {
iperf_err(test, "iperf_print_intermediate error: interval_results is NULL");
return;
}
bytes += irp->bytes_transferred;
if (test->protocol->id == Ptcp && has_tcpinfo_retransmits())
retransmits += irp->this_retrans;
}
if (bytes < 0) { /* this can happen if timer goes off just when client exits */
iperf_err(test, "error: bytes < 0!");
return;
}
/* next build string with sum of all streams */
if (test->num_streams > 1) {
sp = SLIST_FIRST(&test->streams); /* reset back to 1st stream */
irp = TAILQ_LAST(&sp->result->interval_results, irlisthead); /* use 1st stream for timing info */
unit_snprintf(ubuf, UNIT_LEN, (double) bytes, 'A');
bandwidth = (double) bytes / (double) irp->interval_duration;
unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
start_time = timeval_diff(&sp->result->start_time,&irp->interval_start_time);
end_time = timeval_diff(&sp->result->start_time,&irp->interval_end_time);
if (test->protocol->id == Ptcp && has_tcpinfo_retransmits()) {
if (test->json_output)
cJSON_AddItemToObject(json_interval, "sum", iperf_json_printf("start: %f end: %f seconds: %f bytes: %d bits_per_second: %f retransmits: %d", (double) start_time, (double) end_time, (double) irp->interval_duration, (int64_t) bytes, bandwidth * 8, (int64_t) retransmits));
else
printf(report_sum_bw_retrans_format, start_time, end_time, ubuf, nbuf, retransmits);
} else {
if (test->json_output)
cJSON_AddItemToObject(json_interval, "sum", iperf_json_printf("start: %f end: %f seconds: %f bytes: %d bits_per_second: %f", (double) start_time, (double) end_time, (double) irp->interval_duration, (int64_t) bytes, bandwidth * 8));
else
printf(report_sum_bw_format, start_time, end_time, ubuf, nbuf);
}
}
}
static void
iperf_print_results(struct iperf_test *test)
{
cJSON *json_summary_streams = NULL;
cJSON *json_summary_stream = NULL;
long retransmits = 0, total_retransmits = 0;
int total_packets = 0, lost_packets = 0;
char ubuf[UNIT_LEN];
char nbuf[UNIT_LEN];
struct iperf_stream *sp = NULL;
iperf_size_t bytes_sent, total_sent = 0;
iperf_size_t bytes_received, total_received = 0;
double start_time, end_time, avg_jitter, loss_percent;
double bandwidth, out_of_order_percent;
/* print final summary for all intervals */
if (test->json_output) {
json_summary_streams = cJSON_CreateArray();
if (json_summary_streams == NULL)
return;
cJSON_AddItemToObject(test->json_end, "streams", json_summary_streams);
} else {
if (test->verbose)
printf("Test Complete. Summary Results:\n");
if (test->protocol->id == Ptcp)
if (has_tcpinfo_retransmits())
fputs(report_bw_retrans_header, stdout);
else
fputs(report_bw_header, stdout);
else
fputs(report_bw_udp_header, stdout);
}
start_time = 0.;
sp = SLIST_FIRST(&test->streams);
end_time = timeval_diff(&sp->result->start_time, &sp->result->end_time);
avg_jitter = 0;
SLIST_FOREACH(sp, &test->streams, streams) {
if (test->json_output) {
json_summary_stream = cJSON_CreateObject();
if (json_summary_stream == NULL)
return;
cJSON_AddItemToArray(json_summary_streams, json_summary_stream);
}
bytes_sent = sp->result->bytes_sent;
bytes_received = sp->result->bytes_received;
total_sent += bytes_sent;
total_received += bytes_received;
if (test->protocol->id == Ptcp) {
if (has_tcpinfo_retransmits()) {
retransmits = get_tcpinfo_total_retransmits(TAILQ_LAST(&sp->result->interval_results, irlisthead));
total_retransmits += retransmits;
}
} else {
total_packets += sp->packet_count;
lost_packets += sp->cnt_error;
avg_jitter += sp->jitter;
}
if (bytes_sent > 0) {
unit_snprintf(ubuf, UNIT_LEN, (double) bytes_sent, 'A');
bandwidth = (double) bytes_sent / (double) end_time;
unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
if (test->protocol->id == Ptcp) {
if (!test->json_output)
fputs(" Sent\n", stdout);
if (has_tcpinfo_retransmits()) {
if (test->json_output)
cJSON_AddItemToObject(json_summary_stream, "sent", iperf_json_printf("socket: %d start: %f end: %f seconds: %f bytes: %d bits_per_second: %f retransmits: %d", (int64_t) sp->socket, (double) start_time, (double) end_time, (double) end_time, (int64_t) bytes_sent, bandwidth * 8, (int64_t) retransmits));
else
printf(report_bw_retrans_format, sp->socket, start_time, end_time, ubuf, nbuf, retransmits);
} else {
if (test->json_output)
cJSON_AddItemToObject(json_summary_stream, "sent", iperf_json_printf("socket: %d start: %f end: %f seconds: %f bytes: %d bits_per_second: %f", (int64_t) sp->socket, (double) start_time, (double) end_time, (double) end_time, (int64_t) bytes_sent, bandwidth * 8));
else
printf(report_bw_format, sp->socket, start_time, end_time, ubuf, nbuf);
}
} else {
out_of_order_percent = 100.0 * sp->cnt_error / sp->packet_count;
if (test->json_output)
cJSON_AddItemToObject(json_summary_stream, "udp", iperf_json_printf("socket: %d start: %f end: %f seconds: %f bytes: %d bits_per_second: %f jitter_ms: %f outoforder: %d packets: %d percent: %f", (int64_t) sp->socket, (double) start_time, (double) end_time, (double) end_time, (int64_t) bytes_sent, bandwidth * 8, (double) sp->jitter * 1000.0, (int64_t) sp->cnt_error, (int64_t) sp->packet_count, out_of_order_percent));
else {
printf(report_bw_udp_format, sp->socket, start_time, end_time, ubuf, nbuf, sp->jitter * 1000.0, sp->cnt_error, sp->packet_count, out_of_order_percent);
if (test->role == 'c')
printf(report_datagrams, sp->socket, sp->packet_count);
if (sp->outoforder_packets > 0)
printf(report_sum_outoforder, start_time, end_time, sp->cnt_error);
}
}
}
if (bytes_received > 0) {
unit_snprintf(ubuf, UNIT_LEN, (double) bytes_received, 'A');
bandwidth = (double) bytes_received / (double) end_time;
unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
if (test->protocol->id == Ptcp) {
if (!test->json_output)
printf(" Received\n");
if (test->json_output)
cJSON_AddItemToObject(json_summary_stream, "received", iperf_json_printf("socket: %d start: %f end: %f seconds: %f bytes: %d bits_per_second: %f", (int64_t) sp->socket, (double) start_time, (double) end_time, (double) end_time, (int64_t) bytes_received, bandwidth * 8));
else
printf(report_bw_format, sp->socket, start_time, end_time, ubuf, nbuf);
}
}
}
if (test->num_streams > 1) {
unit_snprintf(ubuf, UNIT_LEN, (double) total_sent, 'A');
bandwidth = (double) total_sent / (double) end_time;
unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
if (test->protocol->id == Ptcp) {
if (!test->json_output)
printf(" Total sent\n");
if (has_tcpinfo_retransmits()) {
if (test->json_output)
cJSON_AddItemToObject(test->json_end, "sum_sent", iperf_json_printf("start: %f end: %f seconds: %f bytes: %d bits_per_second: %f retransmits: %d", (double) start_time, (double) end_time, (double) end_time, (int64_t) total_sent, bandwidth * 8, (int64_t) total_retransmits));
else
printf(report_sum_bw_retrans_format, start_time, end_time, ubuf, nbuf, total_retransmits);
} else {
if (test->json_output)
cJSON_AddItemToObject(test->json_end, "sum_sent", iperf_json_printf("start: %f end: %f seconds: %f bytes: %d bits_per_second: %f", (double) start_time, (double) end_time, (double) end_time, (int64_t) total_sent, bandwidth * 8));
else
printf(report_sum_bw_format, start_time, end_time, ubuf, nbuf);
}
unit_snprintf(ubuf, UNIT_LEN, (double) total_received, 'A');
bandwidth = (double) total_received / (double) end_time;
unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
if (!test->json_output)
printf(" Total received\n");
if (test->json_output)
cJSON_AddItemToObject(test->json_end, "sum_received", iperf_json_printf("start: %f end: %f seconds: %f bytes: %d bits_per_second: %f", (double) start_time, (double) end_time, (double) end_time, (int64_t) total_received, bandwidth * 8));
else
printf(report_sum_bw_format, start_time, end_time, ubuf, nbuf);
} else {
avg_jitter /= test->num_streams;
loss_percent = 100.0 * lost_packets / total_packets;
if (test->json_output)
cJSON_AddItemToObject(test->json_end, "sum", iperf_json_printf("start: %f end: %f seconds: %f bytes: %d bits_per_second: %f jitter_ms: %f lost_packets: %d total_packets: %d loss_percent: %f", (double) start_time, (double) end_time, (double) end_time, (int64_t) total_sent, bandwidth * 8, avg_jitter, (int64_t) lost_packets, (int64_t) total_packets, loss_percent));
else
printf(report_sum_bw_udp_format, start_time, end_time, ubuf, nbuf, avg_jitter, lost_packets, total_packets, loss_percent);
}
}
if (test->json_output)
cJSON_AddItemToObject(test->json_end, "cpu_utilization_percent", iperf_json_printf("host: %f remote: %f", (double) test->cpu_util, (double) test->remote_cpu_util));
else if (test->verbose) {
printf("Host CPU Utilization: %.1f%%\n", test->cpu_util);
printf("Remote CPU Utilization: %.1f%%\n", test->remote_cpu_util);
}
}
/**************************************************************************/
/**
* iperf_reporter_callback -- handles the report printing
*
*/
void
iperf_reporter_callback(struct iperf_test *test)
{
switch (test->state) {
case TEST_RUNNING:
case STREAM_RUNNING:
/* print interval results for each stream */
iperf_print_intermediate(test);
break;
case DISPLAY_RESULTS:
iperf_print_intermediate(test);
iperf_print_results(test);
break;
}
}
/**************************************************************************/
static void
print_interval_results(struct iperf_test *test, struct iperf_stream *sp, cJSON *json_interval_streams)
{
char ubuf[UNIT_LEN];
char nbuf[UNIT_LEN];
double st = 0., et = 0.;
struct iperf_interval_results *irp = NULL;
double bandwidth;
irp = TAILQ_LAST(&sp->result->interval_results, irlisthead); /* get last entry in linked list */
if (irp == NULL) {
iperf_err(test, "print_interval_results error: interval_results is NULL");
return;
}
if (!test->json_output) {
/* First stream? */
if (sp == SLIST_FIRST(&test->streams)) {
/* It it's the first interval, print the header;
** else if there's more than one stream, print the separator;
** else nothing.
*/
if (timeval_equals(&sp->result->start_time, &irp->interval_start_time))
if (test->protocol->id == Ptcp && has_tcpinfo_retransmits())
fputs(report_bw_retrans_header, stdout);
else
fputs(report_bw_header, stdout);
else if (test->num_streams > 1)
fputs(report_bw_separator, stdout);
}
}
unit_snprintf(ubuf, UNIT_LEN, (double) (irp->bytes_transferred), 'A');
bandwidth = (double) irp->bytes_transferred / (double) irp->interval_duration;
unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
st = timeval_diff(&sp->result->start_time, &irp->interval_start_time);
et = timeval_diff(&sp->result->start_time, &irp->interval_end_time);
if (test->protocol->id == Ptcp && has_tcpinfo_retransmits()) {
if (test->json_output)
cJSON_AddItemToArray(json_interval_streams, iperf_json_printf("socket: %d start: %f end: %f seconds: %f bytes: %d bits_per_second: %f retransmits: %d", (int64_t) sp->socket, (double) st, (double) et, (double) irp->interval_duration, (int64_t) irp->bytes_transferred, bandwidth * 8, (int64_t) irp->this_retrans));
else
printf(report_bw_retrans_format, sp->socket, st, et, ubuf, nbuf, irp->this_retrans);
} else {
if (test->json_output)
cJSON_AddItemToArray(json_interval_streams, iperf_json_printf("socket: %d start: %f end: %f seconds: %f bytes: %d bits_per_second: %f", (int64_t) sp->socket, (double) st, (double) et, (double) irp->interval_duration, (int64_t) irp->bytes_transferred, bandwidth * 8));
else
printf(report_bw_format, sp->socket, st, et, ubuf, nbuf);
}
}
/**************************************************************************/
void
iperf_free_stream(struct iperf_stream *sp)
{
struct iperf_interval_results *irp, *nirp;
/* XXX: need to free interval list too! */
munmap(sp->buffer, sp->test->settings->blksize);
close(sp->buffer_fd);
for (irp = TAILQ_FIRST(&sp->result->interval_results); irp != TAILQ_END(sp->result->interval_results); irp = nirp) {
nirp = TAILQ_NEXT(irp, irlistentries);
free(irp);
}
free(sp->result);
if (sp->send_timer != NULL)
tmr_cancel(sp->send_timer);
free(sp);
}
/**************************************************************************/
struct iperf_stream *
iperf_new_stream(struct iperf_test *test, int s)
{
int i;
struct iperf_stream *sp;
/* delete /tmp/ for compiling in cygwin for windows */
char template[] = "iperf3.XXXXXX";
h_errno = 0;
sp = (struct iperf_stream *) malloc(sizeof(struct iperf_stream));
if (!sp) {
i_errno = IECREATESTREAM;
return NULL;
}
memset(sp, 0, sizeof(struct iperf_stream));
sp->test = test;
sp->result = (struct iperf_stream_result *) malloc(sizeof(struct iperf_stream_result));
sp->settings = test->settings;
if (!sp->result) {
i_errno = IECREATESTREAM;
return NULL;
}
memset(sp->result, 0, sizeof(struct iperf_stream_result));
TAILQ_INIT(&sp->result->interval_results);
/* Create and randomize the buffer */
sp->buffer_fd = mkstemp(template);
if (sp->buffer_fd == -1) {
i_errno = IECREATESTREAM;
return NULL;
}
/* unlink temp file otherwise it would be remained in /tmp */
if(0 != unlink(template)) {
i_errno = IECREATESTREAM; /* here is not quite right */
return NULL;
}
if (ftruncate(sp->buffer_fd, test->settings->blksize) < 0) {
i_errno = IECREATESTREAM;
return NULL;
}
sp->buffer = (char *) mmap(NULL, test->settings->blksize, PROT_READ|PROT_WRITE, MAP_PRIVATE, sp->buffer_fd, 0);
if (sp->buffer == MAP_FAILED) {
i_errno = IECREATESTREAM;
return NULL;
}
srandom(time(NULL));
for (i = 0; i < test->settings->blksize; ++i)
sp->buffer[i] = random();
/* Set socket */
sp->socket = s;
sp->snd = test->protocol->send;
sp->rcv = test->protocol->recv;
/* Initialize stream */
if (iperf_init_stream(sp, test) < 0)
return NULL;
iperf_add_stream(test, sp);
return sp;
}
/**************************************************************************/
int
iperf_init_stream(struct iperf_stream *sp, struct iperf_test *test)
{
socklen_t len;
int opt;
len = sizeof(struct sockaddr_storage);
if (getsockname(sp->socket, (struct sockaddr *) &sp->local_addr, &len) < 0) {
i_errno = IEINITSTREAM;
return -1;
}
len = sizeof(struct sockaddr_storage);
if (getpeername(sp->socket, (struct sockaddr *) &sp->remote_addr, &len) < 0) {
i_errno = IEINITSTREAM;
return -1;
}
/* Set IP TOS */
if ((opt = test->settings->tos)) {
if (getsockdomain(sp->socket) == AF_INET6) {
#ifdef IPV6_TCLASS
if (setsockopt(sp->socket, IPPROTO_IPV6, IPV6_TCLASS, &opt, sizeof(opt)) < 0) {
i_errno = IESETCOS;
return -1;
}
#else
i_errno = IESETCOS;
return -1;
#endif
} else {
if (setsockopt(sp->socket, IPPROTO_IP, IP_TOS, &opt, sizeof(opt)) < 0) {
i_errno = IESETTOS;
return -1;
}
}
}
return 0;
}
/**************************************************************************/
void
iperf_add_stream(struct iperf_test *test, struct iperf_stream *sp)
{
int i;
struct iperf_stream *n, *prev;
if (SLIST_EMPTY(&test->streams)) {
SLIST_INSERT_HEAD(&test->streams, sp, streams);
sp->id = 1;
} else {
// for (n = test->streams, i = 2; n->next; n = n->next, ++i);
i = 2;
SLIST_FOREACH(n, &test->streams, streams) {
prev = n;
++i;
}
SLIST_INSERT_AFTER(prev, sp, streams);
sp->id = i;
}
}
void
sig_handler(int sig)
{
longjmp(env, 1);
}
int
iperf_json_start(struct iperf_test *test)
{
test->json_top = cJSON_CreateObject();
if (test->json_top == NULL)
return -1;
test->json_start = cJSON_CreateObject();
if (test->json_start == NULL)
return -1;
cJSON_AddItemToObject(test->json_top, "start", test->json_start);
test->json_intervals = cJSON_CreateArray();
if (test->json_intervals == NULL)
return -1;
cJSON_AddItemToObject(test->json_top, "intervals", test->json_intervals);
test->json_end = cJSON_CreateObject();
if (test->json_end == NULL)
return -1;
cJSON_AddItemToObject(test->json_top, "end", test->json_end);
return 0;
}
int
iperf_json_finish(struct iperf_test *test)
{
char *str;
str = cJSON_Print(test->json_top);
if (str == NULL)
return -1;
fputs(str, stdout);
putchar('\n');
fflush(stdout);
free(str);
cJSON_Delete(test->json_top);
test->json_top = test->json_start = test->json_intervals = test->json_end = NULL;
return 0;
}
| zz1126wnx-iperf3 | src/iperf_api.c | C | bsd | 56,858 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
enum {
UNIT_LEN = 11
};
double unit_atof( const char *s );
iperf_size_t unit_atoi( const char *s );
void unit_snprintf( char *s, int inLen, double inNum, char inFormat );
| zz1126wnx-iperf3 | src/units.h | C | bsd | 517 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <assert.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdint.h>
#include <sys/time.h>
#include <sys/select.h>
#include "iperf.h"
#include "iperf_api.h"
#include "iperf_util.h"
#include "iperf_udp.h"
#include "timer.h"
#include "net.h"
/* iperf_udp_recv
*
* receives the data for UDP
*/
int
iperf_udp_recv(struct iperf_stream *sp)
{
int r;
int size = sp->settings->blksize;
int sec, usec, pcount;
double transit = 0, d = 0;
struct timeval sent_time, arrival_time;
r = Nread(sp->socket, sp->buffer, size, Pudp);
if (r < 0)
return r;
sp->result->bytes_received += r;
sp->result->bytes_received_this_interval += r;
memcpy(&sec, sp->buffer, sizeof(sec));
memcpy(&usec, sp->buffer+4, sizeof(usec));
memcpy(&pcount, sp->buffer+8, sizeof(pcount));
sec = ntohl(sec);
usec = ntohl(usec);
pcount = ntohl(pcount);
sent_time.tv_sec = sec;
sent_time.tv_usec = usec;
/* Out of order packets */
if (pcount >= sp->packet_count + 1) {
if (pcount > sp->packet_count + 1) {
sp->cnt_error += (pcount - 1) - sp->packet_count;
}
sp->packet_count = pcount;
} else {
sp->outoforder_packets++;
iperf_err(sp->test, "OUT OF ORDER - incoming packet = %d and received packet = %d AND SP = %d", pcount, sp->packet_count, sp->socket);
}
/* jitter measurement */
gettimeofday(&arrival_time, NULL);
transit = timeval_diff(&sent_time, &arrival_time);
d = transit - sp->prev_transit;
if (d < 0)
d = -d;
sp->prev_transit = transit;
// XXX: This is NOT the way to calculate jitter
// J = |(R1 - S1) - (R0 - S0)| [/ number of packets, for average]
sp->jitter += (d - sp->jitter) / 16.0;
return r;
}
static void
send_timer_proc(TimerClientData client_data, struct timeval* nowP)
{
struct iperf_stream *sp = client_data.p;
/* All we do here is set a flag saying that this UDP stream may be sent
** to. The actual sending gets done in iperf_udp_send(), which then
** resets the flag and makes a new adjusted timer.
*/
sp->send_timer = NULL;
sp->udp_green_light = 1;
}
/* iperf_udp_send
*
* sends the data for UDP
*/
int
iperf_udp_send(struct iperf_stream *sp)
{
int r;
int64_t dtargus;
int64_t adjustus;
uint64_t sec, usec, pcount;
int size = sp->settings->blksize;
struct timeval before, after;
TimerClientData cd;
if (! sp->udp_green_light)
return 0;
gettimeofday(&before, 0);
++sp->packet_count;
sec = htonl(before.tv_sec);
usec = htonl(before.tv_usec);
pcount = htonl(sp->packet_count);
memcpy(sp->buffer, &sec, sizeof(sec));
memcpy(sp->buffer+4, &usec, sizeof(usec));
memcpy(sp->buffer+8, &pcount, sizeof(pcount));
r = Nwrite(sp->socket, sp->buffer, size, Pudp);
if (r < 0)
return r;
sp->result->bytes_sent += r;
sp->result->bytes_sent_this_interval += r;
if (sp->settings->rate != 0) {
gettimeofday(&after, 0);
dtargus = (int64_t) (sp->settings->blksize) * SEC_TO_US * 8;
dtargus /= sp->settings->rate;
assert(dtargus != 0);
adjustus = dtargus;
adjustus += (before.tv_sec - after.tv_sec) * SEC_TO_US;
adjustus += (before.tv_usec - after.tv_usec);
if (adjustus > 0) {
dtargus = adjustus;
}
cd.p = sp;
sp->udp_green_light = 0;
sp->send_timer = tmr_create((struct timeval*) 0, send_timer_proc, cd, dtargus, 0);
if (sp->send_timer == NULL)
return -1;
}
return r;
}
/**************************************************************************/
/* iperf_udp_accept
*
* accepts a new UDP connection
*/
int
iperf_udp_accept(struct iperf_test *test)
{
struct sockaddr_storage sa_peer;
int buf;
socklen_t len;
int sz, s;
s = test->prot_listener;
len = sizeof(sa_peer);
if ((sz = recvfrom(test->prot_listener, &buf, sizeof(buf), 0, (struct sockaddr *) &sa_peer, &len)) < 0) {
i_errno = IESTREAMACCEPT;
return -1;
}
if (connect(s, (struct sockaddr *) &sa_peer, len) < 0) {
i_errno = IESTREAMACCEPT;
return -1;
}
test->prot_listener = netannounce(test->settings->domain, Pudp, test->bind_address, test->server_port);
if (test->prot_listener < 0) {
i_errno = IESTREAMLISTEN;
return -1;
}
FD_SET(test->prot_listener, &test->read_set);
test->max_fd = (test->max_fd < test->prot_listener) ? test->prot_listener : test->max_fd;
/* Let the client know we're ready "accept" another UDP "stream" */
buf = 987654321;
if (write(s, &buf, sizeof(buf)) < 0) {
i_errno = IESTREAMWRITE;
return -1;
}
return s;
}
/* iperf_udp_listen
*
* start up a listener for UDP stream connections
*/
int
iperf_udp_listen(struct iperf_test *test)
{
int s;
if ((s = netannounce(test->settings->domain, Pudp, test->bind_address, test->server_port)) < 0) {
i_errno = IESTREAMLISTEN;
return -1;
}
return s;
}
/* iperf_udp_connect
*
* connect to a TCP stream listener
*/
int
iperf_udp_connect(struct iperf_test *test)
{
int s, buf, sz;
if ((s = netdial(test->settings->domain, Pudp, test->bind_address, test->server_hostname, test->server_port)) < 0) {
i_errno = IESTREAMCONNECT;
return -1;
}
/* Write to the UDP stream to let the server know we're here. */
buf = 123456789;
if (write(s, &buf, sizeof(buf)) < 0) {
// XXX: Should this be changed to IESTREAMCONNECT?
i_errno = IESTREAMWRITE;
return -1;
}
/* Wait until the server confirms the client UDP write */
// XXX: Should this read be TCP instead?
if ((sz = recv(s, &buf, sizeof(buf), 0)) < 0) {
i_errno = IESTREAMREAD;
return -1;
}
return s;
}
/* iperf_udp_init
*
* initializer for UDP streams in TEST_START
*/
int
iperf_udp_init(struct iperf_test *test)
{
int64_t dtargus;
struct iperf_stream *sp;
TimerClientData cd;
if (test->settings->rate == 0) {
SLIST_FOREACH(sp, &test->streams, streams) {
sp->udp_green_light = 1;
}
} else {
/* Calculate the send delay needed to hit target bandwidth (-b) */
dtargus = (int64_t) test->settings->blksize * SEC_TO_US * 8;
dtargus /= test->settings->rate;
assert(dtargus != 0);
SLIST_FOREACH(sp, &test->streams, streams) {
cd.p = sp;
sp->udp_green_light = 0;
sp->send_timer = tmr_create((struct timeval*) 0, send_timer_proc, cd, dtargus, 0);
if (sp->send_timer == NULL)
return -1;
}
}
return 0;
}
| zz1126wnx-iperf3 | src/iperf_udp.c | C | bsd | 7,091 |
/*
* Copyright (c) 2009-2011, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt of any
* required approvals from the U.S. Dept. of Energy). All rights reserved.
*
* This code is distributed under a BSD style license, see the LICENSE file
* for complete information.
*/
int set_tcp_windowsize(int sock, int bufsize, int dir);
int get_tcp_windowsize(int sock, int dir);
| zz1126wnx-iperf3 | src/tcp_window_size.h | C | bsd | 440 |
/*---------------------------------------------------------------
* Copyright (c) 1999,2000,2001,2002,2003
* The Board of Trustees of the University of Illinois
* All Rights Reserved.
*---------------------------------------------------------------
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software (Iperf) and associated
* documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
*
* Redistributions of source code must retain the above
* copyright notice, this list of conditions and
* the following disclaimers.
*
*
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimers in the documentation and/or other materials
* provided with the distribution.
*
*
* Neither the names of the University of Illinois, NCSA,
* nor the names of its contributors may be used to endorse
* or promote products derived from this Software without
* specific prior written permission.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE CONTIBUTORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
* ________________________________________________________________
* National Laboratory for Applied Network Research
* National Center for Supercomputing Applications
* University of Illinois at Urbana-Champaign
* http://www.ncsa.uiuc.edu
* ________________________________________________________________
*
* stdio.c
* by Mark Gates <mgates@nlanr.net>
* and Ajay Tirumalla <tirumala@ncsa.uiuc.edu>
* -------------------------------------------------------------------
* input and output numbers, converting with kilo, mega, giga
* ------------------------------------------------------------------- */
#include <stdio.h>
#include <assert.h>
#include <ctype.h>
#include <stdint.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/tcp.h>
#include "iperf.h"
#ifdef __cplusplus
extern "C"
{
#endif
const long KILO_UNIT = 1024;
const long MEGA_UNIT = 1024 * 1024;
const long GIGA_UNIT = 1024 * 1024 * 1024;
/* -------------------------------------------------------------------
* unit_atof
*
* Given a string of form #x where # is a number and x is a format
* character listed below, this returns the interpreted integer.
* Gg, Mm, Kk are giga, mega, kilo respectively
* ------------------------------------------------------------------- */
double unit_atof(const char *s)
{
double n;
char suffix = '\0';
assert(s != NULL);
/* scan the number and any suffices */
sscanf(s, "%lf%c", &n, &suffix);
/* convert according to [Gg Mm Kk] */
switch (suffix)
{
case 'g': case 'G':
n *= GIGA_UNIT;
break;
case 'm': case 'M':
n *= MEGA_UNIT;
break;
case 'k': case 'K':
n *= KILO_UNIT;
break;
default:
break;
}
return n;
} /* end unit_atof */
/* -------------------------------------------------------------------
* unit_atoi
*
* Given a string of form #x where # is a number and x is a format
* character listed below, this returns the interpreted integer.
* Gg, Mm, Kk are giga, mega, kilo respectively
* ------------------------------------------------------------------- */
iperf_size_t unit_atoi(const char *s)
{
double n;
char suffix = '\0';
assert(s != NULL);
/* scan the number and any suffices */
sscanf(s, "%lf%c", &n, &suffix);
/* convert according to [Gg Mm Kk] */
switch (suffix)
{
case 'g': case 'G':
n *= GIGA_UNIT;
break;
case 'm': case 'M':
n *= MEGA_UNIT;
break;
case 'k': case 'K':
n *= KILO_UNIT;
break;
default:
break;
}
return (iperf_size_t) n;
} /* end unit_atof */
/* -------------------------------------------------------------------
* constants for byte_printf
* ------------------------------------------------------------------- */
/* used as indices into conversion_bytes[], label_byte[], and label_bit[] */
enum
{
UNIT_CONV,
KILO_CONV,
MEGA_CONV,
GIGA_CONV
};
/* factor to multiply the number by */
const double conversion_bytes[] =
{
1.0, /* unit */
1.0 / 1024, /* kilo */
1.0 / 1024 / 1024, /* mega */
1.0 / 1024 / 1024 / 1024/* giga */
};
/* factor to multiply the number by for bits*/
const double conversion_bits[] =
{
1.0, /* unit */
1.0 / 1000, /* kilo */
1.0 / 1000 / 1000, /* mega */
1.0 / 1000 / 1000 / 1000/* giga */
};
/* labels for Byte formats [KMG] */
const char *label_byte[] =
{
"Byte",
"KByte",
"MByte",
"GByte"
};
/* labels for bit formats [kmg] */
const char *label_bit[] =
{
"bit",
"Kbit",
"Mbit",
"Gbit"
};
/* -------------------------------------------------------------------
* unit_snprintf
*
* Given a number in bytes and a format, converts the number and
* prints it out with a bits or bytes label.
* B, K, M, G, A for Byte, Kbyte, Mbyte, Gbyte, adaptive byte
* b, k, m, g, a for bit, Kbit, Mbit, Gbit, adaptive bit
* adaptive picks the "best" one based on the number.
* s should be at least 11 chars long
* (4 digits + space + 5 chars max + null)
* ------------------------------------------------------------------- */
void unit_snprintf(char *s, int inLen,
double inNum, char inFormat)
{
int conv;
const char *suffix;
const char *format;
/* convert to bits for [bkmga] */
if (!isupper((int) inFormat))
{
inNum *= 8;
}
switch (toupper(inFormat))
{
case 'B':
conv = UNIT_CONV;
break;
case 'K':
conv = KILO_CONV;
break;
case 'M':
conv = MEGA_CONV;
break;
case 'G':
conv = GIGA_CONV;
break;
default:
case 'A':
{
double tmpNum = inNum;
conv = UNIT_CONV;
if (isupper((int) inFormat))
{
while (tmpNum >= 1024.0 && conv <= GIGA_CONV)
{
tmpNum /= 1024.0;
conv++;
}
} else
{
while (tmpNum >= 1000.0 && conv <= GIGA_CONV)
{
tmpNum /= 1000.0;
conv++;
}
}
break;
}
}
if (!isupper((int) inFormat))
{
inNum *= conversion_bits[conv];
suffix = label_bit[conv];
} else
{
inNum *= conversion_bytes[conv];
suffix = label_byte[conv];
}
/* print such that we always fit in 4 places */
if (inNum < 9.995)
{ /* 9.995 would be rounded to 10.0 */
format = "%4.2f %s";/* #.## */
} else if (inNum < 99.95)
{ /* 99.95 would be rounded to 100 */
format = "%4.1f %s";/* ##.# */
} else if (inNum < 999.5)
{ /* 999.5 would be rounded to 1000 */
format = "%4.0f %s";/* ### */
} else
{ /* 1000-1024 fits in 4 places If not using
* Adaptive sizes then this code will not
* control spaces */
format = "%4.0f %s";/* #### */
}
snprintf(s, inLen, format, inNum, suffix);
} /* end unit_snprintf */
#ifdef __cplusplus
} /* end extern "C" */
#endif
| zz1126wnx-iperf3 | src/units.c | C | bsd | 7,619 |
#! /bin/sh
# Wrapper for compilers which do not understand `-c -o'.
scriptversion=2005-05-14.22
# Copyright (C) 1999, 2000, 2003, 2004, 2005 Free Software Foundation, Inc.
# Written by Tom Tromey <tromey@cygnus.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# This file is maintained in Automake, please report
# bugs to <bug-automake@gnu.org> or send patches to
# <automake-patches@gnu.org>.
case $1 in
'')
echo "$0: No command. Try \`$0 --help' for more information." 1>&2
exit 1;
;;
-h | --h*)
cat <<\EOF
Usage: compile [--help] [--version] PROGRAM [ARGS]
Wrapper for compilers which do not understand `-c -o'.
Remove `-o dest.o' from ARGS, run PROGRAM with the remaining
arguments, and rename the output as expected.
If you are trying to build a whole package this is not the
right script to run: please start by reading the file `INSTALL'.
Report bugs to <bug-automake@gnu.org>.
EOF
exit $?
;;
-v | --v*)
echo "compile $scriptversion"
exit $?
;;
esac
ofile=
cfile=
eat=
for arg
do
if test -n "$eat"; then
eat=
else
case $1 in
-o)
# configure might choose to run compile as `compile cc -o foo foo.c'.
# So we strip `-o arg' only if arg is an object.
eat=1
case $2 in
*.o | *.obj)
ofile=$2
;;
*)
set x "$@" -o "$2"
shift
;;
esac
;;
*.c)
cfile=$1
set x "$@" "$1"
shift
;;
*)
set x "$@" "$1"
shift
;;
esac
fi
shift
done
if test -z "$ofile" || test -z "$cfile"; then
# If no `-o' option was seen then we might have been invoked from a
# pattern rule where we don't need one. That is ok -- this is a
# normal compilation that the losing compiler can handle. If no
# `.c' file was seen then we are probably linking. That is also
# ok.
exec "$@"
fi
# Name of file we expect compiler to create.
cofile=`echo "$cfile" | sed -e 's|^.*/||' -e 's/\.c$/.o/'`
# Create the lock directory.
# Note: use `[/.-]' here to ensure that we don't use the same name
# that we are using for the .o file. Also, base the name on the expected
# object file name, since that is what matters with a parallel build.
lockdir=`echo "$cofile" | sed -e 's|[/.-]|_|g'`.d
while true; do
if mkdir "$lockdir" >/dev/null 2>&1; then
break
fi
sleep 1
done
# FIXME: race condition here if user kills between mkdir and trap.
trap "rmdir '$lockdir'; exit 1" 1 2 15
# Run the compile.
"$@"
ret=$?
if test -f "$cofile"; then
mv "$cofile" "$ofile"
elif test -f "${cofile}bj"; then
mv "${cofile}bj" "$ofile"
fi
rmdir "$lockdir"
exit $ret
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-end: "$"
# End:
| zz1126wnx-iperf3 | config/compile | Shell | bsd | 3,707 |
#! /bin/sh
# mkinstalldirs --- make directory hierarchy
scriptversion=2005-06-29.22
# Original author: Noah Friedman <friedman@prep.ai.mit.edu>
# Created: 1993-05-16
# Public domain.
#
# This file is maintained in Automake, please report
# bugs to <bug-automake@gnu.org> or send patches to
# <automake-patches@gnu.org>.
errstatus=0
dirmode=
usage="\
Usage: mkinstalldirs [-h] [--help] [--version] [-m MODE] DIR ...
Create each directory DIR (with mode MODE, if specified), including all
leading file name components.
Report bugs to <bug-automake@gnu.org>."
# process command line arguments
while test $# -gt 0 ; do
case $1 in
-h | --help | --h*) # -h for help
echo "$usage"
exit $?
;;
-m) # -m PERM arg
shift
test $# -eq 0 && { echo "$usage" 1>&2; exit 1; }
dirmode=$1
shift
;;
--version)
echo "$0 $scriptversion"
exit $?
;;
--) # stop option processing
shift
break
;;
-*) # unknown option
echo "$usage" 1>&2
exit 1
;;
*) # first non-opt arg
break
;;
esac
done
for file
do
if test -d "$file"; then
shift
else
break
fi
done
case $# in
0) exit 0 ;;
esac
# Solaris 8's mkdir -p isn't thread-safe. If you mkdir -p a/b and
# mkdir -p a/c at the same time, both will detect that a is missing,
# one will create a, then the other will try to create a and die with
# a "File exists" error. This is a problem when calling mkinstalldirs
# from a parallel make. We use --version in the probe to restrict
# ourselves to GNU mkdir, which is thread-safe.
case $dirmode in
'')
if mkdir -p --version . >/dev/null 2>&1 && test ! -d ./--version; then
echo "mkdir -p -- $*"
exec mkdir -p -- "$@"
else
# On NextStep and OpenStep, the `mkdir' command does not
# recognize any option. It will interpret all options as
# directories to create, and then abort because `.' already
# exists.
test -d ./-p && rmdir ./-p
test -d ./--version && rmdir ./--version
fi
;;
*)
if mkdir -m "$dirmode" -p --version . >/dev/null 2>&1 &&
test ! -d ./--version; then
echo "mkdir -m $dirmode -p -- $*"
exec mkdir -m "$dirmode" -p -- "$@"
else
# Clean up after NextStep and OpenStep mkdir.
for d in ./-m ./-p ./--version "./$dirmode";
do
test -d $d && rmdir $d
done
fi
;;
esac
for file
do
case $file in
/*) pathcomp=/ ;;
*) pathcomp= ;;
esac
oIFS=$IFS
IFS=/
set fnord $file
shift
IFS=$oIFS
for d
do
test "x$d" = x && continue
pathcomp=$pathcomp$d
case $pathcomp in
-*) pathcomp=./$pathcomp ;;
esac
if test ! -d "$pathcomp"; then
echo "mkdir $pathcomp"
mkdir "$pathcomp" || lasterr=$?
if test ! -d "$pathcomp"; then
errstatus=$lasterr
else
if test ! -z "$dirmode"; then
echo "chmod $dirmode $pathcomp"
lasterr=
chmod "$dirmode" "$pathcomp" || lasterr=$?
if test ! -z "$lasterr"; then
errstatus=$lasterr
fi
fi
fi
fi
pathcomp=$pathcomp/
done
done
exit $errstatus
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-end: "$"
# End:
| zz1126wnx-iperf3 | config/mkinstalldirs | Shell | bsd | 3,474 |
# ltmain.sh - Provide generalized library-building support services.
# NOTE: Changing this file will not affect anything until you rerun configure.
#
# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005
# Free Software Foundation, Inc.
# Originally by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
basename="s,^.*/,,g"
# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
# is ksh but when the shell is invoked as "sh" and the current value of
# the _XPG environment variable is not equal to 1 (one), the special
# positional parameter $0, within a function call, is the name of the
# function.
progpath="$0"
# The name of this program:
progname=`echo "$progpath" | $SED $basename`
modename="$progname"
# Global variables:
EXIT_SUCCESS=0
EXIT_FAILURE=1
PROGRAM=ltmain.sh
PACKAGE=libtool
VERSION=1.5.22
TIMESTAMP=" (1.1220.2.365 2005/12/18 22:14:06)"
# Be Bourne compatible (taken from Autoconf:_AS_BOURNE_COMPATIBLE).
if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
emulate sh
NULLCMD=:
# Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
# is contrary to our usage. Disable this feature.
alias -g '${1+"$@"}'='"$@"'
setopt NO_GLOB_SUBST
else
case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
fi
# Check that we have a working $echo.
if test "X$1" = X--no-reexec; then
# Discard the --no-reexec flag, and continue.
shift
elif test "X$1" = X--fallback-echo; then
# Avoid inline document here, it may be left over
:
elif test "X`($echo '\t') 2>/dev/null`" = 'X\t'; then
# Yippee, $echo works!
:
else
# Restart under the correct shell, and then maybe $echo will work.
exec $SHELL "$progpath" --no-reexec ${1+"$@"}
fi
if test "X$1" = X--fallback-echo; then
# used as fallback echo
shift
cat <<EOF
$*
EOF
exit $EXIT_SUCCESS
fi
default_mode=
help="Try \`$progname --help' for more information."
magic="%%%MAGIC variable%%%"
mkdir="mkdir"
mv="mv -f"
rm="rm -f"
# Sed substitution that helps us do robust quoting. It backslashifies
# metacharacters that are still active within double-quoted strings.
Xsed="${SED}"' -e 1s/^X//'
sed_quote_subst='s/\([\\`\\"$\\\\]\)/\\\1/g'
# test EBCDIC or ASCII
case `echo X|tr X '\101'` in
A) # ASCII based system
# \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
SP2NL='tr \040 \012'
NL2SP='tr \015\012 \040\040'
;;
*) # EBCDIC based system
SP2NL='tr \100 \n'
NL2SP='tr \r\n \100\100'
;;
esac
# NLS nuisances.
# Only set LANG and LC_ALL to C if already set.
# These must not be set unconditionally because not all systems understand
# e.g. LANG=C (notably SCO).
# We save the old values to restore during execute mode.
for lt_var in LANG LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
do
eval "if test \"\${$lt_var+set}\" = set; then
save_$lt_var=\$$lt_var
$lt_var=C
export $lt_var
fi"
done
# Make sure IFS has a sensible default
lt_nl='
'
IFS=" $lt_nl"
if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
$echo "$modename: not configured to build any kind of library" 1>&2
$echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2
exit $EXIT_FAILURE
fi
# Global variables.
mode=$default_mode
nonopt=
prev=
prevopt=
run=
show="$echo"
show_help=
execute_dlfiles=
duplicate_deps=no
preserve_args=
lo2o="s/\\.lo\$/.${objext}/"
o2lo="s/\\.${objext}\$/.lo/"
extracted_archives=
extracted_serial=0
#####################################
# Shell function definitions:
# This seems to be the best place for them
# func_mktempdir [string]
# Make a temporary directory that won't clash with other running
# libtool processes, and avoids race conditions if possible. If
# given, STRING is the basename for that directory.
func_mktempdir ()
{
my_template="${TMPDIR-/tmp}/${1-$progname}"
if test "$run" = ":"; then
# Return a directory name, but don't create it in dry-run mode
my_tmpdir="${my_template}-$$"
else
# If mktemp works, use that first and foremost
my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null`
if test ! -d "$my_tmpdir"; then
# Failing that, at least try and use $RANDOM to avoid a race
my_tmpdir="${my_template}-${RANDOM-0}$$"
save_mktempdir_umask=`umask`
umask 0077
$mkdir "$my_tmpdir"
umask $save_mktempdir_umask
fi
# If we're not in dry-run mode, bomb out on failure
test -d "$my_tmpdir" || {
$echo "cannot create temporary directory \`$my_tmpdir'" 1>&2
exit $EXIT_FAILURE
}
fi
$echo "X$my_tmpdir" | $Xsed
}
# func_win32_libid arg
# return the library type of file 'arg'
#
# Need a lot of goo to handle *both* DLLs and import libs
# Has to be a shell function in order to 'eat' the argument
# that is supplied when $file_magic_command is called.
func_win32_libid ()
{
win32_libid_type="unknown"
win32_fileres=`file -L $1 2>/dev/null`
case $win32_fileres in
*ar\ archive\ import\ library*) # definitely import
win32_libid_type="x86 archive import"
;;
*ar\ archive*) # could be an import, or static
if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | \
$EGREP -e 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then
win32_nmres=`eval $NM -f posix -A $1 | \
$SED -n -e '1,100{/ I /{s,.*,import,;p;q;};}'`
case $win32_nmres in
import*) win32_libid_type="x86 archive import";;
*) win32_libid_type="x86 archive static";;
esac
fi
;;
*DLL*)
win32_libid_type="x86 DLL"
;;
*executable*) # but shell scripts are "executable" too...
case $win32_fileres in
*MS\ Windows\ PE\ Intel*)
win32_libid_type="x86 DLL"
;;
esac
;;
esac
$echo $win32_libid_type
}
# func_infer_tag arg
# Infer tagged configuration to use if any are available and
# if one wasn't chosen via the "--tag" command line option.
# Only attempt this if the compiler in the base compile
# command doesn't match the default compiler.
# arg is usually of the form 'gcc ...'
func_infer_tag ()
{
if test -n "$available_tags" && test -z "$tagname"; then
CC_quoted=
for arg in $CC; do
case $arg in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
arg="\"$arg\""
;;
esac
CC_quoted="$CC_quoted $arg"
done
case $@ in
# Blanks in the command may have been stripped by the calling shell,
# but not from the CC environment variable when configure was run.
" $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) ;;
# Blanks at the start of $base_compile will cause this to fail
# if we don't check for them as well.
*)
for z in $available_tags; do
if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then
# Evaluate the configuration.
eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`"
CC_quoted=
for arg in $CC; do
# Double-quote args containing other shell metacharacters.
case $arg in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
arg="\"$arg\""
;;
esac
CC_quoted="$CC_quoted $arg"
done
case "$@ " in
" $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*)
# The compiler in the base compile command matches
# the one in the tagged configuration.
# Assume this is the tagged configuration we want.
tagname=$z
break
;;
esac
fi
done
# If $tagname still isn't set, then no tagged configuration
# was found and let the user know that the "--tag" command
# line option must be used.
if test -z "$tagname"; then
$echo "$modename: unable to infer tagged configuration"
$echo "$modename: specify a tag with \`--tag'" 1>&2
exit $EXIT_FAILURE
# else
# $echo "$modename: using $tagname tagged configuration"
fi
;;
esac
fi
}
# func_extract_an_archive dir oldlib
func_extract_an_archive ()
{
f_ex_an_ar_dir="$1"; shift
f_ex_an_ar_oldlib="$1"
$show "(cd $f_ex_an_ar_dir && $AR x $f_ex_an_ar_oldlib)"
$run eval "(cd \$f_ex_an_ar_dir && $AR x \$f_ex_an_ar_oldlib)" || exit $?
if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
:
else
$echo "$modename: ERROR: object name conflicts: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" 1>&2
exit $EXIT_FAILURE
fi
}
# func_extract_archives gentop oldlib ...
func_extract_archives ()
{
my_gentop="$1"; shift
my_oldlibs=${1+"$@"}
my_oldobjs=""
my_xlib=""
my_xabs=""
my_xdir=""
my_status=""
$show "${rm}r $my_gentop"
$run ${rm}r "$my_gentop"
$show "$mkdir $my_gentop"
$run $mkdir "$my_gentop"
my_status=$?
if test "$my_status" -ne 0 && test ! -d "$my_gentop"; then
exit $my_status
fi
for my_xlib in $my_oldlibs; do
# Extract the objects.
case $my_xlib in
[\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;;
*) my_xabs=`pwd`"/$my_xlib" ;;
esac
my_xlib=`$echo "X$my_xlib" | $Xsed -e 's%^.*/%%'`
my_xlib_u=$my_xlib
while :; do
case " $extracted_archives " in
*" $my_xlib_u "*)
extracted_serial=`expr $extracted_serial + 1`
my_xlib_u=lt$extracted_serial-$my_xlib ;;
*) break ;;
esac
done
extracted_archives="$extracted_archives $my_xlib_u"
my_xdir="$my_gentop/$my_xlib_u"
$show "${rm}r $my_xdir"
$run ${rm}r "$my_xdir"
$show "$mkdir $my_xdir"
$run $mkdir "$my_xdir"
exit_status=$?
if test "$exit_status" -ne 0 && test ! -d "$my_xdir"; then
exit $exit_status
fi
case $host in
*-darwin*)
$show "Extracting $my_xabs"
# Do not bother doing anything if just a dry run
if test -z "$run"; then
darwin_orig_dir=`pwd`
cd $my_xdir || exit $?
darwin_archive=$my_xabs
darwin_curdir=`pwd`
darwin_base_archive=`$echo "X$darwin_archive" | $Xsed -e 's%^.*/%%'`
darwin_arches=`lipo -info "$darwin_archive" 2>/dev/null | $EGREP Architectures 2>/dev/null`
if test -n "$darwin_arches"; then
darwin_arches=`echo "$darwin_arches" | $SED -e 's/.*are://'`
darwin_arch=
$show "$darwin_base_archive has multiple architectures $darwin_arches"
for darwin_arch in $darwin_arches ; do
mkdir -p "unfat-$$/${darwin_base_archive}-${darwin_arch}"
lipo -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}"
cd "unfat-$$/${darwin_base_archive}-${darwin_arch}"
func_extract_an_archive "`pwd`" "${darwin_base_archive}"
cd "$darwin_curdir"
$rm "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}"
done # $darwin_arches
## Okay now we have a bunch of thin objects, gotta fatten them up :)
darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print| xargs basename | sort -u | $NL2SP`
darwin_file=
darwin_files=
for darwin_file in $darwin_filelist; do
darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP`
lipo -create -output "$darwin_file" $darwin_files
done # $darwin_filelist
${rm}r unfat-$$
cd "$darwin_orig_dir"
else
cd "$darwin_orig_dir"
func_extract_an_archive "$my_xdir" "$my_xabs"
fi # $darwin_arches
fi # $run
;;
*)
func_extract_an_archive "$my_xdir" "$my_xabs"
;;
esac
my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP`
done
func_extract_archives_result="$my_oldobjs"
}
# End of Shell function definitions
#####################################
# Darwin sucks
eval std_shrext=\"$shrext_cmds\"
disable_libs=no
# Parse our command line options once, thoroughly.
while test "$#" -gt 0
do
arg="$1"
shift
case $arg in
-*=*) optarg=`$echo "X$arg" | $Xsed -e 's/[-_a-zA-Z0-9]*=//'` ;;
*) optarg= ;;
esac
# If the previous option needs an argument, assign it.
if test -n "$prev"; then
case $prev in
execute_dlfiles)
execute_dlfiles="$execute_dlfiles $arg"
;;
tag)
tagname="$arg"
preserve_args="${preserve_args}=$arg"
# Check whether tagname contains only valid characters
case $tagname in
*[!-_A-Za-z0-9,/]*)
$echo "$progname: invalid tag name: $tagname" 1>&2
exit $EXIT_FAILURE
;;
esac
case $tagname in
CC)
# Don't test for the "default" C tag, as we know, it's there, but
# not specially marked.
;;
*)
if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "$progpath" > /dev/null; then
taglist="$taglist $tagname"
# Evaluate the configuration.
eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$tagname'$/,/^# ### END LIBTOOL TAG CONFIG: '$tagname'$/p' < $progpath`"
else
$echo "$progname: ignoring unknown tag $tagname" 1>&2
fi
;;
esac
;;
*)
eval "$prev=\$arg"
;;
esac
prev=
prevopt=
continue
fi
# Have we seen a non-optional argument yet?
case $arg in
--help)
show_help=yes
;;
--version)
$echo "$PROGRAM (GNU $PACKAGE) $VERSION$TIMESTAMP"
$echo
$echo "Copyright (C) 2005 Free Software Foundation, Inc."
$echo "This is free software; see the source for copying conditions. There is NO"
$echo "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
exit $?
;;
--config)
${SED} -e '1,/^# ### BEGIN LIBTOOL CONFIG/d' -e '/^# ### END LIBTOOL CONFIG/,$d' $progpath
# Now print the configurations for the tags.
for tagname in $taglist; do
${SED} -n -e "/^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$/,/^# ### END LIBTOOL TAG CONFIG: $tagname$/p" < "$progpath"
done
exit $?
;;
--debug)
$echo "$progname: enabling shell trace mode"
set -x
preserve_args="$preserve_args $arg"
;;
--dry-run | -n)
run=:
;;
--features)
$echo "host: $host"
if test "$build_libtool_libs" = yes; then
$echo "enable shared libraries"
else
$echo "disable shared libraries"
fi
if test "$build_old_libs" = yes; then
$echo "enable static libraries"
else
$echo "disable static libraries"
fi
exit $?
;;
--finish) mode="finish" ;;
--mode) prevopt="--mode" prev=mode ;;
--mode=*) mode="$optarg" ;;
--preserve-dup-deps) duplicate_deps="yes" ;;
--quiet | --silent)
show=:
preserve_args="$preserve_args $arg"
;;
--tag)
prevopt="--tag"
prev=tag
preserve_args="$preserve_args --tag"
;;
--tag=*)
set tag "$optarg" ${1+"$@"}
shift
prev=tag
preserve_args="$preserve_args --tag"
;;
-dlopen)
prevopt="-dlopen"
prev=execute_dlfiles
;;
-*)
$echo "$modename: unrecognized option \`$arg'" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
;;
*)
nonopt="$arg"
break
;;
esac
done
if test -n "$prevopt"; then
$echo "$modename: option \`$prevopt' requires an argument" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
case $disable_libs in
no)
;;
shared)
build_libtool_libs=no
build_old_libs=yes
;;
static)
build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`
;;
esac
# If this variable is set in any of the actions, the command in it
# will be execed at the end. This prevents here-documents from being
# left over by shells.
exec_cmd=
if test -z "$show_help"; then
# Infer the operation mode.
if test -z "$mode"; then
$echo "*** Warning: inferring the mode of operation is deprecated." 1>&2
$echo "*** Future versions of Libtool will require --mode=MODE be specified." 1>&2
case $nonopt in
*cc | cc* | *++ | gcc* | *-gcc* | g++* | xlc*)
mode=link
for arg
do
case $arg in
-c)
mode=compile
break
;;
esac
done
;;
*db | *dbx | *strace | *truss)
mode=execute
;;
*install*|cp|mv)
mode=install
;;
*rm)
mode=uninstall
;;
*)
# If we have no mode, but dlfiles were specified, then do execute mode.
test -n "$execute_dlfiles" && mode=execute
# Just use the default operation mode.
if test -z "$mode"; then
if test -n "$nonopt"; then
$echo "$modename: warning: cannot infer operation mode from \`$nonopt'" 1>&2
else
$echo "$modename: warning: cannot infer operation mode without MODE-ARGS" 1>&2
fi
fi
;;
esac
fi
# Only execute mode is allowed to have -dlopen flags.
if test -n "$execute_dlfiles" && test "$mode" != execute; then
$echo "$modename: unrecognized option \`-dlopen'" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
# Change the help message to a mode-specific one.
generic_help="$help"
help="Try \`$modename --help --mode=$mode' for more information."
# These modes are in order of execution frequency so that they run quickly.
case $mode in
# libtool compile mode
compile)
modename="$modename: compile"
# Get the compilation command and the source file.
base_compile=
srcfile="$nonopt" # always keep a non-empty value in "srcfile"
suppress_opt=yes
suppress_output=
arg_mode=normal
libobj=
later=
for arg
do
case $arg_mode in
arg )
# do not "continue". Instead, add this to base_compile
lastarg="$arg"
arg_mode=normal
;;
target )
libobj="$arg"
arg_mode=normal
continue
;;
normal )
# Accept any command-line options.
case $arg in
-o)
if test -n "$libobj" ; then
$echo "$modename: you cannot specify \`-o' more than once" 1>&2
exit $EXIT_FAILURE
fi
arg_mode=target
continue
;;
-static | -prefer-pic | -prefer-non-pic)
later="$later $arg"
continue
;;
-no-suppress)
suppress_opt=no
continue
;;
-Xcompiler)
arg_mode=arg # the next one goes into the "base_compile" arg list
continue # The current "srcfile" will either be retained or
;; # replaced later. I would guess that would be a bug.
-Wc,*)
args=`$echo "X$arg" | $Xsed -e "s/^-Wc,//"`
lastarg=
save_ifs="$IFS"; IFS=','
for arg in $args; do
IFS="$save_ifs"
# Double-quote args containing other shell metacharacters.
# Many Bourne shells cannot handle close brackets correctly
# in scan sets, so we specify it separately.
case $arg in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
arg="\"$arg\""
;;
esac
lastarg="$lastarg $arg"
done
IFS="$save_ifs"
lastarg=`$echo "X$lastarg" | $Xsed -e "s/^ //"`
# Add the arguments to base_compile.
base_compile="$base_compile $lastarg"
continue
;;
* )
# Accept the current argument as the source file.
# The previous "srcfile" becomes the current argument.
#
lastarg="$srcfile"
srcfile="$arg"
;;
esac # case $arg
;;
esac # case $arg_mode
# Aesthetically quote the previous argument.
lastarg=`$echo "X$lastarg" | $Xsed -e "$sed_quote_subst"`
case $lastarg in
# Double-quote args containing other shell metacharacters.
# Many Bourne shells cannot handle close brackets correctly
# in scan sets, and some SunOS ksh mistreat backslash-escaping
# in scan sets (worked around with variable expansion),
# and furthermore cannot handle '|' '&' '(' ')' in scan sets
# at all, so we specify them separately.
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
lastarg="\"$lastarg\""
;;
esac
base_compile="$base_compile $lastarg"
done # for arg
case $arg_mode in
arg)
$echo "$modename: you must specify an argument for -Xcompile"
exit $EXIT_FAILURE
;;
target)
$echo "$modename: you must specify a target with \`-o'" 1>&2
exit $EXIT_FAILURE
;;
*)
# Get the name of the library object.
[ -z "$libobj" ] && libobj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%'`
;;
esac
# Recognize several different file suffixes.
# If the user specifies -o file.o, it is replaced with file.lo
xform='[cCFSifmso]'
case $libobj in
*.ada) xform=ada ;;
*.adb) xform=adb ;;
*.ads) xform=ads ;;
*.asm) xform=asm ;;
*.c++) xform=c++ ;;
*.cc) xform=cc ;;
*.ii) xform=ii ;;
*.class) xform=class ;;
*.cpp) xform=cpp ;;
*.cxx) xform=cxx ;;
*.f90) xform=f90 ;;
*.for) xform=for ;;
*.java) xform=java ;;
*.obj) xform=obj ;;
esac
libobj=`$echo "X$libobj" | $Xsed -e "s/\.$xform$/.lo/"`
case $libobj in
*.lo) obj=`$echo "X$libobj" | $Xsed -e "$lo2o"` ;;
*)
$echo "$modename: cannot determine name of library object from \`$libobj'" 1>&2
exit $EXIT_FAILURE
;;
esac
func_infer_tag $base_compile
for arg in $later; do
case $arg in
-static)
build_old_libs=yes
continue
;;
-prefer-pic)
pic_mode=yes
continue
;;
-prefer-non-pic)
pic_mode=no
continue
;;
esac
done
qlibobj=`$echo "X$libobj" | $Xsed -e "$sed_quote_subst"`
case $qlibobj in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
qlibobj="\"$qlibobj\"" ;;
esac
test "X$libobj" != "X$qlibobj" \
&& $echo "X$libobj" | grep '[]~#^*{};<>?"'"'"' &()|`$[]' \
&& $echo "$modename: libobj name \`$libobj' may not contain shell special characters."
objname=`$echo "X$obj" | $Xsed -e 's%^.*/%%'`
xdir=`$echo "X$obj" | $Xsed -e 's%/[^/]*$%%'`
if test "X$xdir" = "X$obj"; then
xdir=
else
xdir=$xdir/
fi
lobj=${xdir}$objdir/$objname
if test -z "$base_compile"; then
$echo "$modename: you must specify a compilation command" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
# Delete any leftover library objects.
if test "$build_old_libs" = yes; then
removelist="$obj $lobj $libobj ${libobj}T"
else
removelist="$lobj $libobj ${libobj}T"
fi
$run $rm $removelist
trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15
# On Cygwin there's no "real" PIC flag so we must build both object types
case $host_os in
cygwin* | mingw* | pw32* | os2*)
pic_mode=default
;;
esac
if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then
# non-PIC code in shared libraries is not supported
pic_mode=default
fi
# Calculate the filename of the output object if compiler does
# not support -o with -c
if test "$compiler_c_o" = no; then
output_obj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext}
lockfile="$output_obj.lock"
removelist="$removelist $output_obj $lockfile"
trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15
else
output_obj=
need_locks=no
lockfile=
fi
# Lock this critical section if it is needed
# We use this script file to make the link, it avoids creating a new file
if test "$need_locks" = yes; then
until $run ln "$progpath" "$lockfile" 2>/dev/null; do
$show "Waiting for $lockfile to be removed"
sleep 2
done
elif test "$need_locks" = warn; then
if test -f "$lockfile"; then
$echo "\
*** ERROR, $lockfile exists and contains:
`cat $lockfile 2>/dev/null`
This indicates that another process is trying to use the same
temporary object file, and libtool could not work around it because
your compiler does not support \`-c' and \`-o' together. If you
repeat this compilation, it may succeed, by chance, but you had better
avoid parallel builds (make -j) in this platform, or get a better
compiler."
$run $rm $removelist
exit $EXIT_FAILURE
fi
$echo "$srcfile" > "$lockfile"
fi
if test -n "$fix_srcfile_path"; then
eval srcfile=\"$fix_srcfile_path\"
fi
qsrcfile=`$echo "X$srcfile" | $Xsed -e "$sed_quote_subst"`
case $qsrcfile in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
qsrcfile="\"$qsrcfile\"" ;;
esac
$run $rm "$libobj" "${libobj}T"
# Create a libtool object file (analogous to a ".la" file),
# but don't create it if we're doing a dry run.
test -z "$run" && cat > ${libobj}T <<EOF
# $libobj - a libtool object file
# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
#
# Please DO NOT delete this file!
# It is necessary for linking the library.
# Name of the PIC object.
EOF
# Only build a PIC object if we are building libtool libraries.
if test "$build_libtool_libs" = yes; then
# Without this assignment, base_compile gets emptied.
fbsd_hideous_sh_bug=$base_compile
if test "$pic_mode" != no; then
command="$base_compile $qsrcfile $pic_flag"
else
# Don't build PIC code
command="$base_compile $qsrcfile"
fi
if test ! -d "${xdir}$objdir"; then
$show "$mkdir ${xdir}$objdir"
$run $mkdir ${xdir}$objdir
exit_status=$?
if test "$exit_status" -ne 0 && test ! -d "${xdir}$objdir"; then
exit $exit_status
fi
fi
if test -z "$output_obj"; then
# Place PIC objects in $objdir
command="$command -o $lobj"
fi
$run $rm "$lobj" "$output_obj"
$show "$command"
if $run eval "$command"; then :
else
test -n "$output_obj" && $run $rm $removelist
exit $EXIT_FAILURE
fi
if test "$need_locks" = warn &&
test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
$echo "\
*** ERROR, $lockfile contains:
`cat $lockfile 2>/dev/null`
but it should contain:
$srcfile
This indicates that another process is trying to use the same
temporary object file, and libtool could not work around it because
your compiler does not support \`-c' and \`-o' together. If you
repeat this compilation, it may succeed, by chance, but you had better
avoid parallel builds (make -j) in this platform, or get a better
compiler."
$run $rm $removelist
exit $EXIT_FAILURE
fi
# Just move the object if needed, then go on to compile the next one
if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then
$show "$mv $output_obj $lobj"
if $run $mv $output_obj $lobj; then :
else
error=$?
$run $rm $removelist
exit $error
fi
fi
# Append the name of the PIC object to the libtool object file.
test -z "$run" && cat >> ${libobj}T <<EOF
pic_object='$objdir/$objname'
EOF
# Allow error messages only from the first compilation.
if test "$suppress_opt" = yes; then
suppress_output=' >/dev/null 2>&1'
fi
else
# No PIC object so indicate it doesn't exist in the libtool
# object file.
test -z "$run" && cat >> ${libobj}T <<EOF
pic_object=none
EOF
fi
# Only build a position-dependent object if we build old libraries.
if test "$build_old_libs" = yes; then
if test "$pic_mode" != yes; then
# Don't build PIC code
command="$base_compile $qsrcfile"
else
command="$base_compile $qsrcfile $pic_flag"
fi
if test "$compiler_c_o" = yes; then
command="$command -o $obj"
fi
# Suppress compiler output if we already did a PIC compilation.
command="$command$suppress_output"
$run $rm "$obj" "$output_obj"
$show "$command"
if $run eval "$command"; then :
else
$run $rm $removelist
exit $EXIT_FAILURE
fi
if test "$need_locks" = warn &&
test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
$echo "\
*** ERROR, $lockfile contains:
`cat $lockfile 2>/dev/null`
but it should contain:
$srcfile
This indicates that another process is trying to use the same
temporary object file, and libtool could not work around it because
your compiler does not support \`-c' and \`-o' together. If you
repeat this compilation, it may succeed, by chance, but you had better
avoid parallel builds (make -j) in this platform, or get a better
compiler."
$run $rm $removelist
exit $EXIT_FAILURE
fi
# Just move the object if needed
if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then
$show "$mv $output_obj $obj"
if $run $mv $output_obj $obj; then :
else
error=$?
$run $rm $removelist
exit $error
fi
fi
# Append the name of the non-PIC object the libtool object file.
# Only append if the libtool object file exists.
test -z "$run" && cat >> ${libobj}T <<EOF
# Name of the non-PIC object.
non_pic_object='$objname'
EOF
else
# Append the name of the non-PIC object the libtool object file.
# Only append if the libtool object file exists.
test -z "$run" && cat >> ${libobj}T <<EOF
# Name of the non-PIC object.
non_pic_object=none
EOF
fi
$run $mv "${libobj}T" "${libobj}"
# Unlock the critical section if it was locked
if test "$need_locks" != no; then
$run $rm "$lockfile"
fi
exit $EXIT_SUCCESS
;;
# libtool link mode
link | relink)
modename="$modename: link"
case $host in
*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
# It is impossible to link a dll without this setting, and
# we shouldn't force the makefile maintainer to figure out
# which system we are compiling for in order to pass an extra
# flag for every libtool invocation.
# allow_undefined=no
# FIXME: Unfortunately, there are problems with the above when trying
# to make a dll which has undefined symbols, in which case not
# even a static library is built. For now, we need to specify
# -no-undefined on the libtool link line when we can be certain
# that all symbols are satisfied, otherwise we get a static library.
allow_undefined=yes
;;
*)
allow_undefined=yes
;;
esac
libtool_args="$nonopt"
base_compile="$nonopt $@"
compile_command="$nonopt"
finalize_command="$nonopt"
compile_rpath=
finalize_rpath=
compile_shlibpath=
finalize_shlibpath=
convenience=
old_convenience=
deplibs=
old_deplibs=
compiler_flags=
linker_flags=
dllsearchpath=
lib_search_path=`pwd`
inst_prefix_dir=
avoid_version=no
dlfiles=
dlprefiles=
dlself=no
export_dynamic=no
export_symbols=
export_symbols_regex=
generated=
libobjs=
ltlibs=
module=no
no_install=no
objs=
non_pic_objects=
notinst_path= # paths that contain not-installed libtool libraries
precious_files_regex=
prefer_static_libs=no
preload=no
prev=
prevarg=
release=
rpath=
xrpath=
perm_rpath=
temp_rpath=
thread_safe=no
vinfo=
vinfo_number=no
func_infer_tag $base_compile
# We need to know -static, to get the right output filenames.
for arg
do
case $arg in
-all-static | -static | -static-libtool-libs)
case $arg in
-all-static)
if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then
$echo "$modename: warning: complete static linking is impossible in this configuration" 1>&2
fi
if test -n "$link_static_flag"; then
dlopen_self=$dlopen_self_static
fi
prefer_static_libs=yes
;;
-static)
if test -z "$pic_flag" && test -n "$link_static_flag"; then
dlopen_self=$dlopen_self_static
fi
prefer_static_libs=built
;;
-static-libtool-libs)
if test -z "$pic_flag" && test -n "$link_static_flag"; then
dlopen_self=$dlopen_self_static
fi
prefer_static_libs=yes
;;
esac
build_libtool_libs=no
build_old_libs=yes
break
;;
esac
done
# See if our shared archives depend on static archives.
test -n "$old_archive_from_new_cmds" && build_old_libs=yes
# Go through the arguments, transforming them on the way.
while test "$#" -gt 0; do
arg="$1"
shift
case $arg in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
qarg=\"`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`\" ### testsuite: skip nested quoting test
;;
*) qarg=$arg ;;
esac
libtool_args="$libtool_args $qarg"
# If the previous option needs an argument, assign it.
if test -n "$prev"; then
case $prev in
output)
compile_command="$compile_command @OUTPUT@"
finalize_command="$finalize_command @OUTPUT@"
;;
esac
case $prev in
dlfiles|dlprefiles)
if test "$preload" = no; then
# Add the symbol object into the linking commands.
compile_command="$compile_command @SYMFILE@"
finalize_command="$finalize_command @SYMFILE@"
preload=yes
fi
case $arg in
*.la | *.lo) ;; # We handle these cases below.
force)
if test "$dlself" = no; then
dlself=needless
export_dynamic=yes
fi
prev=
continue
;;
self)
if test "$prev" = dlprefiles; then
dlself=yes
elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then
dlself=yes
else
dlself=needless
export_dynamic=yes
fi
prev=
continue
;;
*)
if test "$prev" = dlfiles; then
dlfiles="$dlfiles $arg"
else
dlprefiles="$dlprefiles $arg"
fi
prev=
continue
;;
esac
;;
expsyms)
export_symbols="$arg"
if test ! -f "$arg"; then
$echo "$modename: symbol file \`$arg' does not exist"
exit $EXIT_FAILURE
fi
prev=
continue
;;
expsyms_regex)
export_symbols_regex="$arg"
prev=
continue
;;
inst_prefix)
inst_prefix_dir="$arg"
prev=
continue
;;
precious_regex)
precious_files_regex="$arg"
prev=
continue
;;
release)
release="-$arg"
prev=
continue
;;
objectlist)
if test -f "$arg"; then
save_arg=$arg
moreargs=
for fil in `cat $save_arg`
do
# moreargs="$moreargs $fil"
arg=$fil
# A libtool-controlled object.
# Check to see that this really is a libtool object.
if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
pic_object=
non_pic_object=
# Read the .lo file
# If there is no directory component, then add one.
case $arg in
*/* | *\\*) . $arg ;;
*) . ./$arg ;;
esac
if test -z "$pic_object" || \
test -z "$non_pic_object" ||
test "$pic_object" = none && \
test "$non_pic_object" = none; then
$echo "$modename: cannot find name of object for \`$arg'" 1>&2
exit $EXIT_FAILURE
fi
# Extract subdirectory from the argument.
xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
if test "X$xdir" = "X$arg"; then
xdir=
else
xdir="$xdir/"
fi
if test "$pic_object" != none; then
# Prepend the subdirectory the object is found in.
pic_object="$xdir$pic_object"
if test "$prev" = dlfiles; then
if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
dlfiles="$dlfiles $pic_object"
prev=
continue
else
# If libtool objects are unsupported, then we need to preload.
prev=dlprefiles
fi
fi
# CHECK ME: I think I busted this. -Ossama
if test "$prev" = dlprefiles; then
# Preload the old-style object.
dlprefiles="$dlprefiles $pic_object"
prev=
fi
# A PIC object.
libobjs="$libobjs $pic_object"
arg="$pic_object"
fi
# Non-PIC object.
if test "$non_pic_object" != none; then
# Prepend the subdirectory the object is found in.
non_pic_object="$xdir$non_pic_object"
# A standard non-PIC object
non_pic_objects="$non_pic_objects $non_pic_object"
if test -z "$pic_object" || test "$pic_object" = none ; then
arg="$non_pic_object"
fi
else
# If the PIC object exists, use it instead.
# $xdir was prepended to $pic_object above.
non_pic_object="$pic_object"
non_pic_objects="$non_pic_objects $non_pic_object"
fi
else
# Only an error if not doing a dry-run.
if test -z "$run"; then
$echo "$modename: \`$arg' is not a valid libtool object" 1>&2
exit $EXIT_FAILURE
else
# Dry-run case.
# Extract subdirectory from the argument.
xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
if test "X$xdir" = "X$arg"; then
xdir=
else
xdir="$xdir/"
fi
pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"`
non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"`
libobjs="$libobjs $pic_object"
non_pic_objects="$non_pic_objects $non_pic_object"
fi
fi
done
else
$echo "$modename: link input file \`$save_arg' does not exist"
exit $EXIT_FAILURE
fi
arg=$save_arg
prev=
continue
;;
rpath | xrpath)
# We need an absolute path.
case $arg in
[\\/]* | [A-Za-z]:[\\/]*) ;;
*)
$echo "$modename: only absolute run-paths are allowed" 1>&2
exit $EXIT_FAILURE
;;
esac
if test "$prev" = rpath; then
case "$rpath " in
*" $arg "*) ;;
*) rpath="$rpath $arg" ;;
esac
else
case "$xrpath " in
*" $arg "*) ;;
*) xrpath="$xrpath $arg" ;;
esac
fi
prev=
continue
;;
xcompiler)
compiler_flags="$compiler_flags $qarg"
prev=
compile_command="$compile_command $qarg"
finalize_command="$finalize_command $qarg"
continue
;;
xlinker)
linker_flags="$linker_flags $qarg"
compiler_flags="$compiler_flags $wl$qarg"
prev=
compile_command="$compile_command $wl$qarg"
finalize_command="$finalize_command $wl$qarg"
continue
;;
xcclinker)
linker_flags="$linker_flags $qarg"
compiler_flags="$compiler_flags $qarg"
prev=
compile_command="$compile_command $qarg"
finalize_command="$finalize_command $qarg"
continue
;;
shrext)
shrext_cmds="$arg"
prev=
continue
;;
darwin_framework|darwin_framework_skip)
test "$prev" = "darwin_framework" && compiler_flags="$compiler_flags $arg"
compile_command="$compile_command $arg"
finalize_command="$finalize_command $arg"
prev=
continue
;;
*)
eval "$prev=\"\$arg\""
prev=
continue
;;
esac
fi # test -n "$prev"
prevarg="$arg"
case $arg in
-all-static)
if test -n "$link_static_flag"; then
compile_command="$compile_command $link_static_flag"
finalize_command="$finalize_command $link_static_flag"
fi
continue
;;
-allow-undefined)
# FIXME: remove this flag sometime in the future.
$echo "$modename: \`-allow-undefined' is deprecated because it is the default" 1>&2
continue
;;
-avoid-version)
avoid_version=yes
continue
;;
-dlopen)
prev=dlfiles
continue
;;
-dlpreopen)
prev=dlprefiles
continue
;;
-export-dynamic)
export_dynamic=yes
continue
;;
-export-symbols | -export-symbols-regex)
if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
$echo "$modename: more than one -exported-symbols argument is not allowed"
exit $EXIT_FAILURE
fi
if test "X$arg" = "X-export-symbols"; then
prev=expsyms
else
prev=expsyms_regex
fi
continue
;;
-framework|-arch|-isysroot)
case " $CC " in
*" ${arg} ${1} "* | *" ${arg} ${1} "*)
prev=darwin_framework_skip ;;
*) compiler_flags="$compiler_flags $arg"
prev=darwin_framework ;;
esac
compile_command="$compile_command $arg"
finalize_command="$finalize_command $arg"
continue
;;
-inst-prefix-dir)
prev=inst_prefix
continue
;;
# The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*
# so, if we see these flags be careful not to treat them like -L
-L[A-Z][A-Z]*:*)
case $with_gcc/$host in
no/*-*-irix* | /*-*-irix*)
compile_command="$compile_command $arg"
finalize_command="$finalize_command $arg"
;;
esac
continue
;;
-L*)
dir=`$echo "X$arg" | $Xsed -e 's/^-L//'`
# We need an absolute path.
case $dir in
[\\/]* | [A-Za-z]:[\\/]*) ;;
*)
absdir=`cd "$dir" && pwd`
if test -z "$absdir"; then
$echo "$modename: cannot determine absolute directory name of \`$dir'" 1>&2
absdir="$dir"
notinst_path="$notinst_path $dir"
fi
dir="$absdir"
;;
esac
case "$deplibs " in
*" -L$dir "*) ;;
*)
deplibs="$deplibs -L$dir"
lib_search_path="$lib_search_path $dir"
;;
esac
case $host in
*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
testbindir=`$echo "X$dir" | $Xsed -e 's*/lib$*/bin*'`
case :$dllsearchpath: in
*":$dir:"*) ;;
*) dllsearchpath="$dllsearchpath:$dir";;
esac
case :$dllsearchpath: in
*":$testbindir:"*) ;;
*) dllsearchpath="$dllsearchpath:$testbindir";;
esac
;;
esac
continue
;;
-l*)
if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then
case $host in
*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos*)
# These systems don't actually have a C or math library (as such)
continue
;;
*-*-os2*)
# These systems don't actually have a C library (as such)
test "X$arg" = "X-lc" && continue
;;
*-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
# Do not include libc due to us having libc/libc_r.
test "X$arg" = "X-lc" && continue
;;
*-*-rhapsody* | *-*-darwin1.[012])
# Rhapsody C and math libraries are in the System framework
deplibs="$deplibs -framework System"
continue
;;
*-*-sco3.2v5* | *-*-sco5v6*)
# Causes problems with __ctype
test "X$arg" = "X-lc" && continue
;;
*-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
# Compiler inserts libc in the correct place for threads to work
test "X$arg" = "X-lc" && continue
;;
esac
elif test "X$arg" = "X-lc_r"; then
case $host in
*-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
# Do not include libc_r directly, use -pthread flag.
continue
;;
esac
fi
deplibs="$deplibs $arg"
continue
;;
# Tru64 UNIX uses -model [arg] to determine the layout of C++
# classes, name mangling, and exception handling.
-model)
compile_command="$compile_command $arg"
compiler_flags="$compiler_flags $arg"
finalize_command="$finalize_command $arg"
prev=xcompiler
continue
;;
-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe)
compiler_flags="$compiler_flags $arg"
compile_command="$compile_command $arg"
finalize_command="$finalize_command $arg"
continue
;;
-module)
module=yes
continue
;;
# -64, -mips[0-9] enable 64-bit mode on the SGI compiler
# -r[0-9][0-9]* specifies the processor on the SGI compiler
# -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler
# +DA*, +DD* enable 64-bit mode on the HP compiler
# -q* pass through compiler args for the IBM compiler
# -m* pass through architecture-specific compiler args for GCC
# -m*, -t[45]*, -txscale* pass through architecture-specific
# compiler args for GCC
# -pg pass through profiling flag for GCC
# @file GCC response files
-64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*|-pg| \
-t[45]*|-txscale*|@*)
# Unknown arguments in both finalize_command and compile_command need
# to be aesthetically quoted because they are evaled later.
arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
case $arg in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
arg="\"$arg\""
;;
esac
compile_command="$compile_command $arg"
finalize_command="$finalize_command $arg"
compiler_flags="$compiler_flags $arg"
continue
;;
-shrext)
prev=shrext
continue
;;
-no-fast-install)
fast_install=no
continue
;;
-no-install)
case $host in
*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
# The PATH hackery in wrapper scripts is required on Windows
# in order for the loader to find any dlls it needs.
$echo "$modename: warning: \`-no-install' is ignored for $host" 1>&2
$echo "$modename: warning: assuming \`-no-fast-install' instead" 1>&2
fast_install=no
;;
*) no_install=yes ;;
esac
continue
;;
-no-undefined)
allow_undefined=no
continue
;;
-objectlist)
prev=objectlist
continue
;;
-o) prev=output ;;
-precious-files-regex)
prev=precious_regex
continue
;;
-release)
prev=release
continue
;;
-rpath)
prev=rpath
continue
;;
-R)
prev=xrpath
continue
;;
-R*)
dir=`$echo "X$arg" | $Xsed -e 's/^-R//'`
# We need an absolute path.
case $dir in
[\\/]* | [A-Za-z]:[\\/]*) ;;
*)
$echo "$modename: only absolute run-paths are allowed" 1>&2
exit $EXIT_FAILURE
;;
esac
case "$xrpath " in
*" $dir "*) ;;
*) xrpath="$xrpath $dir" ;;
esac
continue
;;
-static | -static-libtool-libs)
# The effects of -static are defined in a previous loop.
# We used to do the same as -all-static on platforms that
# didn't have a PIC flag, but the assumption that the effects
# would be equivalent was wrong. It would break on at least
# Digital Unix and AIX.
continue
;;
-thread-safe)
thread_safe=yes
continue
;;
-version-info)
prev=vinfo
continue
;;
-version-number)
prev=vinfo
vinfo_number=yes
continue
;;
-Wc,*)
args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wc,//'`
arg=
save_ifs="$IFS"; IFS=','
for flag in $args; do
IFS="$save_ifs"
case $flag in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
flag="\"$flag\""
;;
esac
arg="$arg $wl$flag"
compiler_flags="$compiler_flags $flag"
done
IFS="$save_ifs"
arg=`$echo "X$arg" | $Xsed -e "s/^ //"`
;;
-Wl,*)
args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wl,//'`
arg=
save_ifs="$IFS"; IFS=','
for flag in $args; do
IFS="$save_ifs"
case $flag in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
flag="\"$flag\""
;;
esac
arg="$arg $wl$flag"
compiler_flags="$compiler_flags $wl$flag"
linker_flags="$linker_flags $flag"
done
IFS="$save_ifs"
arg=`$echo "X$arg" | $Xsed -e "s/^ //"`
;;
-Xcompiler)
prev=xcompiler
continue
;;
-Xlinker)
prev=xlinker
continue
;;
-XCClinker)
prev=xcclinker
continue
;;
# Some other compiler flag.
-* | +*)
# Unknown arguments in both finalize_command and compile_command need
# to be aesthetically quoted because they are evaled later.
arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
case $arg in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
arg="\"$arg\""
;;
esac
;;
*.$objext)
# A standard object.
objs="$objs $arg"
;;
*.lo)
# A libtool-controlled object.
# Check to see that this really is a libtool object.
if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
pic_object=
non_pic_object=
# Read the .lo file
# If there is no directory component, then add one.
case $arg in
*/* | *\\*) . $arg ;;
*) . ./$arg ;;
esac
if test -z "$pic_object" || \
test -z "$non_pic_object" ||
test "$pic_object" = none && \
test "$non_pic_object" = none; then
$echo "$modename: cannot find name of object for \`$arg'" 1>&2
exit $EXIT_FAILURE
fi
# Extract subdirectory from the argument.
xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
if test "X$xdir" = "X$arg"; then
xdir=
else
xdir="$xdir/"
fi
if test "$pic_object" != none; then
# Prepend the subdirectory the object is found in.
pic_object="$xdir$pic_object"
if test "$prev" = dlfiles; then
if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
dlfiles="$dlfiles $pic_object"
prev=
continue
else
# If libtool objects are unsupported, then we need to preload.
prev=dlprefiles
fi
fi
# CHECK ME: I think I busted this. -Ossama
if test "$prev" = dlprefiles; then
# Preload the old-style object.
dlprefiles="$dlprefiles $pic_object"
prev=
fi
# A PIC object.
libobjs="$libobjs $pic_object"
arg="$pic_object"
fi
# Non-PIC object.
if test "$non_pic_object" != none; then
# Prepend the subdirectory the object is found in.
non_pic_object="$xdir$non_pic_object"
# A standard non-PIC object
non_pic_objects="$non_pic_objects $non_pic_object"
if test -z "$pic_object" || test "$pic_object" = none ; then
arg="$non_pic_object"
fi
else
# If the PIC object exists, use it instead.
# $xdir was prepended to $pic_object above.
non_pic_object="$pic_object"
non_pic_objects="$non_pic_objects $non_pic_object"
fi
else
# Only an error if not doing a dry-run.
if test -z "$run"; then
$echo "$modename: \`$arg' is not a valid libtool object" 1>&2
exit $EXIT_FAILURE
else
# Dry-run case.
# Extract subdirectory from the argument.
xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
if test "X$xdir" = "X$arg"; then
xdir=
else
xdir="$xdir/"
fi
pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"`
non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"`
libobjs="$libobjs $pic_object"
non_pic_objects="$non_pic_objects $non_pic_object"
fi
fi
;;
*.$libext)
# An archive.
deplibs="$deplibs $arg"
old_deplibs="$old_deplibs $arg"
continue
;;
*.la)
# A libtool-controlled library.
if test "$prev" = dlfiles; then
# This library was specified with -dlopen.
dlfiles="$dlfiles $arg"
prev=
elif test "$prev" = dlprefiles; then
# The library was specified with -dlpreopen.
dlprefiles="$dlprefiles $arg"
prev=
else
deplibs="$deplibs $arg"
fi
continue
;;
# Some other compiler argument.
*)
# Unknown arguments in both finalize_command and compile_command need
# to be aesthetically quoted because they are evaled later.
arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
case $arg in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
arg="\"$arg\""
;;
esac
;;
esac # arg
# Now actually substitute the argument into the commands.
if test -n "$arg"; then
compile_command="$compile_command $arg"
finalize_command="$finalize_command $arg"
fi
done # argument parsing loop
if test -n "$prev"; then
$echo "$modename: the \`$prevarg' option requires an argument" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then
eval arg=\"$export_dynamic_flag_spec\"
compile_command="$compile_command $arg"
finalize_command="$finalize_command $arg"
fi
oldlibs=
# calculate the name of the file, without its directory
outputname=`$echo "X$output" | $Xsed -e 's%^.*/%%'`
libobjs_save="$libobjs"
if test -n "$shlibpath_var"; then
# get the directories listed in $shlibpath_var
eval shlib_search_path=\`\$echo \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\`
else
shlib_search_path=
fi
eval sys_lib_search_path=\"$sys_lib_search_path_spec\"
eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\"
output_objdir=`$echo "X$output" | $Xsed -e 's%/[^/]*$%%'`
if test "X$output_objdir" = "X$output"; then
output_objdir="$objdir"
else
output_objdir="$output_objdir/$objdir"
fi
# Create the object directory.
if test ! -d "$output_objdir"; then
$show "$mkdir $output_objdir"
$run $mkdir $output_objdir
exit_status=$?
if test "$exit_status" -ne 0 && test ! -d "$output_objdir"; then
exit $exit_status
fi
fi
# Determine the type of output
case $output in
"")
$echo "$modename: you must specify an output file" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
;;
*.$libext) linkmode=oldlib ;;
*.lo | *.$objext) linkmode=obj ;;
*.la) linkmode=lib ;;
*) linkmode=prog ;; # Anything else should be a program.
esac
case $host in
*cygwin* | *mingw* | *pw32*)
# don't eliminate duplications in $postdeps and $predeps
duplicate_compiler_generated_deps=yes
;;
*)
duplicate_compiler_generated_deps=$duplicate_deps
;;
esac
specialdeplibs=
libs=
# Find all interdependent deplibs by searching for libraries
# that are linked more than once (e.g. -la -lb -la)
for deplib in $deplibs; do
if test "X$duplicate_deps" = "Xyes" ; then
case "$libs " in
*" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
esac
fi
libs="$libs $deplib"
done
if test "$linkmode" = lib; then
libs="$predeps $libs $compiler_lib_search_path $postdeps"
# Compute libraries that are listed more than once in $predeps
# $postdeps and mark them as special (i.e., whose duplicates are
# not to be eliminated).
pre_post_deps=
if test "X$duplicate_compiler_generated_deps" = "Xyes" ; then
for pre_post_dep in $predeps $postdeps; do
case "$pre_post_deps " in
*" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;;
esac
pre_post_deps="$pre_post_deps $pre_post_dep"
done
fi
pre_post_deps=
fi
deplibs=
newdependency_libs=
newlib_search_path=
need_relink=no # whether we're linking any uninstalled libtool libraries
notinst_deplibs= # not-installed libtool libraries
case $linkmode in
lib)
passes="conv link"
for file in $dlfiles $dlprefiles; do
case $file in
*.la) ;;
*)
$echo "$modename: libraries can \`-dlopen' only libtool libraries: $file" 1>&2
exit $EXIT_FAILURE
;;
esac
done
;;
prog)
compile_deplibs=
finalize_deplibs=
alldeplibs=no
newdlfiles=
newdlprefiles=
passes="conv scan dlopen dlpreopen link"
;;
*) passes="conv"
;;
esac
for pass in $passes; do
if test "$linkmode,$pass" = "lib,link" ||
test "$linkmode,$pass" = "prog,scan"; then
libs="$deplibs"
deplibs=
fi
if test "$linkmode" = prog; then
case $pass in
dlopen) libs="$dlfiles" ;;
dlpreopen) libs="$dlprefiles" ;;
link) libs="$deplibs %DEPLIBS% $dependency_libs" ;;
esac
fi
if test "$pass" = dlopen; then
# Collect dlpreopened libraries
save_deplibs="$deplibs"
deplibs=
fi
for deplib in $libs; do
lib=
found=no
case $deplib in
-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe)
if test "$linkmode,$pass" = "prog,link"; then
compile_deplibs="$deplib $compile_deplibs"
finalize_deplibs="$deplib $finalize_deplibs"
else
compiler_flags="$compiler_flags $deplib"
fi
continue
;;
-l*)
if test "$linkmode" != lib && test "$linkmode" != prog; then
$echo "$modename: warning: \`-l' is ignored for archives/objects" 1>&2
continue
fi
name=`$echo "X$deplib" | $Xsed -e 's/^-l//'`
for searchdir in $newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path; do
for search_ext in .la $std_shrext .so .a; do
# Search the libtool library
lib="$searchdir/lib${name}${search_ext}"
if test -f "$lib"; then
if test "$search_ext" = ".la"; then
found=yes
else
found=no
fi
break 2
fi
done
done
if test "$found" != yes; then
# deplib doesn't seem to be a libtool library
if test "$linkmode,$pass" = "prog,link"; then
compile_deplibs="$deplib $compile_deplibs"
finalize_deplibs="$deplib $finalize_deplibs"
else
deplibs="$deplib $deplibs"
test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
fi
continue
else # deplib is a libtool library
# If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,
# We need to do some special things here, and not later.
if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
case " $predeps $postdeps " in
*" $deplib "*)
if (${SED} -e '2q' $lib |
grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
library_names=
old_library=
case $lib in
*/* | *\\*) . $lib ;;
*) . ./$lib ;;
esac
for l in $old_library $library_names; do
ll="$l"
done
if test "X$ll" = "X$old_library" ; then # only static version available
found=no
ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'`
test "X$ladir" = "X$lib" && ladir="."
lib=$ladir/$old_library
if test "$linkmode,$pass" = "prog,link"; then
compile_deplibs="$deplib $compile_deplibs"
finalize_deplibs="$deplib $finalize_deplibs"
else
deplibs="$deplib $deplibs"
test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
fi
continue
fi
fi
;;
*) ;;
esac
fi
fi
;; # -l
-L*)
case $linkmode in
lib)
deplibs="$deplib $deplibs"
test "$pass" = conv && continue
newdependency_libs="$deplib $newdependency_libs"
newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`
;;
prog)
if test "$pass" = conv; then
deplibs="$deplib $deplibs"
continue
fi
if test "$pass" = scan; then
deplibs="$deplib $deplibs"
else
compile_deplibs="$deplib $compile_deplibs"
finalize_deplibs="$deplib $finalize_deplibs"
fi
newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`
;;
*)
$echo "$modename: warning: \`-L' is ignored for archives/objects" 1>&2
;;
esac # linkmode
continue
;; # -L
-R*)
if test "$pass" = link; then
dir=`$echo "X$deplib" | $Xsed -e 's/^-R//'`
# Make sure the xrpath contains only unique directories.
case "$xrpath " in
*" $dir "*) ;;
*) xrpath="$xrpath $dir" ;;
esac
fi
deplibs="$deplib $deplibs"
continue
;;
*.la) lib="$deplib" ;;
*.$libext)
if test "$pass" = conv; then
deplibs="$deplib $deplibs"
continue
fi
case $linkmode in
lib)
valid_a_lib=no
case $deplibs_check_method in
match_pattern*)
set dummy $deplibs_check_method
match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
if eval $echo \"$deplib\" 2>/dev/null \
| $SED 10q \
| $EGREP "$match_pattern_regex" > /dev/null; then
valid_a_lib=yes
fi
;;
pass_all)
valid_a_lib=yes
;;
esac
if test "$valid_a_lib" != yes; then
$echo
$echo "*** Warning: Trying to link with static lib archive $deplib."
$echo "*** I have the capability to make that library automatically link in when"
$echo "*** you link to this library. But I can only do this if you have a"
$echo "*** shared version of the library, which you do not appear to have"
$echo "*** because the file extensions .$libext of this argument makes me believe"
$echo "*** that it is just a static archive that I should not used here."
else
$echo
$echo "*** Warning: Linking the shared library $output against the"
$echo "*** static library $deplib is not portable!"
deplibs="$deplib $deplibs"
fi
continue
;;
prog)
if test "$pass" != link; then
deplibs="$deplib $deplibs"
else
compile_deplibs="$deplib $compile_deplibs"
finalize_deplibs="$deplib $finalize_deplibs"
fi
continue
;;
esac # linkmode
;; # *.$libext
*.lo | *.$objext)
if test "$pass" = conv; then
deplibs="$deplib $deplibs"
elif test "$linkmode" = prog; then
if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then
# If there is no dlopen support or we're linking statically,
# we need to preload.
newdlprefiles="$newdlprefiles $deplib"
compile_deplibs="$deplib $compile_deplibs"
finalize_deplibs="$deplib $finalize_deplibs"
else
newdlfiles="$newdlfiles $deplib"
fi
fi
continue
;;
%DEPLIBS%)
alldeplibs=yes
continue
;;
esac # case $deplib
if test "$found" = yes || test -f "$lib"; then :
else
$echo "$modename: cannot find the library \`$lib' or unhandled argument \`$deplib'" 1>&2
exit $EXIT_FAILURE
fi
# Check to see that this really is a libtool archive.
if (${SED} -e '2q' $lib | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then :
else
$echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
exit $EXIT_FAILURE
fi
ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'`
test "X$ladir" = "X$lib" && ladir="."
dlname=
dlopen=
dlpreopen=
libdir=
library_names=
old_library=
# If the library was installed with an old release of libtool,
# it will not redefine variables installed, or shouldnotlink
installed=yes
shouldnotlink=no
avoidtemprpath=
# Read the .la file
case $lib in
*/* | *\\*) . $lib ;;
*) . ./$lib ;;
esac
if test "$linkmode,$pass" = "lib,link" ||
test "$linkmode,$pass" = "prog,scan" ||
{ test "$linkmode" != prog && test "$linkmode" != lib; }; then
test -n "$dlopen" && dlfiles="$dlfiles $dlopen"
test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen"
fi
if test "$pass" = conv; then
# Only check for convenience libraries
deplibs="$lib $deplibs"
if test -z "$libdir"; then
if test -z "$old_library"; then
$echo "$modename: cannot find name of link library for \`$lib'" 1>&2
exit $EXIT_FAILURE
fi
# It is a libtool convenience library, so add in its objects.
convenience="$convenience $ladir/$objdir/$old_library"
old_convenience="$old_convenience $ladir/$objdir/$old_library"
tmp_libs=
for deplib in $dependency_libs; do
deplibs="$deplib $deplibs"
if test "X$duplicate_deps" = "Xyes" ; then
case "$tmp_libs " in
*" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
esac
fi
tmp_libs="$tmp_libs $deplib"
done
elif test "$linkmode" != prog && test "$linkmode" != lib; then
$echo "$modename: \`$lib' is not a convenience library" 1>&2
exit $EXIT_FAILURE
fi
continue
fi # $pass = conv
# Get the name of the library we link against.
linklib=
for l in $old_library $library_names; do
linklib="$l"
done
if test -z "$linklib"; then
$echo "$modename: cannot find name of link library for \`$lib'" 1>&2
exit $EXIT_FAILURE
fi
# This library was specified with -dlopen.
if test "$pass" = dlopen; then
if test -z "$libdir"; then
$echo "$modename: cannot -dlopen a convenience library: \`$lib'" 1>&2
exit $EXIT_FAILURE
fi
if test -z "$dlname" ||
test "$dlopen_support" != yes ||
test "$build_libtool_libs" = no; then
# If there is no dlname, no dlopen support or we're linking
# statically, we need to preload. We also need to preload any
# dependent libraries so libltdl's deplib preloader doesn't
# bomb out in the load deplibs phase.
dlprefiles="$dlprefiles $lib $dependency_libs"
else
newdlfiles="$newdlfiles $lib"
fi
continue
fi # $pass = dlopen
# We need an absolute path.
case $ladir in
[\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;;
*)
abs_ladir=`cd "$ladir" && pwd`
if test -z "$abs_ladir"; then
$echo "$modename: warning: cannot determine absolute directory name of \`$ladir'" 1>&2
$echo "$modename: passing it literally to the linker, although it might fail" 1>&2
abs_ladir="$ladir"
fi
;;
esac
laname=`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
# Find the relevant object directory and library name.
if test "X$installed" = Xyes; then
if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
$echo "$modename: warning: library \`$lib' was moved." 1>&2
dir="$ladir"
absdir="$abs_ladir"
libdir="$abs_ladir"
else
dir="$libdir"
absdir="$libdir"
fi
test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
else
if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then
dir="$ladir"
absdir="$abs_ladir"
# Remove this search path later
notinst_path="$notinst_path $abs_ladir"
else
dir="$ladir/$objdir"
absdir="$abs_ladir/$objdir"
# Remove this search path later
notinst_path="$notinst_path $abs_ladir"
fi
fi # $installed = yes
name=`$echo "X$laname" | $Xsed -e 's/\.la$//' -e 's/^lib//'`
# This library was specified with -dlpreopen.
if test "$pass" = dlpreopen; then
if test -z "$libdir"; then
$echo "$modename: cannot -dlpreopen a convenience library: \`$lib'" 1>&2
exit $EXIT_FAILURE
fi
# Prefer using a static library (so that no silly _DYNAMIC symbols
# are required to link).
if test -n "$old_library"; then
newdlprefiles="$newdlprefiles $dir/$old_library"
# Otherwise, use the dlname, so that lt_dlopen finds it.
elif test -n "$dlname"; then
newdlprefiles="$newdlprefiles $dir/$dlname"
else
newdlprefiles="$newdlprefiles $dir/$linklib"
fi
fi # $pass = dlpreopen
if test -z "$libdir"; then
# Link the convenience library
if test "$linkmode" = lib; then
deplibs="$dir/$old_library $deplibs"
elif test "$linkmode,$pass" = "prog,link"; then
compile_deplibs="$dir/$old_library $compile_deplibs"
finalize_deplibs="$dir/$old_library $finalize_deplibs"
else
deplibs="$lib $deplibs" # used for prog,scan pass
fi
continue
fi
if test "$linkmode" = prog && test "$pass" != link; then
newlib_search_path="$newlib_search_path $ladir"
deplibs="$lib $deplibs"
linkalldeplibs=no
if test "$link_all_deplibs" != no || test -z "$library_names" ||
test "$build_libtool_libs" = no; then
linkalldeplibs=yes
fi
tmp_libs=
for deplib in $dependency_libs; do
case $deplib in
-L*) newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`;; ### testsuite: skip nested quoting test
esac
# Need to link against all dependency_libs?
if test "$linkalldeplibs" = yes; then
deplibs="$deplib $deplibs"
else
# Need to hardcode shared library paths
# or/and link against static libraries
newdependency_libs="$deplib $newdependency_libs"
fi
if test "X$duplicate_deps" = "Xyes" ; then
case "$tmp_libs " in
*" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
esac
fi
tmp_libs="$tmp_libs $deplib"
done # for deplib
continue
fi # $linkmode = prog...
if test "$linkmode,$pass" = "prog,link"; then
if test -n "$library_names" &&
{ { test "$prefer_static_libs" = no ||
test "$prefer_static_libs,$installed" = "built,yes"; } ||
test -z "$old_library"; }; then
# We need to hardcode the library path
if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then
# Make sure the rpath contains only unique directories.
case "$temp_rpath " in
*" $dir "*) ;;
*" $absdir "*) ;;
*) temp_rpath="$temp_rpath $absdir" ;;
esac
fi
# Hardcode the library path.
# Skip directories that are in the system default run-time
# search path.
case " $sys_lib_dlsearch_path " in
*" $absdir "*) ;;
*)
case "$compile_rpath " in
*" $absdir "*) ;;
*) compile_rpath="$compile_rpath $absdir"
esac
;;
esac
case " $sys_lib_dlsearch_path " in
*" $libdir "*) ;;
*)
case "$finalize_rpath " in
*" $libdir "*) ;;
*) finalize_rpath="$finalize_rpath $libdir"
esac
;;
esac
fi # $linkmode,$pass = prog,link...
if test "$alldeplibs" = yes &&
{ test "$deplibs_check_method" = pass_all ||
{ test "$build_libtool_libs" = yes &&
test -n "$library_names"; }; }; then
# We only need to search for static libraries
continue
fi
fi
link_static=no # Whether the deplib will be linked statically
use_static_libs=$prefer_static_libs
if test "$use_static_libs" = built && test "$installed" = yes ; then
use_static_libs=no
fi
if test -n "$library_names" &&
{ test "$use_static_libs" = no || test -z "$old_library"; }; then
if test "$installed" = no; then
notinst_deplibs="$notinst_deplibs $lib"
need_relink=yes
fi
# This is a shared library
# Warn about portability, can't link against -module's on
# some systems (darwin)
if test "$shouldnotlink" = yes && test "$pass" = link ; then
$echo
if test "$linkmode" = prog; then
$echo "*** Warning: Linking the executable $output against the loadable module"
else
$echo "*** Warning: Linking the shared library $output against the loadable module"
fi
$echo "*** $linklib is not portable!"
fi
if test "$linkmode" = lib &&
test "$hardcode_into_libs" = yes; then
# Hardcode the library path.
# Skip directories that are in the system default run-time
# search path.
case " $sys_lib_dlsearch_path " in
*" $absdir "*) ;;
*)
case "$compile_rpath " in
*" $absdir "*) ;;
*) compile_rpath="$compile_rpath $absdir"
esac
;;
esac
case " $sys_lib_dlsearch_path " in
*" $libdir "*) ;;
*)
case "$finalize_rpath " in
*" $libdir "*) ;;
*) finalize_rpath="$finalize_rpath $libdir"
esac
;;
esac
fi
if test -n "$old_archive_from_expsyms_cmds"; then
# figure out the soname
set dummy $library_names
realname="$2"
shift; shift
libname=`eval \\$echo \"$libname_spec\"`
# use dlname if we got it. it's perfectly good, no?
if test -n "$dlname"; then
soname="$dlname"
elif test -n "$soname_spec"; then
# bleh windows
case $host in
*cygwin* | mingw*)
major=`expr $current - $age`
versuffix="-$major"
;;
esac
eval soname=\"$soname_spec\"
else
soname="$realname"
fi
# Make a new name for the extract_expsyms_cmds to use
soroot="$soname"
soname=`$echo $soroot | ${SED} -e 's/^.*\///'`
newlib="libimp-`$echo $soname | ${SED} 's/^lib//;s/\.dll$//'`.a"
# If the library has no export list, then create one now
if test -f "$output_objdir/$soname-def"; then :
else
$show "extracting exported symbol list from \`$soname'"
save_ifs="$IFS"; IFS='~'
cmds=$extract_expsyms_cmds
for cmd in $cmds; do
IFS="$save_ifs"
eval cmd=\"$cmd\"
$show "$cmd"
$run eval "$cmd" || exit $?
done
IFS="$save_ifs"
fi
# Create $newlib
if test -f "$output_objdir/$newlib"; then :; else
$show "generating import library for \`$soname'"
save_ifs="$IFS"; IFS='~'
cmds=$old_archive_from_expsyms_cmds
for cmd in $cmds; do
IFS="$save_ifs"
eval cmd=\"$cmd\"
$show "$cmd"
$run eval "$cmd" || exit $?
done
IFS="$save_ifs"
fi
# make sure the library variables are pointing to the new library
dir=$output_objdir
linklib=$newlib
fi # test -n "$old_archive_from_expsyms_cmds"
if test "$linkmode" = prog || test "$mode" != relink; then
add_shlibpath=
add_dir=
add=
lib_linked=yes
case $hardcode_action in
immediate | unsupported)
if test "$hardcode_direct" = no; then
add="$dir/$linklib"
case $host in
*-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;;
*-*-sysv4*uw2*) add_dir="-L$dir" ;;
*-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \
*-*-unixware7*) add_dir="-L$dir" ;;
*-*-darwin* )
# if the lib is a module then we can not link against
# it, someone is ignoring the new warnings I added
if /usr/bin/file -L $add 2> /dev/null |
$EGREP ": [^:]* bundle" >/dev/null ; then
$echo "** Warning, lib $linklib is a module, not a shared library"
if test -z "$old_library" ; then
$echo
$echo "** And there doesn't seem to be a static archive available"
$echo "** The link will probably fail, sorry"
else
add="$dir/$old_library"
fi
fi
esac
elif test "$hardcode_minus_L" = no; then
case $host in
*-*-sunos*) add_shlibpath="$dir" ;;
esac
add_dir="-L$dir"
add="-l$name"
elif test "$hardcode_shlibpath_var" = no; then
add_shlibpath="$dir"
add="-l$name"
else
lib_linked=no
fi
;;
relink)
if test "$hardcode_direct" = yes; then
add="$dir/$linklib"
elif test "$hardcode_minus_L" = yes; then
add_dir="-L$dir"
# Try looking first in the location we're being installed to.
if test -n "$inst_prefix_dir"; then
case $libdir in
[\\/]*)
add_dir="$add_dir -L$inst_prefix_dir$libdir"
;;
esac
fi
add="-l$name"
elif test "$hardcode_shlibpath_var" = yes; then
add_shlibpath="$dir"
add="-l$name"
else
lib_linked=no
fi
;;
*) lib_linked=no ;;
esac
if test "$lib_linked" != yes; then
$echo "$modename: configuration error: unsupported hardcode properties"
exit $EXIT_FAILURE
fi
if test -n "$add_shlibpath"; then
case :$compile_shlibpath: in
*":$add_shlibpath:"*) ;;
*) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;;
esac
fi
if test "$linkmode" = prog; then
test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs"
test -n "$add" && compile_deplibs="$add $compile_deplibs"
else
test -n "$add_dir" && deplibs="$add_dir $deplibs"
test -n "$add" && deplibs="$add $deplibs"
if test "$hardcode_direct" != yes && \
test "$hardcode_minus_L" != yes && \
test "$hardcode_shlibpath_var" = yes; then
case :$finalize_shlibpath: in
*":$libdir:"*) ;;
*) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
esac
fi
fi
fi
if test "$linkmode" = prog || test "$mode" = relink; then
add_shlibpath=
add_dir=
add=
# Finalize command for both is simple: just hardcode it.
if test "$hardcode_direct" = yes; then
add="$libdir/$linklib"
elif test "$hardcode_minus_L" = yes; then
add_dir="-L$libdir"
add="-l$name"
elif test "$hardcode_shlibpath_var" = yes; then
case :$finalize_shlibpath: in
*":$libdir:"*) ;;
*) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
esac
add="-l$name"
elif test "$hardcode_automatic" = yes; then
if test -n "$inst_prefix_dir" &&
test -f "$inst_prefix_dir$libdir/$linklib" ; then
add="$inst_prefix_dir$libdir/$linklib"
else
add="$libdir/$linklib"
fi
else
# We cannot seem to hardcode it, guess we'll fake it.
add_dir="-L$libdir"
# Try looking first in the location we're being installed to.
if test -n "$inst_prefix_dir"; then
case $libdir in
[\\/]*)
add_dir="$add_dir -L$inst_prefix_dir$libdir"
;;
esac
fi
add="-l$name"
fi
if test "$linkmode" = prog; then
test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs"
test -n "$add" && finalize_deplibs="$add $finalize_deplibs"
else
test -n "$add_dir" && deplibs="$add_dir $deplibs"
test -n "$add" && deplibs="$add $deplibs"
fi
fi
elif test "$linkmode" = prog; then
# Here we assume that one of hardcode_direct or hardcode_minus_L
# is not unsupported. This is valid on all known static and
# shared platforms.
if test "$hardcode_direct" != unsupported; then
test -n "$old_library" && linklib="$old_library"
compile_deplibs="$dir/$linklib $compile_deplibs"
finalize_deplibs="$dir/$linklib $finalize_deplibs"
else
compile_deplibs="-l$name -L$dir $compile_deplibs"
finalize_deplibs="-l$name -L$dir $finalize_deplibs"
fi
elif test "$build_libtool_libs" = yes; then
# Not a shared library
if test "$deplibs_check_method" != pass_all; then
# We're trying link a shared library against a static one
# but the system doesn't support it.
# Just print a warning and add the library to dependency_libs so
# that the program can be linked against the static library.
$echo
$echo "*** Warning: This system can not link to static lib archive $lib."
$echo "*** I have the capability to make that library automatically link in when"
$echo "*** you link to this library. But I can only do this if you have a"
$echo "*** shared version of the library, which you do not appear to have."
if test "$module" = yes; then
$echo "*** But as you try to build a module library, libtool will still create "
$echo "*** a static module, that should work as long as the dlopening application"
$echo "*** is linked with the -dlopen flag to resolve symbols at runtime."
if test -z "$global_symbol_pipe"; then
$echo
$echo "*** However, this would only work if libtool was able to extract symbol"
$echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
$echo "*** not find such a program. So, this module is probably useless."
$echo "*** \`nm' from GNU binutils and a full rebuild may help."
fi
if test "$build_old_libs" = no; then
build_libtool_libs=module
build_old_libs=yes
else
build_libtool_libs=no
fi
fi
else
deplibs="$dir/$old_library $deplibs"
link_static=yes
fi
fi # link shared/static library?
if test "$linkmode" = lib; then
if test -n "$dependency_libs" &&
{ test "$hardcode_into_libs" != yes ||
test "$build_old_libs" = yes ||
test "$link_static" = yes; }; then
# Extract -R from dependency_libs
temp_deplibs=
for libdir in $dependency_libs; do
case $libdir in
-R*) temp_xrpath=`$echo "X$libdir" | $Xsed -e 's/^-R//'`
case " $xrpath " in
*" $temp_xrpath "*) ;;
*) xrpath="$xrpath $temp_xrpath";;
esac;;
*) temp_deplibs="$temp_deplibs $libdir";;
esac
done
dependency_libs="$temp_deplibs"
fi
newlib_search_path="$newlib_search_path $absdir"
# Link against this library
test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs"
# ... and its dependency_libs
tmp_libs=
for deplib in $dependency_libs; do
newdependency_libs="$deplib $newdependency_libs"
if test "X$duplicate_deps" = "Xyes" ; then
case "$tmp_libs " in
*" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
esac
fi
tmp_libs="$tmp_libs $deplib"
done
if test "$link_all_deplibs" != no; then
# Add the search paths of all dependency libraries
for deplib in $dependency_libs; do
case $deplib in
-L*) path="$deplib" ;;
*.la)
dir=`$echo "X$deplib" | $Xsed -e 's%/[^/]*$%%'`
test "X$dir" = "X$deplib" && dir="."
# We need an absolute path.
case $dir in
[\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;;
*)
absdir=`cd "$dir" && pwd`
if test -z "$absdir"; then
$echo "$modename: warning: cannot determine absolute directory name of \`$dir'" 1>&2
absdir="$dir"
fi
;;
esac
if grep "^installed=no" $deplib > /dev/null; then
path="$absdir/$objdir"
else
eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
if test -z "$libdir"; then
$echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2
exit $EXIT_FAILURE
fi
if test "$absdir" != "$libdir"; then
$echo "$modename: warning: \`$deplib' seems to be moved" 1>&2
fi
path="$absdir"
fi
depdepl=
case $host in
*-*-darwin*)
# we do not want to link against static libs,
# but need to link against shared
eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib`
if test -n "$deplibrary_names" ; then
for tmp in $deplibrary_names ; do
depdepl=$tmp
done
if test -f "$path/$depdepl" ; then
depdepl="$path/$depdepl"
fi
# do not add paths which are already there
case " $newlib_search_path " in
*" $path "*) ;;
*) newlib_search_path="$newlib_search_path $path";;
esac
fi
path=""
;;
*)
path="-L$path"
;;
esac
;;
-l*)
case $host in
*-*-darwin*)
# Again, we only want to link against shared libraries
eval tmp_libs=`$echo "X$deplib" | $Xsed -e "s,^\-l,,"`
for tmp in $newlib_search_path ; do
if test -f "$tmp/lib$tmp_libs.dylib" ; then
eval depdepl="$tmp/lib$tmp_libs.dylib"
break
fi
done
path=""
;;
*) continue ;;
esac
;;
*) continue ;;
esac
case " $deplibs " in
*" $path "*) ;;
*) deplibs="$path $deplibs" ;;
esac
case " $deplibs " in
*" $depdepl "*) ;;
*) deplibs="$depdepl $deplibs" ;;
esac
done
fi # link_all_deplibs != no
fi # linkmode = lib
done # for deplib in $libs
dependency_libs="$newdependency_libs"
if test "$pass" = dlpreopen; then
# Link the dlpreopened libraries before other libraries
for deplib in $save_deplibs; do
deplibs="$deplib $deplibs"
done
fi
if test "$pass" != dlopen; then
if test "$pass" != conv; then
# Make sure lib_search_path contains only unique directories.
lib_search_path=
for dir in $newlib_search_path; do
case "$lib_search_path " in
*" $dir "*) ;;
*) lib_search_path="$lib_search_path $dir" ;;
esac
done
newlib_search_path=
fi
if test "$linkmode,$pass" != "prog,link"; then
vars="deplibs"
else
vars="compile_deplibs finalize_deplibs"
fi
for var in $vars dependency_libs; do
# Add libraries to $var in reverse order
eval tmp_libs=\"\$$var\"
new_libs=
for deplib in $tmp_libs; do
# FIXME: Pedantically, this is the right thing to do, so
# that some nasty dependency loop isn't accidentally
# broken:
#new_libs="$deplib $new_libs"
# Pragmatically, this seems to cause very few problems in
# practice:
case $deplib in
-L*) new_libs="$deplib $new_libs" ;;
-R*) ;;
*)
# And here is the reason: when a library appears more
# than once as an explicit dependence of a library, or
# is implicitly linked in more than once by the
# compiler, it is considered special, and multiple
# occurrences thereof are not removed. Compare this
# with having the same library being listed as a
# dependency of multiple other libraries: in this case,
# we know (pedantically, we assume) the library does not
# need to be listed more than once, so we keep only the
# last copy. This is not always right, but it is rare
# enough that we require users that really mean to play
# such unportable linking tricks to link the library
# using -Wl,-lname, so that libtool does not consider it
# for duplicate removal.
case " $specialdeplibs " in
*" $deplib "*) new_libs="$deplib $new_libs" ;;
*)
case " $new_libs " in
*" $deplib "*) ;;
*) new_libs="$deplib $new_libs" ;;
esac
;;
esac
;;
esac
done
tmp_libs=
for deplib in $new_libs; do
case $deplib in
-L*)
case " $tmp_libs " in
*" $deplib "*) ;;
*) tmp_libs="$tmp_libs $deplib" ;;
esac
;;
*) tmp_libs="$tmp_libs $deplib" ;;
esac
done
eval $var=\"$tmp_libs\"
done # for var
fi
# Last step: remove runtime libs from dependency_libs
# (they stay in deplibs)
tmp_libs=
for i in $dependency_libs ; do
case " $predeps $postdeps $compiler_lib_search_path " in
*" $i "*)
i=""
;;
esac
if test -n "$i" ; then
tmp_libs="$tmp_libs $i"
fi
done
dependency_libs=$tmp_libs
done # for pass
if test "$linkmode" = prog; then
dlfiles="$newdlfiles"
dlprefiles="$newdlprefiles"
fi
case $linkmode in
oldlib)
if test -n "$deplibs"; then
$echo "$modename: warning: \`-l' and \`-L' are ignored for archives" 1>&2
fi
if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
$echo "$modename: warning: \`-dlopen' is ignored for archives" 1>&2
fi
if test -n "$rpath"; then
$echo "$modename: warning: \`-rpath' is ignored for archives" 1>&2
fi
if test -n "$xrpath"; then
$echo "$modename: warning: \`-R' is ignored for archives" 1>&2
fi
if test -n "$vinfo"; then
$echo "$modename: warning: \`-version-info/-version-number' is ignored for archives" 1>&2
fi
if test -n "$release"; then
$echo "$modename: warning: \`-release' is ignored for archives" 1>&2
fi
if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
$echo "$modename: warning: \`-export-symbols' is ignored for archives" 1>&2
fi
# Now set the variables for building old libraries.
build_libtool_libs=no
oldlibs="$output"
objs="$objs$old_deplibs"
;;
lib)
# Make sure we only generate libraries of the form `libNAME.la'.
case $outputname in
lib*)
name=`$echo "X$outputname" | $Xsed -e 's/\.la$//' -e 's/^lib//'`
eval shared_ext=\"$shrext_cmds\"
eval libname=\"$libname_spec\"
;;
*)
if test "$module" = no; then
$echo "$modename: libtool library \`$output' must begin with \`lib'" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
if test "$need_lib_prefix" != no; then
# Add the "lib" prefix for modules if required
name=`$echo "X$outputname" | $Xsed -e 's/\.la$//'`
eval shared_ext=\"$shrext_cmds\"
eval libname=\"$libname_spec\"
else
libname=`$echo "X$outputname" | $Xsed -e 's/\.la$//'`
fi
;;
esac
if test -n "$objs"; then
if test "$deplibs_check_method" != pass_all; then
$echo "$modename: cannot build libtool library \`$output' from non-libtool objects on this host:$objs" 2>&1
exit $EXIT_FAILURE
else
$echo
$echo "*** Warning: Linking the shared library $output against the non-libtool"
$echo "*** objects $objs is not portable!"
libobjs="$libobjs $objs"
fi
fi
if test "$dlself" != no; then
$echo "$modename: warning: \`-dlopen self' is ignored for libtool libraries" 1>&2
fi
set dummy $rpath
if test "$#" -gt 2; then
$echo "$modename: warning: ignoring multiple \`-rpath's for a libtool library" 1>&2
fi
install_libdir="$2"
oldlibs=
if test -z "$rpath"; then
if test "$build_libtool_libs" = yes; then
# Building a libtool convenience library.
# Some compilers have problems with a `.al' extension so
# convenience libraries should have the same extension an
# archive normally would.
oldlibs="$output_objdir/$libname.$libext $oldlibs"
build_libtool_libs=convenience
build_old_libs=yes
fi
if test -n "$vinfo"; then
$echo "$modename: warning: \`-version-info/-version-number' is ignored for convenience libraries" 1>&2
fi
if test -n "$release"; then
$echo "$modename: warning: \`-release' is ignored for convenience libraries" 1>&2
fi
else
# Parse the version information argument.
save_ifs="$IFS"; IFS=':'
set dummy $vinfo 0 0 0
IFS="$save_ifs"
if test -n "$8"; then
$echo "$modename: too many parameters to \`-version-info'" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
# convert absolute version numbers to libtool ages
# this retains compatibility with .la files and attempts
# to make the code below a bit more comprehensible
case $vinfo_number in
yes)
number_major="$2"
number_minor="$3"
number_revision="$4"
#
# There are really only two kinds -- those that
# use the current revision as the major version
# and those that subtract age and use age as
# a minor version. But, then there is irix
# which has an extra 1 added just for fun
#
case $version_type in
darwin|linux|osf|windows|none)
current=`expr $number_major + $number_minor`
age="$number_minor"
revision="$number_revision"
;;
freebsd-aout|freebsd-elf|sunos)
current="$number_major"
revision="$number_minor"
age="0"
;;
irix|nonstopux)
current=`expr $number_major + $number_minor - 1`
age="$number_minor"
revision="$number_minor"
;;
esac
;;
no)
current="$2"
revision="$3"
age="$4"
;;
esac
# Check that each of the things are valid numbers.
case $current in
0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
*)
$echo "$modename: CURRENT \`$current' must be a nonnegative integer" 1>&2
$echo "$modename: \`$vinfo' is not valid version information" 1>&2
exit $EXIT_FAILURE
;;
esac
case $revision in
0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
*)
$echo "$modename: REVISION \`$revision' must be a nonnegative integer" 1>&2
$echo "$modename: \`$vinfo' is not valid version information" 1>&2
exit $EXIT_FAILURE
;;
esac
case $age in
0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
*)
$echo "$modename: AGE \`$age' must be a nonnegative integer" 1>&2
$echo "$modename: \`$vinfo' is not valid version information" 1>&2
exit $EXIT_FAILURE
;;
esac
if test "$age" -gt "$current"; then
$echo "$modename: AGE \`$age' is greater than the current interface number \`$current'" 1>&2
$echo "$modename: \`$vinfo' is not valid version information" 1>&2
exit $EXIT_FAILURE
fi
# Calculate the version variables.
major=
versuffix=
verstring=
case $version_type in
none) ;;
darwin)
# Like Linux, but with the current version available in
# verstring for coding it into the library header
major=.`expr $current - $age`
versuffix="$major.$age.$revision"
# Darwin ld doesn't like 0 for these options...
minor_current=`expr $current + 1`
verstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision"
;;
freebsd-aout)
major=".$current"
versuffix=".$current.$revision";
;;
freebsd-elf)
major=".$current"
versuffix=".$current";
;;
irix | nonstopux)
major=`expr $current - $age + 1`
case $version_type in
nonstopux) verstring_prefix=nonstopux ;;
*) verstring_prefix=sgi ;;
esac
verstring="$verstring_prefix$major.$revision"
# Add in all the interfaces that we are compatible with.
loop=$revision
while test "$loop" -ne 0; do
iface=`expr $revision - $loop`
loop=`expr $loop - 1`
verstring="$verstring_prefix$major.$iface:$verstring"
done
# Before this point, $major must not contain `.'.
major=.$major
versuffix="$major.$revision"
;;
linux)
major=.`expr $current - $age`
versuffix="$major.$age.$revision"
;;
osf)
major=.`expr $current - $age`
versuffix=".$current.$age.$revision"
verstring="$current.$age.$revision"
# Add in all the interfaces that we are compatible with.
loop=$age
while test "$loop" -ne 0; do
iface=`expr $current - $loop`
loop=`expr $loop - 1`
verstring="$verstring:${iface}.0"
done
# Make executables depend on our current version.
verstring="$verstring:${current}.0"
;;
sunos)
major=".$current"
versuffix=".$current.$revision"
;;
windows)
# Use '-' rather than '.', since we only want one
# extension on DOS 8.3 filesystems.
major=`expr $current - $age`
versuffix="-$major"
;;
*)
$echo "$modename: unknown library version type \`$version_type'" 1>&2
$echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2
exit $EXIT_FAILURE
;;
esac
# Clear the version info if we defaulted, and they specified a release.
if test -z "$vinfo" && test -n "$release"; then
major=
case $version_type in
darwin)
# we can't check for "0.0" in archive_cmds due to quoting
# problems, so we reset it completely
verstring=
;;
*)
verstring="0.0"
;;
esac
if test "$need_version" = no; then
versuffix=
else
versuffix=".0.0"
fi
fi
# Remove version info from name if versioning should be avoided
if test "$avoid_version" = yes && test "$need_version" = no; then
major=
versuffix=
verstring=""
fi
# Check to see if the archive will have undefined symbols.
if test "$allow_undefined" = yes; then
if test "$allow_undefined_flag" = unsupported; then
$echo "$modename: warning: undefined symbols not allowed in $host shared libraries" 1>&2
build_libtool_libs=no
build_old_libs=yes
fi
else
# Don't allow undefined symbols.
allow_undefined_flag="$no_undefined_flag"
fi
fi
if test "$mode" != relink; then
# Remove our outputs, but don't remove object files since they
# may have been created when compiling PIC objects.
removelist=
tempremovelist=`$echo "$output_objdir/*"`
for p in $tempremovelist; do
case $p in
*.$objext)
;;
$output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*)
if test "X$precious_files_regex" != "X"; then
if echo $p | $EGREP -e "$precious_files_regex" >/dev/null 2>&1
then
continue
fi
fi
removelist="$removelist $p"
;;
*) ;;
esac
done
if test -n "$removelist"; then
$show "${rm}r $removelist"
$run ${rm}r $removelist
fi
fi
# Now set the variables for building old libraries.
if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then
oldlibs="$oldlibs $output_objdir/$libname.$libext"
# Transform .lo files to .o files.
oldobjs="$objs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP`
fi
# Eliminate all temporary directories.
# for path in $notinst_path; do
# lib_search_path=`$echo "$lib_search_path " | ${SED} -e "s% $path % %g"`
# deplibs=`$echo "$deplibs " | ${SED} -e "s% -L$path % %g"`
# dependency_libs=`$echo "$dependency_libs " | ${SED} -e "s% -L$path % %g"`
# done
if test -n "$xrpath"; then
# If the user specified any rpath flags, then add them.
temp_xrpath=
for libdir in $xrpath; do
temp_xrpath="$temp_xrpath -R$libdir"
case "$finalize_rpath " in
*" $libdir "*) ;;
*) finalize_rpath="$finalize_rpath $libdir" ;;
esac
done
if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then
dependency_libs="$temp_xrpath $dependency_libs"
fi
fi
# Make sure dlfiles contains only unique files that won't be dlpreopened
old_dlfiles="$dlfiles"
dlfiles=
for lib in $old_dlfiles; do
case " $dlprefiles $dlfiles " in
*" $lib "*) ;;
*) dlfiles="$dlfiles $lib" ;;
esac
done
# Make sure dlprefiles contains only unique files
old_dlprefiles="$dlprefiles"
dlprefiles=
for lib in $old_dlprefiles; do
case "$dlprefiles " in
*" $lib "*) ;;
*) dlprefiles="$dlprefiles $lib" ;;
esac
done
if test "$build_libtool_libs" = yes; then
if test -n "$rpath"; then
case $host in
*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos*)
# these systems don't actually have a c library (as such)!
;;
*-*-rhapsody* | *-*-darwin1.[012])
# Rhapsody C library is in the System framework
deplibs="$deplibs -framework System"
;;
*-*-netbsd*)
# Don't link with libc until the a.out ld.so is fixed.
;;
*-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
# Do not include libc due to us having libc/libc_r.
;;
*-*-sco3.2v5* | *-*-sco5v6*)
# Causes problems with __ctype
;;
*-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
# Compiler inserts libc in the correct place for threads to work
;;
*)
# Add libc to deplibs on all other systems if necessary.
if test "$build_libtool_need_lc" = "yes"; then
deplibs="$deplibs -lc"
fi
;;
esac
fi
# Transform deplibs into only deplibs that can be linked in shared.
name_save=$name
libname_save=$libname
release_save=$release
versuffix_save=$versuffix
major_save=$major
# I'm not sure if I'm treating the release correctly. I think
# release should show up in the -l (ie -lgmp5) so we don't want to
# add it in twice. Is that correct?
release=""
versuffix=""
major=""
newdeplibs=
droppeddeps=no
case $deplibs_check_method in
pass_all)
# Don't check for shared/static. Everything works.
# This might be a little naive. We might want to check
# whether the library exists or not. But this is on
# osf3 & osf4 and I'm not really sure... Just
# implementing what was already the behavior.
newdeplibs=$deplibs
;;
test_compile)
# This code stresses the "libraries are programs" paradigm to its
# limits. Maybe even breaks it. We compile a program, linking it
# against the deplibs as a proxy for the library. Then we can check
# whether they linked in statically or dynamically with ldd.
$rm conftest.c
cat > conftest.c <<EOF
int main() { return 0; }
EOF
$rm conftest
if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then
ldd_output=`ldd conftest`
for i in $deplibs; do
name=`expr $i : '-l\(.*\)'`
# If $name is empty we are operating on a -L argument.
if test "$name" != "" && test "$name" != "0"; then
if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
case " $predeps $postdeps " in
*" $i "*)
newdeplibs="$newdeplibs $i"
i=""
;;
esac
fi
if test -n "$i" ; then
libname=`eval \\$echo \"$libname_spec\"`
deplib_matches=`eval \\$echo \"$library_names_spec\"`
set dummy $deplib_matches
deplib_match=$2
if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
newdeplibs="$newdeplibs $i"
else
droppeddeps=yes
$echo
$echo "*** Warning: dynamic linker does not accept needed library $i."
$echo "*** I have the capability to make that library automatically link in when"
$echo "*** you link to this library. But I can only do this if you have a"
$echo "*** shared version of the library, which I believe you do not have"
$echo "*** because a test_compile did reveal that the linker did not use it for"
$echo "*** its dynamic dependency list that programs get resolved with at runtime."
fi
fi
else
newdeplibs="$newdeplibs $i"
fi
done
else
# Error occurred in the first compile. Let's try to salvage
# the situation: Compile a separate program for each library.
for i in $deplibs; do
name=`expr $i : '-l\(.*\)'`
# If $name is empty we are operating on a -L argument.
if test "$name" != "" && test "$name" != "0"; then
$rm conftest
if $LTCC $LTCFLAGS -o conftest conftest.c $i; then
ldd_output=`ldd conftest`
if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
case " $predeps $postdeps " in
*" $i "*)
newdeplibs="$newdeplibs $i"
i=""
;;
esac
fi
if test -n "$i" ; then
libname=`eval \\$echo \"$libname_spec\"`
deplib_matches=`eval \\$echo \"$library_names_spec\"`
set dummy $deplib_matches
deplib_match=$2
if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
newdeplibs="$newdeplibs $i"
else
droppeddeps=yes
$echo
$echo "*** Warning: dynamic linker does not accept needed library $i."
$echo "*** I have the capability to make that library automatically link in when"
$echo "*** you link to this library. But I can only do this if you have a"
$echo "*** shared version of the library, which you do not appear to have"
$echo "*** because a test_compile did reveal that the linker did not use this one"
$echo "*** as a dynamic dependency that programs can get resolved with at runtime."
fi
fi
else
droppeddeps=yes
$echo
$echo "*** Warning! Library $i is needed by this library but I was not able to"
$echo "*** make it link in! You will probably need to install it or some"
$echo "*** library that it depends on before this library will be fully"
$echo "*** functional. Installing it before continuing would be even better."
fi
else
newdeplibs="$newdeplibs $i"
fi
done
fi
;;
file_magic*)
set dummy $deplibs_check_method
file_magic_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
for a_deplib in $deplibs; do
name=`expr $a_deplib : '-l\(.*\)'`
# If $name is empty we are operating on a -L argument.
if test "$name" != "" && test "$name" != "0"; then
if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
case " $predeps $postdeps " in
*" $a_deplib "*)
newdeplibs="$newdeplibs $a_deplib"
a_deplib=""
;;
esac
fi
if test -n "$a_deplib" ; then
libname=`eval \\$echo \"$libname_spec\"`
for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
for potent_lib in $potential_libs; do
# Follow soft links.
if ls -lLd "$potent_lib" 2>/dev/null \
| grep " -> " >/dev/null; then
continue
fi
# The statement above tries to avoid entering an
# endless loop below, in case of cyclic links.
# We might still enter an endless loop, since a link
# loop can be closed while we follow links,
# but so what?
potlib="$potent_lib"
while test -h "$potlib" 2>/dev/null; do
potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'`
case $potliblink in
[\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";;
*) potlib=`$echo "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";;
esac
done
if eval $file_magic_cmd \"\$potlib\" 2>/dev/null \
| ${SED} 10q \
| $EGREP "$file_magic_regex" > /dev/null; then
newdeplibs="$newdeplibs $a_deplib"
a_deplib=""
break 2
fi
done
done
fi
if test -n "$a_deplib" ; then
droppeddeps=yes
$echo
$echo "*** Warning: linker path does not have real file for library $a_deplib."
$echo "*** I have the capability to make that library automatically link in when"
$echo "*** you link to this library. But I can only do this if you have a"
$echo "*** shared version of the library, which you do not appear to have"
$echo "*** because I did check the linker path looking for a file starting"
if test -z "$potlib" ; then
$echo "*** with $libname but no candidates were found. (...for file magic test)"
else
$echo "*** with $libname and none of the candidates passed a file format test"
$echo "*** using a file magic. Last file checked: $potlib"
fi
fi
else
# Add a -L argument.
newdeplibs="$newdeplibs $a_deplib"
fi
done # Gone through all deplibs.
;;
match_pattern*)
set dummy $deplibs_check_method
match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
for a_deplib in $deplibs; do
name=`expr $a_deplib : '-l\(.*\)'`
# If $name is empty we are operating on a -L argument.
if test -n "$name" && test "$name" != "0"; then
if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
case " $predeps $postdeps " in
*" $a_deplib "*)
newdeplibs="$newdeplibs $a_deplib"
a_deplib=""
;;
esac
fi
if test -n "$a_deplib" ; then
libname=`eval \\$echo \"$libname_spec\"`
for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
for potent_lib in $potential_libs; do
potlib="$potent_lib" # see symlink-check above in file_magic test
if eval $echo \"$potent_lib\" 2>/dev/null \
| ${SED} 10q \
| $EGREP "$match_pattern_regex" > /dev/null; then
newdeplibs="$newdeplibs $a_deplib"
a_deplib=""
break 2
fi
done
done
fi
if test -n "$a_deplib" ; then
droppeddeps=yes
$echo
$echo "*** Warning: linker path does not have real file for library $a_deplib."
$echo "*** I have the capability to make that library automatically link in when"
$echo "*** you link to this library. But I can only do this if you have a"
$echo "*** shared version of the library, which you do not appear to have"
$echo "*** because I did check the linker path looking for a file starting"
if test -z "$potlib" ; then
$echo "*** with $libname but no candidates were found. (...for regex pattern test)"
else
$echo "*** with $libname and none of the candidates passed a file format test"
$echo "*** using a regex pattern. Last file checked: $potlib"
fi
fi
else
# Add a -L argument.
newdeplibs="$newdeplibs $a_deplib"
fi
done # Gone through all deplibs.
;;
none | unknown | *)
newdeplibs=""
tmp_deplibs=`$echo "X $deplibs" | $Xsed -e 's/ -lc$//' \
-e 's/ -[LR][^ ]*//g'`
if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
for i in $predeps $postdeps ; do
# can't use Xsed below, because $i might contain '/'
tmp_deplibs=`$echo "X $tmp_deplibs" | ${SED} -e "1s,^X,," -e "s,$i,,"`
done
fi
if $echo "X $tmp_deplibs" | $Xsed -e 's/[ ]//g' \
| grep . >/dev/null; then
$echo
if test "X$deplibs_check_method" = "Xnone"; then
$echo "*** Warning: inter-library dependencies are not supported in this platform."
else
$echo "*** Warning: inter-library dependencies are not known to be supported."
fi
$echo "*** All declared inter-library dependencies are being dropped."
droppeddeps=yes
fi
;;
esac
versuffix=$versuffix_save
major=$major_save
release=$release_save
libname=$libname_save
name=$name_save
case $host in
*-*-rhapsody* | *-*-darwin1.[012])
# On Rhapsody replace the C library is the System framework
newdeplibs=`$echo "X $newdeplibs" | $Xsed -e 's/ -lc / -framework System /'`
;;
esac
if test "$droppeddeps" = yes; then
if test "$module" = yes; then
$echo
$echo "*** Warning: libtool could not satisfy all declared inter-library"
$echo "*** dependencies of module $libname. Therefore, libtool will create"
$echo "*** a static module, that should work as long as the dlopening"
$echo "*** application is linked with the -dlopen flag."
if test -z "$global_symbol_pipe"; then
$echo
$echo "*** However, this would only work if libtool was able to extract symbol"
$echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
$echo "*** not find such a program. So, this module is probably useless."
$echo "*** \`nm' from GNU binutils and a full rebuild may help."
fi
if test "$build_old_libs" = no; then
oldlibs="$output_objdir/$libname.$libext"
build_libtool_libs=module
build_old_libs=yes
else
build_libtool_libs=no
fi
else
$echo "*** The inter-library dependencies that have been dropped here will be"
$echo "*** automatically added whenever a program is linked with this library"
$echo "*** or is declared to -dlopen it."
if test "$allow_undefined" = no; then
$echo
$echo "*** Since this library must not contain undefined symbols,"
$echo "*** because either the platform does not support them or"
$echo "*** it was explicitly requested with -no-undefined,"
$echo "*** libtool will only create a static version of it."
if test "$build_old_libs" = no; then
oldlibs="$output_objdir/$libname.$libext"
build_libtool_libs=module
build_old_libs=yes
else
build_libtool_libs=no
fi
fi
fi
fi
# Done checking deplibs!
deplibs=$newdeplibs
fi
# move library search paths that coincide with paths to not yet
# installed libraries to the beginning of the library search list
new_libs=
for path in $notinst_path; do
case " $new_libs " in
*" -L$path/$objdir "*) ;;
*)
case " $deplibs " in
*" -L$path/$objdir "*)
new_libs="$new_libs -L$path/$objdir" ;;
esac
;;
esac
done
for deplib in $deplibs; do
case $deplib in
-L*)
case " $new_libs " in
*" $deplib "*) ;;
*) new_libs="$new_libs $deplib" ;;
esac
;;
*) new_libs="$new_libs $deplib" ;;
esac
done
deplibs="$new_libs"
# All the library-specific variables (install_libdir is set above).
library_names=
old_library=
dlname=
# Test again, we may have decided not to build it any more
if test "$build_libtool_libs" = yes; then
if test "$hardcode_into_libs" = yes; then
# Hardcode the library paths
hardcode_libdirs=
dep_rpath=
rpath="$finalize_rpath"
test "$mode" != relink && rpath="$compile_rpath$rpath"
for libdir in $rpath; do
if test -n "$hardcode_libdir_flag_spec"; then
if test -n "$hardcode_libdir_separator"; then
if test -z "$hardcode_libdirs"; then
hardcode_libdirs="$libdir"
else
# Just accumulate the unique libdirs.
case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
*"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
;;
*)
hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
;;
esac
fi
else
eval flag=\"$hardcode_libdir_flag_spec\"
dep_rpath="$dep_rpath $flag"
fi
elif test -n "$runpath_var"; then
case "$perm_rpath " in
*" $libdir "*) ;;
*) perm_rpath="$perm_rpath $libdir" ;;
esac
fi
done
# Substitute the hardcoded libdirs into the rpath.
if test -n "$hardcode_libdir_separator" &&
test -n "$hardcode_libdirs"; then
libdir="$hardcode_libdirs"
if test -n "$hardcode_libdir_flag_spec_ld"; then
eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\"
else
eval dep_rpath=\"$hardcode_libdir_flag_spec\"
fi
fi
if test -n "$runpath_var" && test -n "$perm_rpath"; then
# We should set the runpath_var.
rpath=
for dir in $perm_rpath; do
rpath="$rpath$dir:"
done
eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var"
fi
test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs"
fi
shlibpath="$finalize_shlibpath"
test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
if test -n "$shlibpath"; then
eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var"
fi
# Get the real and link names of the library.
eval shared_ext=\"$shrext_cmds\"
eval library_names=\"$library_names_spec\"
set dummy $library_names
realname="$2"
shift; shift
if test -n "$soname_spec"; then
eval soname=\"$soname_spec\"
else
soname="$realname"
fi
if test -z "$dlname"; then
dlname=$soname
fi
lib="$output_objdir/$realname"
linknames=
for link
do
linknames="$linknames $link"
done
# Use standard objects if they are pic
test -z "$pic_flag" && libobjs=`$echo "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
# Prepare the list of exported symbols
if test -z "$export_symbols"; then
if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then
$show "generating symbol list for \`$libname.la'"
export_symbols="$output_objdir/$libname.exp"
$run $rm $export_symbols
cmds=$export_symbols_cmds
save_ifs="$IFS"; IFS='~'
for cmd in $cmds; do
IFS="$save_ifs"
eval cmd=\"$cmd\"
if len=`expr "X$cmd" : ".*"` &&
test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
$show "$cmd"
$run eval "$cmd" || exit $?
skipped_export=false
else
# The command line is too long to execute in one step.
$show "using reloadable object file for export list..."
skipped_export=:
# Break out early, otherwise skipped_export may be
# set to false by a later but shorter cmd.
break
fi
done
IFS="$save_ifs"
if test -n "$export_symbols_regex"; then
$show "$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\""
$run eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
$show "$mv \"${export_symbols}T\" \"$export_symbols\""
$run eval '$mv "${export_symbols}T" "$export_symbols"'
fi
fi
fi
if test -n "$export_symbols" && test -n "$include_expsyms"; then
$run eval '$echo "X$include_expsyms" | $SP2NL >> "$export_symbols"'
fi
tmp_deplibs=
for test_deplib in $deplibs; do
case " $convenience " in
*" $test_deplib "*) ;;
*)
tmp_deplibs="$tmp_deplibs $test_deplib"
;;
esac
done
deplibs="$tmp_deplibs"
if test -n "$convenience"; then
if test -n "$whole_archive_flag_spec"; then
save_libobjs=$libobjs
eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
else
gentop="$output_objdir/${outputname}x"
generated="$generated $gentop"
func_extract_archives $gentop $convenience
libobjs="$libobjs $func_extract_archives_result"
fi
fi
if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then
eval flag=\"$thread_safe_flag_spec\"
linker_flags="$linker_flags $flag"
fi
# Make a backup of the uninstalled library when relinking
if test "$mode" = relink; then
$run eval '(cd $output_objdir && $rm ${realname}U && $mv $realname ${realname}U)' || exit $?
fi
# Do each of the archive commands.
if test "$module" = yes && test -n "$module_cmds" ; then
if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
eval test_cmds=\"$module_expsym_cmds\"
cmds=$module_expsym_cmds
else
eval test_cmds=\"$module_cmds\"
cmds=$module_cmds
fi
else
if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
eval test_cmds=\"$archive_expsym_cmds\"
cmds=$archive_expsym_cmds
else
eval test_cmds=\"$archive_cmds\"
cmds=$archive_cmds
fi
fi
if test "X$skipped_export" != "X:" &&
len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
:
else
# The command line is too long to link in one step, link piecewise.
$echo "creating reloadable object files..."
# Save the value of $output and $libobjs because we want to
# use them later. If we have whole_archive_flag_spec, we
# want to use save_libobjs as it was before
# whole_archive_flag_spec was expanded, because we can't
# assume the linker understands whole_archive_flag_spec.
# This may have to be revisited, in case too many
# convenience libraries get linked in and end up exceeding
# the spec.
if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then
save_libobjs=$libobjs
fi
save_output=$output
output_la=`$echo "X$output" | $Xsed -e "$basename"`
# Clear the reloadable object creation command queue and
# initialize k to one.
test_cmds=
concat_cmds=
objlist=
delfiles=
last_robj=
k=1
output=$output_objdir/$output_la-${k}.$objext
# Loop over the list of objects to be linked.
for obj in $save_libobjs
do
eval test_cmds=\"$reload_cmds $objlist $last_robj\"
if test "X$objlist" = X ||
{ len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
test "$len" -le "$max_cmd_len"; }; then
objlist="$objlist $obj"
else
# The command $test_cmds is almost too long, add a
# command to the queue.
if test "$k" -eq 1 ; then
# The first file doesn't have a previous command to add.
eval concat_cmds=\"$reload_cmds $objlist $last_robj\"
else
# All subsequent reloadable object files will link in
# the last one created.
eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj\"
fi
last_robj=$output_objdir/$output_la-${k}.$objext
k=`expr $k + 1`
output=$output_objdir/$output_la-${k}.$objext
objlist=$obj
len=1
fi
done
# Handle the remaining objects by creating one last
# reloadable object file. All subsequent reloadable object
# files will link in the last one created.
test -z "$concat_cmds" || concat_cmds=$concat_cmds~
eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\"
if ${skipped_export-false}; then
$show "generating symbol list for \`$libname.la'"
export_symbols="$output_objdir/$libname.exp"
$run $rm $export_symbols
libobjs=$output
# Append the command to create the export file.
eval concat_cmds=\"\$concat_cmds~$export_symbols_cmds\"
fi
# Set up a command to remove the reloadable object files
# after they are used.
i=0
while test "$i" -lt "$k"
do
i=`expr $i + 1`
delfiles="$delfiles $output_objdir/$output_la-${i}.$objext"
done
$echo "creating a temporary reloadable object file: $output"
# Loop through the commands generated above and execute them.
save_ifs="$IFS"; IFS='~'
for cmd in $concat_cmds; do
IFS="$save_ifs"
$show "$cmd"
$run eval "$cmd" || exit $?
done
IFS="$save_ifs"
libobjs=$output
# Restore the value of output.
output=$save_output
if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then
eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
fi
# Expand the library linking commands again to reset the
# value of $libobjs for piecewise linking.
# Do each of the archive commands.
if test "$module" = yes && test -n "$module_cmds" ; then
if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
cmds=$module_expsym_cmds
else
cmds=$module_cmds
fi
else
if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
cmds=$archive_expsym_cmds
else
cmds=$archive_cmds
fi
fi
# Append the command to remove the reloadable object files
# to the just-reset $cmds.
eval cmds=\"\$cmds~\$rm $delfiles\"
fi
save_ifs="$IFS"; IFS='~'
for cmd in $cmds; do
IFS="$save_ifs"
eval cmd=\"$cmd\"
$show "$cmd"
$run eval "$cmd" || {
lt_exit=$?
# Restore the uninstalled library and exit
if test "$mode" = relink; then
$run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname}U $realname)'
fi
exit $lt_exit
}
done
IFS="$save_ifs"
# Restore the uninstalled library and exit
if test "$mode" = relink; then
$run eval '(cd $output_objdir && $rm ${realname}T && $mv $realname ${realname}T && $mv "$realname"U $realname)' || exit $?
if test -n "$convenience"; then
if test -z "$whole_archive_flag_spec"; then
$show "${rm}r $gentop"
$run ${rm}r "$gentop"
fi
fi
exit $EXIT_SUCCESS
fi
# Create links to the real library.
for linkname in $linknames; do
if test "$realname" != "$linkname"; then
$show "(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)"
$run eval '(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)' || exit $?
fi
done
# If -module or -export-dynamic was specified, set the dlname.
if test "$module" = yes || test "$export_dynamic" = yes; then
# On all known operating systems, these are identical.
dlname="$soname"
fi
fi
;;
obj)
if test -n "$deplibs"; then
$echo "$modename: warning: \`-l' and \`-L' are ignored for objects" 1>&2
fi
if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
$echo "$modename: warning: \`-dlopen' is ignored for objects" 1>&2
fi
if test -n "$rpath"; then
$echo "$modename: warning: \`-rpath' is ignored for objects" 1>&2
fi
if test -n "$xrpath"; then
$echo "$modename: warning: \`-R' is ignored for objects" 1>&2
fi
if test -n "$vinfo"; then
$echo "$modename: warning: \`-version-info' is ignored for objects" 1>&2
fi
if test -n "$release"; then
$echo "$modename: warning: \`-release' is ignored for objects" 1>&2
fi
case $output in
*.lo)
if test -n "$objs$old_deplibs"; then
$echo "$modename: cannot build library object \`$output' from non-libtool objects" 1>&2
exit $EXIT_FAILURE
fi
libobj="$output"
obj=`$echo "X$output" | $Xsed -e "$lo2o"`
;;
*)
libobj=
obj="$output"
;;
esac
# Delete the old objects.
$run $rm $obj $libobj
# Objects from convenience libraries. This assumes
# single-version convenience libraries. Whenever we create
# different ones for PIC/non-PIC, this we'll have to duplicate
# the extraction.
reload_conv_objs=
gentop=
# reload_cmds runs $LD directly, so let us get rid of
# -Wl from whole_archive_flag_spec and hope we can get by with
# turning comma into space..
wl=
if test -n "$convenience"; then
if test -n "$whole_archive_flag_spec"; then
eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\"
reload_conv_objs=$reload_objs\ `$echo "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'`
else
gentop="$output_objdir/${obj}x"
generated="$generated $gentop"
func_extract_archives $gentop $convenience
reload_conv_objs="$reload_objs $func_extract_archives_result"
fi
fi
# Create the old-style object.
reload_objs="$objs$old_deplibs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
output="$obj"
cmds=$reload_cmds
save_ifs="$IFS"; IFS='~'
for cmd in $cmds; do
IFS="$save_ifs"
eval cmd=\"$cmd\"
$show "$cmd"
$run eval "$cmd" || exit $?
done
IFS="$save_ifs"
# Exit if we aren't doing a library object file.
if test -z "$libobj"; then
if test -n "$gentop"; then
$show "${rm}r $gentop"
$run ${rm}r $gentop
fi
exit $EXIT_SUCCESS
fi
if test "$build_libtool_libs" != yes; then
if test -n "$gentop"; then
$show "${rm}r $gentop"
$run ${rm}r $gentop
fi
# Create an invalid libtool object if no PIC, so that we don't
# accidentally link it into a program.
# $show "echo timestamp > $libobj"
# $run eval "echo timestamp > $libobj" || exit $?
exit $EXIT_SUCCESS
fi
if test -n "$pic_flag" || test "$pic_mode" != default; then
# Only do commands if we really have different PIC objects.
reload_objs="$libobjs $reload_conv_objs"
output="$libobj"
cmds=$reload_cmds
save_ifs="$IFS"; IFS='~'
for cmd in $cmds; do
IFS="$save_ifs"
eval cmd=\"$cmd\"
$show "$cmd"
$run eval "$cmd" || exit $?
done
IFS="$save_ifs"
fi
if test -n "$gentop"; then
$show "${rm}r $gentop"
$run ${rm}r $gentop
fi
exit $EXIT_SUCCESS
;;
prog)
case $host in
*cygwin*) output=`$echo $output | ${SED} -e 's,.exe$,,;s,$,.exe,'` ;;
esac
if test -n "$vinfo"; then
$echo "$modename: warning: \`-version-info' is ignored for programs" 1>&2
fi
if test -n "$release"; then
$echo "$modename: warning: \`-release' is ignored for programs" 1>&2
fi
if test "$preload" = yes; then
if test "$dlopen_support" = unknown && test "$dlopen_self" = unknown &&
test "$dlopen_self_static" = unknown; then
$echo "$modename: warning: \`AC_LIBTOOL_DLOPEN' not used. Assuming no dlopen support."
fi
fi
case $host in
*-*-rhapsody* | *-*-darwin1.[012])
# On Rhapsody replace the C library is the System framework
compile_deplibs=`$echo "X $compile_deplibs" | $Xsed -e 's/ -lc / -framework System /'`
finalize_deplibs=`$echo "X $finalize_deplibs" | $Xsed -e 's/ -lc / -framework System /'`
;;
esac
case $host in
*darwin*)
# Don't allow lazy linking, it breaks C++ global constructors
if test "$tagname" = CXX ; then
compile_command="$compile_command ${wl}-bind_at_load"
finalize_command="$finalize_command ${wl}-bind_at_load"
fi
;;
esac
# move library search paths that coincide with paths to not yet
# installed libraries to the beginning of the library search list
new_libs=
for path in $notinst_path; do
case " $new_libs " in
*" -L$path/$objdir "*) ;;
*)
case " $compile_deplibs " in
*" -L$path/$objdir "*)
new_libs="$new_libs -L$path/$objdir" ;;
esac
;;
esac
done
for deplib in $compile_deplibs; do
case $deplib in
-L*)
case " $new_libs " in
*" $deplib "*) ;;
*) new_libs="$new_libs $deplib" ;;
esac
;;
*) new_libs="$new_libs $deplib" ;;
esac
done
compile_deplibs="$new_libs"
compile_command="$compile_command $compile_deplibs"
finalize_command="$finalize_command $finalize_deplibs"
if test -n "$rpath$xrpath"; then
# If the user specified any rpath flags, then add them.
for libdir in $rpath $xrpath; do
# This is the magic to use -rpath.
case "$finalize_rpath " in
*" $libdir "*) ;;
*) finalize_rpath="$finalize_rpath $libdir" ;;
esac
done
fi
# Now hardcode the library paths
rpath=
hardcode_libdirs=
for libdir in $compile_rpath $finalize_rpath; do
if test -n "$hardcode_libdir_flag_spec"; then
if test -n "$hardcode_libdir_separator"; then
if test -z "$hardcode_libdirs"; then
hardcode_libdirs="$libdir"
else
# Just accumulate the unique libdirs.
case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
*"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
;;
*)
hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
;;
esac
fi
else
eval flag=\"$hardcode_libdir_flag_spec\"
rpath="$rpath $flag"
fi
elif test -n "$runpath_var"; then
case "$perm_rpath " in
*" $libdir "*) ;;
*) perm_rpath="$perm_rpath $libdir" ;;
esac
fi
case $host in
*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
testbindir=`$echo "X$libdir" | $Xsed -e 's*/lib$*/bin*'`
case :$dllsearchpath: in
*":$libdir:"*) ;;
*) dllsearchpath="$dllsearchpath:$libdir";;
esac
case :$dllsearchpath: in
*":$testbindir:"*) ;;
*) dllsearchpath="$dllsearchpath:$testbindir";;
esac
;;
esac
done
# Substitute the hardcoded libdirs into the rpath.
if test -n "$hardcode_libdir_separator" &&
test -n "$hardcode_libdirs"; then
libdir="$hardcode_libdirs"
eval rpath=\" $hardcode_libdir_flag_spec\"
fi
compile_rpath="$rpath"
rpath=
hardcode_libdirs=
for libdir in $finalize_rpath; do
if test -n "$hardcode_libdir_flag_spec"; then
if test -n "$hardcode_libdir_separator"; then
if test -z "$hardcode_libdirs"; then
hardcode_libdirs="$libdir"
else
# Just accumulate the unique libdirs.
case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
*"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
;;
*)
hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
;;
esac
fi
else
eval flag=\"$hardcode_libdir_flag_spec\"
rpath="$rpath $flag"
fi
elif test -n "$runpath_var"; then
case "$finalize_perm_rpath " in
*" $libdir "*) ;;
*) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;;
esac
fi
done
# Substitute the hardcoded libdirs into the rpath.
if test -n "$hardcode_libdir_separator" &&
test -n "$hardcode_libdirs"; then
libdir="$hardcode_libdirs"
eval rpath=\" $hardcode_libdir_flag_spec\"
fi
finalize_rpath="$rpath"
if test -n "$libobjs" && test "$build_old_libs" = yes; then
# Transform all the library objects into standard objects.
compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
fi
dlsyms=
if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
if test -n "$NM" && test -n "$global_symbol_pipe"; then
dlsyms="${outputname}S.c"
else
$echo "$modename: not configured to extract global symbols from dlpreopened files" 1>&2
fi
fi
if test -n "$dlsyms"; then
case $dlsyms in
"") ;;
*.c)
# Discover the nlist of each of the dlfiles.
nlist="$output_objdir/${outputname}.nm"
$show "$rm $nlist ${nlist}S ${nlist}T"
$run $rm "$nlist" "${nlist}S" "${nlist}T"
# Parse the name list into a source file.
$show "creating $output_objdir/$dlsyms"
test -z "$run" && $echo > "$output_objdir/$dlsyms" "\
/* $dlsyms - symbol resolution table for \`$outputname' dlsym emulation. */
/* Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP */
#ifdef __cplusplus
extern \"C\" {
#endif
/* Prevent the only kind of declaration conflicts we can make. */
#define lt_preloaded_symbols some_other_symbol
/* External symbol declarations for the compiler. */\
"
if test "$dlself" = yes; then
$show "generating symbol list for \`$output'"
test -z "$run" && $echo ': @PROGRAM@ ' > "$nlist"
# Add our own program objects to the symbol list.
progfiles=`$echo "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
for arg in $progfiles; do
$show "extracting global C symbols from \`$arg'"
$run eval "$NM $arg | $global_symbol_pipe >> '$nlist'"
done
if test -n "$exclude_expsyms"; then
$run eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T'
$run eval '$mv "$nlist"T "$nlist"'
fi
if test -n "$export_symbols_regex"; then
$run eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T'
$run eval '$mv "$nlist"T "$nlist"'
fi
# Prepare the list of exported symbols
if test -z "$export_symbols"; then
export_symbols="$output_objdir/$outputname.exp"
$run $rm $export_symbols
$run eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
case $host in
*cygwin* | *mingw* )
$run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
$run eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"'
;;
esac
else
$run eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"'
$run eval 'grep -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T'
$run eval 'mv "$nlist"T "$nlist"'
case $host in
*cygwin* | *mingw* )
$run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
$run eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
;;
esac
fi
fi
for arg in $dlprefiles; do
$show "extracting global C symbols from \`$arg'"
name=`$echo "$arg" | ${SED} -e 's%^.*/%%'`
$run eval '$echo ": $name " >> "$nlist"'
$run eval "$NM $arg | $global_symbol_pipe >> '$nlist'"
done
if test -z "$run"; then
# Make sure we have at least an empty file.
test -f "$nlist" || : > "$nlist"
if test -n "$exclude_expsyms"; then
$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T
$mv "$nlist"T "$nlist"
fi
# Try sorting and uniquifying the output.
if grep -v "^: " < "$nlist" |
if sort -k 3 </dev/null >/dev/null 2>&1; then
sort -k 3
else
sort +2
fi |
uniq > "$nlist"S; then
:
else
grep -v "^: " < "$nlist" > "$nlist"S
fi
if test -f "$nlist"S; then
eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$dlsyms"'
else
$echo '/* NONE */' >> "$output_objdir/$dlsyms"
fi
$echo >> "$output_objdir/$dlsyms" "\
#undef lt_preloaded_symbols
#if defined (__STDC__) && __STDC__
# define lt_ptr void *
#else
# define lt_ptr char *
# define const
#endif
/* The mapping between symbol names and symbols. */
"
case $host in
*cygwin* | *mingw* )
$echo >> "$output_objdir/$dlsyms" "\
/* DATA imports from DLLs on WIN32 can't be const, because
runtime relocations are performed -- see ld's documentation
on pseudo-relocs */
struct {
"
;;
* )
$echo >> "$output_objdir/$dlsyms" "\
const struct {
"
;;
esac
$echo >> "$output_objdir/$dlsyms" "\
const char *name;
lt_ptr address;
}
lt_preloaded_symbols[] =
{\
"
eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$dlsyms"
$echo >> "$output_objdir/$dlsyms" "\
{0, (lt_ptr) 0}
};
/* This works around a problem in FreeBSD linker */
#ifdef FREEBSD_WORKAROUND
static const void *lt_preloaded_setup() {
return lt_preloaded_symbols;
}
#endif
#ifdef __cplusplus
}
#endif\
"
fi
pic_flag_for_symtable=
case $host in
# compiling the symbol table file with pic_flag works around
# a FreeBSD bug that causes programs to crash when -lm is
# linked before any other PIC object. But we must not use
# pic_flag when linking with -static. The problem exists in
# FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.
*-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
case "$compile_command " in
*" -static "*) ;;
*) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND";;
esac;;
*-*-hpux*)
case "$compile_command " in
*" -static "*) ;;
*) pic_flag_for_symtable=" $pic_flag";;
esac
esac
# Now compile the dynamic symbol file.
$show "(cd $output_objdir && $LTCC $LTCFLAGS -c$no_builtin_flag$pic_flag_for_symtable \"$dlsyms\")"
$run eval '(cd $output_objdir && $LTCC $LTCFLAGS -c$no_builtin_flag$pic_flag_for_symtable "$dlsyms")' || exit $?
# Clean up the generated files.
$show "$rm $output_objdir/$dlsyms $nlist ${nlist}S ${nlist}T"
$run $rm "$output_objdir/$dlsyms" "$nlist" "${nlist}S" "${nlist}T"
# Transform the symbol file into the correct name.
case $host in
*cygwin* | *mingw* )
if test -f "$output_objdir/${outputname}.def" ; then
compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%" | $NL2SP`
finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%" | $NL2SP`
else
compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP`
finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP`
fi
;;
* )
compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP`
finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP`
;;
esac
;;
*)
$echo "$modename: unknown suffix for \`$dlsyms'" 1>&2
exit $EXIT_FAILURE
;;
esac
else
# We keep going just in case the user didn't refer to
# lt_preloaded_symbols. The linker will fail if global_symbol_pipe
# really was required.
# Nullify the symbol file.
compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s% @SYMFILE@%%" | $NL2SP`
finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s% @SYMFILE@%%" | $NL2SP`
fi
if test "$need_relink" = no || test "$build_libtool_libs" != yes; then
# Replace the output file specification.
compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e 's%@OUTPUT@%'"$output"'%g' | $NL2SP`
link_command="$compile_command$compile_rpath"
# We have no uninstalled library dependencies, so finalize right now.
$show "$link_command"
$run eval "$link_command"
exit_status=$?
# Delete the generated files.
if test -n "$dlsyms"; then
$show "$rm $output_objdir/${outputname}S.${objext}"
$run $rm "$output_objdir/${outputname}S.${objext}"
fi
exit $exit_status
fi
if test -n "$shlibpath_var"; then
# We should set the shlibpath_var
rpath=
for dir in $temp_rpath; do
case $dir in
[\\/]* | [A-Za-z]:[\\/]*)
# Absolute path.
rpath="$rpath$dir:"
;;
*)
# Relative path: add a thisdir entry.
rpath="$rpath\$thisdir/$dir:"
;;
esac
done
temp_rpath="$rpath"
fi
if test -n "$compile_shlibpath$finalize_shlibpath"; then
compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command"
fi
if test -n "$finalize_shlibpath"; then
finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command"
fi
compile_var=
finalize_var=
if test -n "$runpath_var"; then
if test -n "$perm_rpath"; then
# We should set the runpath_var.
rpath=
for dir in $perm_rpath; do
rpath="$rpath$dir:"
done
compile_var="$runpath_var=\"$rpath\$$runpath_var\" "
fi
if test -n "$finalize_perm_rpath"; then
# We should set the runpath_var.
rpath=
for dir in $finalize_perm_rpath; do
rpath="$rpath$dir:"
done
finalize_var="$runpath_var=\"$rpath\$$runpath_var\" "
fi
fi
if test "$no_install" = yes; then
# We don't need to create a wrapper script.
link_command="$compile_var$compile_command$compile_rpath"
# Replace the output file specification.
link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'`
# Delete the old output file.
$run $rm $output
# Link the executable and exit
$show "$link_command"
$run eval "$link_command" || exit $?
exit $EXIT_SUCCESS
fi
if test "$hardcode_action" = relink; then
# Fast installation is not supported
link_command="$compile_var$compile_command$compile_rpath"
relink_command="$finalize_var$finalize_command$finalize_rpath"
$echo "$modename: warning: this platform does not like uninstalled shared libraries" 1>&2
$echo "$modename: \`$output' will be relinked during installation" 1>&2
else
if test "$fast_install" != no; then
link_command="$finalize_var$compile_command$finalize_rpath"
if test "$fast_install" = yes; then
relink_command=`$echo "X$compile_var$compile_command$compile_rpath" | $SP2NL | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g' | $NL2SP`
else
# fast_install is set to needless
relink_command=
fi
else
link_command="$compile_var$compile_command$compile_rpath"
relink_command="$finalize_var$finalize_command$finalize_rpath"
fi
fi
# Replace the output file specification.
link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`
# Delete the old output files.
$run $rm $output $output_objdir/$outputname $output_objdir/lt-$outputname
$show "$link_command"
$run eval "$link_command" || exit $?
# Now create the wrapper script.
$show "creating $output"
# Quote the relink command for shipping.
if test -n "$relink_command"; then
# Preserve any variables that may affect compiler behavior
for var in $variables_saved_for_relink; do
if eval test -z \"\${$var+set}\"; then
relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command"
elif eval var_value=\$$var; test -z "$var_value"; then
relink_command="$var=; export $var; $relink_command"
else
var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"`
relink_command="$var=\"$var_value\"; export $var; $relink_command"
fi
done
relink_command="(cd `pwd`; $relink_command)"
relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e "$sed_quote_subst" | $NL2SP`
fi
# Quote $echo for shipping.
if test "X$echo" = "X$SHELL $progpath --fallback-echo"; then
case $progpath in
[\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";;
*) qecho="$SHELL `pwd`/$progpath --fallback-echo";;
esac
qecho=`$echo "X$qecho" | $Xsed -e "$sed_quote_subst"`
else
qecho=`$echo "X$echo" | $Xsed -e "$sed_quote_subst"`
fi
# Only actually do things if our run command is non-null.
if test -z "$run"; then
# win32 will think the script is a binary if it has
# a .exe suffix, so we strip it off here.
case $output in
*.exe) output=`$echo $output|${SED} 's,.exe$,,'` ;;
esac
# test for cygwin because mv fails w/o .exe extensions
case $host in
*cygwin*)
exeext=.exe
outputname=`$echo $outputname|${SED} 's,.exe$,,'` ;;
*) exeext= ;;
esac
case $host in
*cygwin* | *mingw* )
output_name=`basename $output`
output_path=`dirname $output`
cwrappersource="$output_path/$objdir/lt-$output_name.c"
cwrapper="$output_path/$output_name.exe"
$rm $cwrappersource $cwrapper
trap "$rm $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15
cat > $cwrappersource <<EOF
/* $cwrappersource - temporary wrapper executable for $objdir/$outputname
Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
The $output program cannot be directly executed until all the libtool
libraries that it depends on are installed.
This wrapper executable should never be moved out of the build directory.
If it is, it will not operate correctly.
Currently, it simply execs the wrapper *script* "/bin/sh $output",
but could eventually absorb all of the scripts functionality and
exec $objdir/$outputname directly.
*/
EOF
cat >> $cwrappersource<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <malloc.h>
#include <stdarg.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#if defined(PATH_MAX)
# define LT_PATHMAX PATH_MAX
#elif defined(MAXPATHLEN)
# define LT_PATHMAX MAXPATHLEN
#else
# define LT_PATHMAX 1024
#endif
#ifndef DIR_SEPARATOR
# define DIR_SEPARATOR '/'
# define PATH_SEPARATOR ':'
#endif
#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \
defined (__OS2__)
# define HAVE_DOS_BASED_FILE_SYSTEM
# ifndef DIR_SEPARATOR_2
# define DIR_SEPARATOR_2 '\\'
# endif
# ifndef PATH_SEPARATOR_2
# define PATH_SEPARATOR_2 ';'
# endif
#endif
#ifndef DIR_SEPARATOR_2
# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
#else /* DIR_SEPARATOR_2 */
# define IS_DIR_SEPARATOR(ch) \
(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
#endif /* DIR_SEPARATOR_2 */
#ifndef PATH_SEPARATOR_2
# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)
#else /* PATH_SEPARATOR_2 */
# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)
#endif /* PATH_SEPARATOR_2 */
#define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type)))
#define XFREE(stale) do { \
if (stale) { free ((void *) stale); stale = 0; } \
} while (0)
/* -DDEBUG is fairly common in CFLAGS. */
#undef DEBUG
#if defined DEBUGWRAPPER
# define DEBUG(format, ...) fprintf(stderr, format, __VA_ARGS__)
#else
# define DEBUG(format, ...)
#endif
const char *program_name = NULL;
void * xmalloc (size_t num);
char * xstrdup (const char *string);
const char * base_name (const char *name);
char * find_executable(const char *wrapper);
int check_executable(const char *path);
char * strendzap(char *str, const char *pat);
void lt_fatal (const char *message, ...);
int
main (int argc, char *argv[])
{
char **newargz;
int i;
program_name = (char *) xstrdup (base_name (argv[0]));
DEBUG("(main) argv[0] : %s\n",argv[0]);
DEBUG("(main) program_name : %s\n",program_name);
newargz = XMALLOC(char *, argc+2);
EOF
cat >> $cwrappersource <<EOF
newargz[0] = (char *) xstrdup("$SHELL");
EOF
cat >> $cwrappersource <<"EOF"
newargz[1] = find_executable(argv[0]);
if (newargz[1] == NULL)
lt_fatal("Couldn't find %s", argv[0]);
DEBUG("(main) found exe at : %s\n",newargz[1]);
/* we know the script has the same name, without the .exe */
/* so make sure newargz[1] doesn't end in .exe */
strendzap(newargz[1],".exe");
for (i = 1; i < argc; i++)
newargz[i+1] = xstrdup(argv[i]);
newargz[argc+1] = NULL;
for (i=0; i<argc+1; i++)
{
DEBUG("(main) newargz[%d] : %s\n",i,newargz[i]);
;
}
EOF
case $host_os in
mingw*)
cat >> $cwrappersource <<EOF
execv("$SHELL",(char const **)newargz);
EOF
;;
*)
cat >> $cwrappersource <<EOF
execv("$SHELL",newargz);
EOF
;;
esac
cat >> $cwrappersource <<"EOF"
return 127;
}
void *
xmalloc (size_t num)
{
void * p = (void *) malloc (num);
if (!p)
lt_fatal ("Memory exhausted");
return p;
}
char *
xstrdup (const char *string)
{
return string ? strcpy ((char *) xmalloc (strlen (string) + 1), string) : NULL
;
}
const char *
base_name (const char *name)
{
const char *base;
#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
/* Skip over the disk name in MSDOS pathnames. */
if (isalpha ((unsigned char)name[0]) && name[1] == ':')
name += 2;
#endif
for (base = name; *name; name++)
if (IS_DIR_SEPARATOR (*name))
base = name + 1;
return base;
}
int
check_executable(const char * path)
{
struct stat st;
DEBUG("(check_executable) : %s\n", path ? (*path ? path : "EMPTY!") : "NULL!");
if ((!path) || (!*path))
return 0;
if ((stat (path, &st) >= 0) &&
(
/* MinGW & native WIN32 do not support S_IXOTH or S_IXGRP */
#if defined (S_IXOTH)
((st.st_mode & S_IXOTH) == S_IXOTH) ||
#endif
#if defined (S_IXGRP)
((st.st_mode & S_IXGRP) == S_IXGRP) ||
#endif
((st.st_mode & S_IXUSR) == S_IXUSR))
)
return 1;
else
return 0;
}
/* Searches for the full path of the wrapper. Returns
newly allocated full path name if found, NULL otherwise */
char *
find_executable (const char* wrapper)
{
int has_slash = 0;
const char* p;
const char* p_next;
/* static buffer for getcwd */
char tmp[LT_PATHMAX + 1];
int tmp_len;
char* concat_name;
DEBUG("(find_executable) : %s\n", wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!");
if ((wrapper == NULL) || (*wrapper == '\0'))
return NULL;
/* Absolute path? */
#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
if (isalpha ((unsigned char)wrapper[0]) && wrapper[1] == ':')
{
concat_name = xstrdup (wrapper);
if (check_executable(concat_name))
return concat_name;
XFREE(concat_name);
}
else
{
#endif
if (IS_DIR_SEPARATOR (wrapper[0]))
{
concat_name = xstrdup (wrapper);
if (check_executable(concat_name))
return concat_name;
XFREE(concat_name);
}
#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
}
#endif
for (p = wrapper; *p; p++)
if (*p == '/')
{
has_slash = 1;
break;
}
if (!has_slash)
{
/* no slashes; search PATH */
const char* path = getenv ("PATH");
if (path != NULL)
{
for (p = path; *p; p = p_next)
{
const char* q;
size_t p_len;
for (q = p; *q; q++)
if (IS_PATH_SEPARATOR(*q))
break;
p_len = q - p;
p_next = (*q == '\0' ? q : q + 1);
if (p_len == 0)
{
/* empty path: current directory */
if (getcwd (tmp, LT_PATHMAX) == NULL)
lt_fatal ("getcwd failed");
tmp_len = strlen(tmp);
concat_name = XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1);
memcpy (concat_name, tmp, tmp_len);
concat_name[tmp_len] = '/';
strcpy (concat_name + tmp_len + 1, wrapper);
}
else
{
concat_name = XMALLOC(char, p_len + 1 + strlen(wrapper) + 1);
memcpy (concat_name, p, p_len);
concat_name[p_len] = '/';
strcpy (concat_name + p_len + 1, wrapper);
}
if (check_executable(concat_name))
return concat_name;
XFREE(concat_name);
}
}
/* not found in PATH; assume curdir */
}
/* Relative path | not found in path: prepend cwd */
if (getcwd (tmp, LT_PATHMAX) == NULL)
lt_fatal ("getcwd failed");
tmp_len = strlen(tmp);
concat_name = XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1);
memcpy (concat_name, tmp, tmp_len);
concat_name[tmp_len] = '/';
strcpy (concat_name + tmp_len + 1, wrapper);
if (check_executable(concat_name))
return concat_name;
XFREE(concat_name);
return NULL;
}
char *
strendzap(char *str, const char *pat)
{
size_t len, patlen;
assert(str != NULL);
assert(pat != NULL);
len = strlen(str);
patlen = strlen(pat);
if (patlen <= len)
{
str += len - patlen;
if (strcmp(str, pat) == 0)
*str = '\0';
}
return str;
}
static void
lt_error_core (int exit_status, const char * mode,
const char * message, va_list ap)
{
fprintf (stderr, "%s: %s: ", program_name, mode);
vfprintf (stderr, message, ap);
fprintf (stderr, ".\n");
if (exit_status >= 0)
exit (exit_status);
}
void
lt_fatal (const char *message, ...)
{
va_list ap;
va_start (ap, message);
lt_error_core (EXIT_FAILURE, "FATAL", message, ap);
va_end (ap);
}
EOF
# we should really use a build-platform specific compiler
# here, but OTOH, the wrappers (shell script and this C one)
# are only useful if you want to execute the "real" binary.
# Since the "real" binary is built for $host, then this
# wrapper might as well be built for $host, too.
$run $LTCC $LTCFLAGS -s -o $cwrapper $cwrappersource
;;
esac
$rm $output
trap "$rm $output; exit $EXIT_FAILURE" 1 2 15
$echo > $output "\
#! $SHELL
# $output - temporary wrapper script for $objdir/$outputname
# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
#
# The $output program cannot be directly executed until all the libtool
# libraries that it depends on are installed.
#
# This wrapper script should never be moved out of the build directory.
# If it is, it will not operate correctly.
# Sed substitution that helps us do robust quoting. It backslashifies
# metacharacters that are still active within double-quoted strings.
Xsed='${SED} -e 1s/^X//'
sed_quote_subst='$sed_quote_subst'
# Be Bourne compatible (taken from Autoconf:_AS_BOURNE_COMPATIBLE).
if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
emulate sh
NULLCMD=:
# Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
# is contrary to our usage. Disable this feature.
alias -g '\${1+\"\$@\"}'='\"\$@\"'
setopt NO_GLOB_SUBST
else
case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
fi
# The HP-UX ksh and POSIX shell print the target directory to stdout
# if CDPATH is set.
(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
relink_command=\"$relink_command\"
# This environment variable determines our operation mode.
if test \"\$libtool_install_magic\" = \"$magic\"; then
# install mode needs the following variable:
notinst_deplibs='$notinst_deplibs'
else
# When we are sourced in execute mode, \$file and \$echo are already set.
if test \"\$libtool_execute_magic\" != \"$magic\"; then
echo=\"$qecho\"
file=\"\$0\"
# Make sure echo works.
if test \"X\$1\" = X--no-reexec; then
# Discard the --no-reexec flag, and continue.
shift
elif test \"X\`(\$echo '\t') 2>/dev/null\`\" = 'X\t'; then
# Yippee, \$echo works!
:
else
# Restart under the correct shell, and then maybe \$echo will work.
exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"}
fi
fi\
"
$echo >> $output "\
# Find the directory that this script lives in.
thisdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\`
test \"x\$thisdir\" = \"x\$file\" && thisdir=.
# Follow symbolic links until we get to the real thisdir.
file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\`
while test -n \"\$file\"; do
destdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\`
# If there was a directory component, then change thisdir.
if test \"x\$destdir\" != \"x\$file\"; then
case \"\$destdir\" in
[\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
*) thisdir=\"\$thisdir/\$destdir\" ;;
esac
fi
file=\`\$echo \"X\$file\" | \$Xsed -e 's%^.*/%%'\`
file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\`
done
# Try to get the absolute directory name.
absdir=\`cd \"\$thisdir\" && pwd\`
test -n \"\$absdir\" && thisdir=\"\$absdir\"
"
if test "$fast_install" = yes; then
$echo >> $output "\
program=lt-'$outputname'$exeext
progdir=\"\$thisdir/$objdir\"
if test ! -f \"\$progdir/\$program\" || \\
{ file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
test \"X\$file\" != \"X\$progdir/\$program\"; }; then
file=\"\$\$-\$program\"
if test ! -d \"\$progdir\"; then
$mkdir \"\$progdir\"
else
$rm \"\$progdir/\$file\"
fi"
$echo >> $output "\
# relink executable if necessary
if test -n \"\$relink_command\"; then
if relink_command_output=\`eval \$relink_command 2>&1\`; then :
else
$echo \"\$relink_command_output\" >&2
$rm \"\$progdir/\$file\"
exit $EXIT_FAILURE
fi
fi
$mv \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
{ $rm \"\$progdir/\$program\";
$mv \"\$progdir/\$file\" \"\$progdir/\$program\"; }
$rm \"\$progdir/\$file\"
fi"
else
$echo >> $output "\
program='$outputname'
progdir=\"\$thisdir/$objdir\"
"
fi
$echo >> $output "\
if test -f \"\$progdir/\$program\"; then"
# Export our shlibpath_var if we have one.
if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
$echo >> $output "\
# Add our own library path to $shlibpath_var
$shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
# Some systems cannot cope with colon-terminated $shlibpath_var
# The second colon is a workaround for a bug in BeOS R4 sed
$shlibpath_var=\`\$echo \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\`
export $shlibpath_var
"
fi
# fixup the dll searchpath if we need to.
if test -n "$dllsearchpath"; then
$echo >> $output "\
# Add the dll search path components to the executable PATH
PATH=$dllsearchpath:\$PATH
"
fi
$echo >> $output "\
if test \"\$libtool_execute_magic\" != \"$magic\"; then
# Run the actual program with our arguments.
"
case $host in
# Backslashes separate directories on plain windows
*-*-mingw | *-*-os2*)
$echo >> $output "\
exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
"
;;
*)
$echo >> $output "\
exec \"\$progdir/\$program\" \${1+\"\$@\"}
"
;;
esac
$echo >> $output "\
\$echo \"\$0: cannot exec \$program \$*\"
exit $EXIT_FAILURE
fi
else
# The program doesn't exist.
\$echo \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
\$echo \"This script is just a wrapper for \$program.\" 1>&2
$echo \"See the $PACKAGE documentation for more information.\" 1>&2
exit $EXIT_FAILURE
fi
fi\
"
chmod +x $output
fi
exit $EXIT_SUCCESS
;;
esac
# See if we need to build an old-fashioned archive.
for oldlib in $oldlibs; do
if test "$build_libtool_libs" = convenience; then
oldobjs="$libobjs_save"
addlibs="$convenience"
build_libtool_libs=no
else
if test "$build_libtool_libs" = module; then
oldobjs="$libobjs_save"
build_libtool_libs=no
else
oldobjs="$old_deplibs $non_pic_objects"
fi
addlibs="$old_convenience"
fi
if test -n "$addlibs"; then
gentop="$output_objdir/${outputname}x"
generated="$generated $gentop"
func_extract_archives $gentop $addlibs
oldobjs="$oldobjs $func_extract_archives_result"
fi
# Do each command in the archive commands.
if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then
cmds=$old_archive_from_new_cmds
else
# POSIX demands no paths to be encoded in archives. We have
# to avoid creating archives with duplicate basenames if we
# might have to extract them afterwards, e.g., when creating a
# static archive out of a convenience library, or when linking
# the entirety of a libtool archive into another (currently
# not supported by libtool).
if (for obj in $oldobjs
do
$echo "X$obj" | $Xsed -e 's%^.*/%%'
done | sort | sort -uc >/dev/null 2>&1); then
:
else
$echo "copying selected object files to avoid basename conflicts..."
if test -z "$gentop"; then
gentop="$output_objdir/${outputname}x"
generated="$generated $gentop"
$show "${rm}r $gentop"
$run ${rm}r "$gentop"
$show "$mkdir $gentop"
$run $mkdir "$gentop"
exit_status=$?
if test "$exit_status" -ne 0 && test ! -d "$gentop"; then
exit $exit_status
fi
fi
save_oldobjs=$oldobjs
oldobjs=
counter=1
for obj in $save_oldobjs
do
objbase=`$echo "X$obj" | $Xsed -e 's%^.*/%%'`
case " $oldobjs " in
" ") oldobjs=$obj ;;
*[\ /]"$objbase "*)
while :; do
# Make sure we don't pick an alternate name that also
# overlaps.
newobj=lt$counter-$objbase
counter=`expr $counter + 1`
case " $oldobjs " in
*[\ /]"$newobj "*) ;;
*) if test ! -f "$gentop/$newobj"; then break; fi ;;
esac
done
$show "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
$run ln "$obj" "$gentop/$newobj" ||
$run cp "$obj" "$gentop/$newobj"
oldobjs="$oldobjs $gentop/$newobj"
;;
*) oldobjs="$oldobjs $obj" ;;
esac
done
fi
eval cmds=\"$old_archive_cmds\"
if len=`expr "X$cmds" : ".*"` &&
test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
cmds=$old_archive_cmds
else
# the command line is too long to link in one step, link in parts
$echo "using piecewise archive linking..."
save_RANLIB=$RANLIB
RANLIB=:
objlist=
concat_cmds=
save_oldobjs=$oldobjs
# Is there a better way of finding the last object in the list?
for obj in $save_oldobjs
do
last_oldobj=$obj
done
for obj in $save_oldobjs
do
oldobjs="$objlist $obj"
objlist="$objlist $obj"
eval test_cmds=\"$old_archive_cmds\"
if len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
test "$len" -le "$max_cmd_len"; then
:
else
# the above command should be used before it gets too long
oldobjs=$objlist
if test "$obj" = "$last_oldobj" ; then
RANLIB=$save_RANLIB
fi
test -z "$concat_cmds" || concat_cmds=$concat_cmds~
eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\"
objlist=
fi
done
RANLIB=$save_RANLIB
oldobjs=$objlist
if test "X$oldobjs" = "X" ; then
eval cmds=\"\$concat_cmds\"
else
eval cmds=\"\$concat_cmds~\$old_archive_cmds\"
fi
fi
fi
save_ifs="$IFS"; IFS='~'
for cmd in $cmds; do
eval cmd=\"$cmd\"
IFS="$save_ifs"
$show "$cmd"
$run eval "$cmd" || exit $?
done
IFS="$save_ifs"
done
if test -n "$generated"; then
$show "${rm}r$generated"
$run ${rm}r$generated
fi
# Now create the libtool archive.
case $output in
*.la)
old_library=
test "$build_old_libs" = yes && old_library="$libname.$libext"
$show "creating $output"
# Preserve any variables that may affect compiler behavior
for var in $variables_saved_for_relink; do
if eval test -z \"\${$var+set}\"; then
relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command"
elif eval var_value=\$$var; test -z "$var_value"; then
relink_command="$var=; export $var; $relink_command"
else
var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"`
relink_command="$var=\"$var_value\"; export $var; $relink_command"
fi
done
# Quote the link command for shipping.
relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)"
relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e "$sed_quote_subst" | $NL2SP`
if test "$hardcode_automatic" = yes ; then
relink_command=
fi
# Only create the output if not a dry run.
if test -z "$run"; then
for installed in no yes; do
if test "$installed" = yes; then
if test -z "$install_libdir"; then
break
fi
output="$output_objdir/$outputname"i
# Replace all uninstalled libtool libraries with the installed ones
newdependency_libs=
for deplib in $dependency_libs; do
case $deplib in
*.la)
name=`$echo "X$deplib" | $Xsed -e 's%^.*/%%'`
eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
if test -z "$libdir"; then
$echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2
exit $EXIT_FAILURE
fi
newdependency_libs="$newdependency_libs $libdir/$name"
;;
*) newdependency_libs="$newdependency_libs $deplib" ;;
esac
done
dependency_libs="$newdependency_libs"
newdlfiles=
for lib in $dlfiles; do
name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
if test -z "$libdir"; then
$echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
exit $EXIT_FAILURE
fi
newdlfiles="$newdlfiles $libdir/$name"
done
dlfiles="$newdlfiles"
newdlprefiles=
for lib in $dlprefiles; do
name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
if test -z "$libdir"; then
$echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
exit $EXIT_FAILURE
fi
newdlprefiles="$newdlprefiles $libdir/$name"
done
dlprefiles="$newdlprefiles"
else
newdlfiles=
for lib in $dlfiles; do
case $lib in
[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
*) abs=`pwd`"/$lib" ;;
esac
newdlfiles="$newdlfiles $abs"
done
dlfiles="$newdlfiles"
newdlprefiles=
for lib in $dlprefiles; do
case $lib in
[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
*) abs=`pwd`"/$lib" ;;
esac
newdlprefiles="$newdlprefiles $abs"
done
dlprefiles="$newdlprefiles"
fi
$rm $output
# place dlname in correct position for cygwin
tdlname=$dlname
case $host,$output,$installed,$module,$dlname in
*cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;;
esac
$echo > $output "\
# $outputname - a libtool library file
# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
#
# Please DO NOT delete this file!
# It is necessary for linking the library.
# The name that we can dlopen(3).
dlname='$tdlname'
# Names of this library.
library_names='$library_names'
# The name of the static archive.
old_library='$old_library'
# Libraries that this one depends upon.
dependency_libs='$dependency_libs'
# Version information for $libname.
current=$current
age=$age
revision=$revision
# Is this an already installed library?
installed=$installed
# Should we warn about portability when linking against -modules?
shouldnotlink=$module
# Files to dlopen/dlpreopen
dlopen='$dlfiles'
dlpreopen='$dlprefiles'
# Directory that this library needs to be installed in:
libdir='$install_libdir'"
if test "$installed" = no && test "$need_relink" = yes; then
$echo >> $output "\
relink_command=\"$relink_command\""
fi
done
fi
# Do a symbolic link so that the libtool archive can be found in
# LD_LIBRARY_PATH before the program is installed.
$show "(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)"
$run eval '(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)' || exit $?
;;
esac
exit $EXIT_SUCCESS
;;
# libtool install mode
install)
modename="$modename: install"
# There may be an optional sh(1) argument at the beginning of
# install_prog (especially on Windows NT).
if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh ||
# Allow the use of GNU shtool's install command.
$echo "X$nonopt" | grep shtool > /dev/null; then
# Aesthetically quote it.
arg=`$echo "X$nonopt" | $Xsed -e "$sed_quote_subst"`
case $arg in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
arg="\"$arg\""
;;
esac
install_prog="$arg "
arg="$1"
shift
else
install_prog=
arg=$nonopt
fi
# The real first argument should be the name of the installation program.
# Aesthetically quote it.
arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
case $arg in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
arg="\"$arg\""
;;
esac
install_prog="$install_prog$arg"
# We need to accept at least all the BSD install flags.
dest=
files=
opts=
prev=
install_type=
isdir=no
stripme=
for arg
do
if test -n "$dest"; then
files="$files $dest"
dest=$arg
continue
fi
case $arg in
-d) isdir=yes ;;
-f)
case " $install_prog " in
*[\\\ /]cp\ *) ;;
*) prev=$arg ;;
esac
;;
-g | -m | -o) prev=$arg ;;
-s)
stripme=" -s"
continue
;;
-*)
;;
*)
# If the previous option needed an argument, then skip it.
if test -n "$prev"; then
prev=
else
dest=$arg
continue
fi
;;
esac
# Aesthetically quote the argument.
arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
case $arg in
*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
arg="\"$arg\""
;;
esac
install_prog="$install_prog $arg"
done
if test -z "$install_prog"; then
$echo "$modename: you must specify an install program" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
if test -n "$prev"; then
$echo "$modename: the \`$prev' option requires an argument" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
if test -z "$files"; then
if test -z "$dest"; then
$echo "$modename: no file or destination specified" 1>&2
else
$echo "$modename: you must specify a destination" 1>&2
fi
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
# Strip any trailing slash from the destination.
dest=`$echo "X$dest" | $Xsed -e 's%/$%%'`
# Check to see that the destination is a directory.
test -d "$dest" && isdir=yes
if test "$isdir" = yes; then
destdir="$dest"
destname=
else
destdir=`$echo "X$dest" | $Xsed -e 's%/[^/]*$%%'`
test "X$destdir" = "X$dest" && destdir=.
destname=`$echo "X$dest" | $Xsed -e 's%^.*/%%'`
# Not a directory, so check to see that there is only one file specified.
set dummy $files
if test "$#" -gt 2; then
$echo "$modename: \`$dest' is not a directory" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
fi
case $destdir in
[\\/]* | [A-Za-z]:[\\/]*) ;;
*)
for file in $files; do
case $file in
*.lo) ;;
*)
$echo "$modename: \`$destdir' must be an absolute directory name" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
;;
esac
done
;;
esac
# This variable tells wrapper scripts just to set variables rather
# than running their programs.
libtool_install_magic="$magic"
staticlibs=
future_libdirs=
current_libdirs=
for file in $files; do
# Do each installation.
case $file in
*.$libext)
# Do the static libraries later.
staticlibs="$staticlibs $file"
;;
*.la)
# Check to see that this really is a libtool archive.
if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then :
else
$echo "$modename: \`$file' is not a valid libtool archive" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
library_names=
old_library=
relink_command=
# If there is no directory component, then add one.
case $file in
*/* | *\\*) . $file ;;
*) . ./$file ;;
esac
# Add the libdir to current_libdirs if it is the destination.
if test "X$destdir" = "X$libdir"; then
case "$current_libdirs " in
*" $libdir "*) ;;
*) current_libdirs="$current_libdirs $libdir" ;;
esac
else
# Note the libdir as a future libdir.
case "$future_libdirs " in
*" $libdir "*) ;;
*) future_libdirs="$future_libdirs $libdir" ;;
esac
fi
dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`/
test "X$dir" = "X$file/" && dir=
dir="$dir$objdir"
if test -n "$relink_command"; then
# Determine the prefix the user has applied to our future dir.
inst_prefix_dir=`$echo "$destdir" | $SED "s%$libdir\$%%"`
# Don't allow the user to place us outside of our expected
# location b/c this prevents finding dependent libraries that
# are installed to the same prefix.
# At present, this check doesn't affect windows .dll's that
# are installed into $libdir/../bin (currently, that works fine)
# but it's something to keep an eye on.
if test "$inst_prefix_dir" = "$destdir"; then
$echo "$modename: error: cannot install \`$file' to a directory not ending in $libdir" 1>&2
exit $EXIT_FAILURE
fi
if test -n "$inst_prefix_dir"; then
# Stick the inst_prefix_dir data into the link command.
relink_command=`$echo "$relink_command" | $SP2NL | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%" | $NL2SP`
else
relink_command=`$echo "$relink_command" | $SP2NL | $SED "s%@inst_prefix_dir@%%" | $NL2SP`
fi
$echo "$modename: warning: relinking \`$file'" 1>&2
$show "$relink_command"
if $run eval "$relink_command"; then :
else
$echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2
exit $EXIT_FAILURE
fi
fi
# See the names of the shared library.
set dummy $library_names
if test -n "$2"; then
realname="$2"
shift
shift
srcname="$realname"
test -n "$relink_command" && srcname="$realname"T
# Install the shared library and build the symlinks.
$show "$install_prog $dir/$srcname $destdir/$realname"
$run eval "$install_prog $dir/$srcname $destdir/$realname" || exit $?
if test -n "$stripme" && test -n "$striplib"; then
$show "$striplib $destdir/$realname"
$run eval "$striplib $destdir/$realname" || exit $?
fi
if test "$#" -gt 0; then
# Delete the old symlinks, and create new ones.
# Try `ln -sf' first, because the `ln' binary might depend on
# the symlink we replace! Solaris /bin/ln does not understand -f,
# so we also need to try rm && ln -s.
for linkname
do
if test "$linkname" != "$realname"; then
$show "(cd $destdir && { $LN_S -f $realname $linkname || { $rm $linkname && $LN_S $realname $linkname; }; })"
$run eval "(cd $destdir && { $LN_S -f $realname $linkname || { $rm $linkname && $LN_S $realname $linkname; }; })"
fi
done
fi
# Do each command in the postinstall commands.
lib="$destdir/$realname"
cmds=$postinstall_cmds
save_ifs="$IFS"; IFS='~'
for cmd in $cmds; do
IFS="$save_ifs"
eval cmd=\"$cmd\"
$show "$cmd"
$run eval "$cmd" || {
lt_exit=$?
# Restore the uninstalled library and exit
if test "$mode" = relink; then
$run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname}U $realname)'
fi
exit $lt_exit
}
done
IFS="$save_ifs"
fi
# Install the pseudo-library for information purposes.
name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
instname="$dir/$name"i
$show "$install_prog $instname $destdir/$name"
$run eval "$install_prog $instname $destdir/$name" || exit $?
# Maybe install the static library, too.
test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library"
;;
*.lo)
# Install (i.e. copy) a libtool object.
# Figure out destination file name, if it wasn't already specified.
if test -n "$destname"; then
destfile="$destdir/$destname"
else
destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
destfile="$destdir/$destfile"
fi
# Deduce the name of the destination old-style object file.
case $destfile in
*.lo)
staticdest=`$echo "X$destfile" | $Xsed -e "$lo2o"`
;;
*.$objext)
staticdest="$destfile"
destfile=
;;
*)
$echo "$modename: cannot copy a libtool object to \`$destfile'" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
;;
esac
# Install the libtool object if requested.
if test -n "$destfile"; then
$show "$install_prog $file $destfile"
$run eval "$install_prog $file $destfile" || exit $?
fi
# Install the old object if enabled.
if test "$build_old_libs" = yes; then
# Deduce the name of the old-style object file.
staticobj=`$echo "X$file" | $Xsed -e "$lo2o"`
$show "$install_prog $staticobj $staticdest"
$run eval "$install_prog \$staticobj \$staticdest" || exit $?
fi
exit $EXIT_SUCCESS
;;
*)
# Figure out destination file name, if it wasn't already specified.
if test -n "$destname"; then
destfile="$destdir/$destname"
else
destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
destfile="$destdir/$destfile"
fi
# If the file is missing, and there is a .exe on the end, strip it
# because it is most likely a libtool script we actually want to
# install
stripped_ext=""
case $file in
*.exe)
if test ! -f "$file"; then
file=`$echo $file|${SED} 's,.exe$,,'`
stripped_ext=".exe"
fi
;;
esac
# Do a test to see if this is really a libtool program.
case $host in
*cygwin*|*mingw*)
wrapper=`$echo $file | ${SED} -e 's,.exe$,,'`
;;
*)
wrapper=$file
;;
esac
if (${SED} -e '4q' $wrapper | grep "^# Generated by .*$PACKAGE")>/dev/null 2>&1; then
notinst_deplibs=
relink_command=
# Note that it is not necessary on cygwin/mingw to append a dot to
# foo even if both foo and FILE.exe exist: automatic-append-.exe
# behavior happens only for exec(3), not for open(2)! Also, sourcing
# `FILE.' does not work on cygwin managed mounts.
#
# If there is no directory component, then add one.
case $wrapper in
*/* | *\\*) . ${wrapper} ;;
*) . ./${wrapper} ;;
esac
# Check the variables that should have been set.
if test -z "$notinst_deplibs"; then
$echo "$modename: invalid libtool wrapper script \`$wrapper'" 1>&2
exit $EXIT_FAILURE
fi
finalize=yes
for lib in $notinst_deplibs; do
# Check to see that each library is installed.
libdir=
if test -f "$lib"; then
# If there is no directory component, then add one.
case $lib in
*/* | *\\*) . $lib ;;
*) . ./$lib ;;
esac
fi
libfile="$libdir/"`$echo "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test
if test -n "$libdir" && test ! -f "$libfile"; then
$echo "$modename: warning: \`$lib' has not been installed in \`$libdir'" 1>&2
finalize=no
fi
done
relink_command=
# Note that it is not necessary on cygwin/mingw to append a dot to
# foo even if both foo and FILE.exe exist: automatic-append-.exe
# behavior happens only for exec(3), not for open(2)! Also, sourcing
# `FILE.' does not work on cygwin managed mounts.
#
# If there is no directory component, then add one.
case $wrapper in
*/* | *\\*) . ${wrapper} ;;
*) . ./${wrapper} ;;
esac
outputname=
if test "$fast_install" = no && test -n "$relink_command"; then
if test "$finalize" = yes && test -z "$run"; then
tmpdir=`func_mktempdir`
file=`$echo "X$file$stripped_ext" | $Xsed -e 's%^.*/%%'`
outputname="$tmpdir/$file"
# Replace the output file specification.
relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g' | $NL2SP`
$show "$relink_command"
if $run eval "$relink_command"; then :
else
$echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2
${rm}r "$tmpdir"
continue
fi
file="$outputname"
else
$echo "$modename: warning: cannot relink \`$file'" 1>&2
fi
else
# Install the binary that we compiled earlier.
file=`$echo "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"`
fi
fi
# remove .exe since cygwin /usr/bin/install will append another
# one anyway
case $install_prog,$host in
*/usr/bin/install*,*cygwin*)
case $file:$destfile in
*.exe:*.exe)
# this is ok
;;
*.exe:*)
destfile=$destfile.exe
;;
*:*.exe)
destfile=`$echo $destfile | ${SED} -e 's,.exe$,,'`
;;
esac
;;
esac
$show "$install_prog$stripme $file $destfile"
$run eval "$install_prog\$stripme \$file \$destfile" || exit $?
test -n "$outputname" && ${rm}r "$tmpdir"
;;
esac
done
for file in $staticlibs; do
name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
# Set up the ranlib parameters.
oldlib="$destdir/$name"
$show "$install_prog $file $oldlib"
$run eval "$install_prog \$file \$oldlib" || exit $?
if test -n "$stripme" && test -n "$old_striplib"; then
$show "$old_striplib $oldlib"
$run eval "$old_striplib $oldlib" || exit $?
fi
# Do each command in the postinstall commands.
cmds=$old_postinstall_cmds
save_ifs="$IFS"; IFS='~'
for cmd in $cmds; do
IFS="$save_ifs"
eval cmd=\"$cmd\"
$show "$cmd"
$run eval "$cmd" || exit $?
done
IFS="$save_ifs"
done
if test -n "$future_libdirs"; then
$echo "$modename: warning: remember to run \`$progname --finish$future_libdirs'" 1>&2
fi
if test -n "$current_libdirs"; then
# Maybe just do a dry run.
test -n "$run" && current_libdirs=" -n$current_libdirs"
exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs'
else
exit $EXIT_SUCCESS
fi
;;
# libtool finish mode
finish)
modename="$modename: finish"
libdirs="$nonopt"
admincmds=
if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
for dir
do
libdirs="$libdirs $dir"
done
for libdir in $libdirs; do
if test -n "$finish_cmds"; then
# Do each command in the finish commands.
cmds=$finish_cmds
save_ifs="$IFS"; IFS='~'
for cmd in $cmds; do
IFS="$save_ifs"
eval cmd=\"$cmd\"
$show "$cmd"
$run eval "$cmd" || admincmds="$admincmds
$cmd"
done
IFS="$save_ifs"
fi
if test -n "$finish_eval"; then
# Do the single finish_eval.
eval cmds=\"$finish_eval\"
$run eval "$cmds" || admincmds="$admincmds
$cmds"
fi
done
fi
# Exit here if they wanted silent mode.
test "$show" = : && exit $EXIT_SUCCESS
$echo "X----------------------------------------------------------------------" | $Xsed
$echo "Libraries have been installed in:"
for libdir in $libdirs; do
$echo " $libdir"
done
$echo
$echo "If you ever happen to want to link against installed libraries"
$echo "in a given directory, LIBDIR, you must either use libtool, and"
$echo "specify the full pathname of the library, or use the \`-LLIBDIR'"
$echo "flag during linking and do at least one of the following:"
if test -n "$shlibpath_var"; then
$echo " - add LIBDIR to the \`$shlibpath_var' environment variable"
$echo " during execution"
fi
if test -n "$runpath_var"; then
$echo " - add LIBDIR to the \`$runpath_var' environment variable"
$echo " during linking"
fi
if test -n "$hardcode_libdir_flag_spec"; then
libdir=LIBDIR
eval flag=\"$hardcode_libdir_flag_spec\"
$echo " - use the \`$flag' linker flag"
fi
if test -n "$admincmds"; then
$echo " - have your system administrator run these commands:$admincmds"
fi
if test -f /etc/ld.so.conf; then
$echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
fi
$echo
$echo "See any operating system documentation about shared libraries for"
$echo "more information, such as the ld(1) and ld.so(8) manual pages."
$echo "X----------------------------------------------------------------------" | $Xsed
exit $EXIT_SUCCESS
;;
# libtool execute mode
execute)
modename="$modename: execute"
# The first argument is the command name.
cmd="$nonopt"
if test -z "$cmd"; then
$echo "$modename: you must specify a COMMAND" 1>&2
$echo "$help"
exit $EXIT_FAILURE
fi
# Handle -dlopen flags immediately.
for file in $execute_dlfiles; do
if test ! -f "$file"; then
$echo "$modename: \`$file' is not a file" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
dir=
case $file in
*.la)
# Check to see that this really is a libtool archive.
if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then :
else
$echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
# Read the libtool library.
dlname=
library_names=
# If there is no directory component, then add one.
case $file in
*/* | *\\*) . $file ;;
*) . ./$file ;;
esac
# Skip this library if it cannot be dlopened.
if test -z "$dlname"; then
# Warn if it was a shared library.
test -n "$library_names" && $echo "$modename: warning: \`$file' was not linked with \`-export-dynamic'"
continue
fi
dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
test "X$dir" = "X$file" && dir=.
if test -f "$dir/$objdir/$dlname"; then
dir="$dir/$objdir"
else
$echo "$modename: cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" 1>&2
exit $EXIT_FAILURE
fi
;;
*.lo)
# Just add the directory containing the .lo file.
dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
test "X$dir" = "X$file" && dir=.
;;
*)
$echo "$modename: warning \`-dlopen' is ignored for non-libtool libraries and objects" 1>&2
continue
;;
esac
# Get the absolute pathname.
absdir=`cd "$dir" && pwd`
test -n "$absdir" && dir="$absdir"
# Now add the directory to shlibpath_var.
if eval "test -z \"\$$shlibpath_var\""; then
eval "$shlibpath_var=\"\$dir\""
else
eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\""
fi
done
# This variable tells wrapper scripts just to set shlibpath_var
# rather than running their programs.
libtool_execute_magic="$magic"
# Check if any of the arguments is a wrapper script.
args=
for file
do
case $file in
-*) ;;
*)
# Do a test to see if this is really a libtool program.
if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
# If there is no directory component, then add one.
case $file in
*/* | *\\*) . $file ;;
*) . ./$file ;;
esac
# Transform arg to wrapped name.
file="$progdir/$program"
fi
;;
esac
# Quote arguments (to preserve shell metacharacters).
file=`$echo "X$file" | $Xsed -e "$sed_quote_subst"`
args="$args \"$file\""
done
if test -z "$run"; then
if test -n "$shlibpath_var"; then
# Export the shlibpath_var.
eval "export $shlibpath_var"
fi
# Restore saved environment variables
for lt_var in LANG LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
do
eval "if test \"\${save_$lt_var+set}\" = set; then
$lt_var=\$save_$lt_var; export $lt_var
else
$lt_unset $lt_var
fi"
done
# Now prepare to actually exec the command.
exec_cmd="\$cmd$args"
else
# Display what would be done.
if test -n "$shlibpath_var"; then
eval "\$echo \"\$shlibpath_var=\$$shlibpath_var\""
$echo "export $shlibpath_var"
fi
$echo "$cmd$args"
exit $EXIT_SUCCESS
fi
;;
# libtool clean and uninstall mode
clean | uninstall)
modename="$modename: $mode"
rm="$nonopt"
files=
rmforce=
exit_status=0
# This variable tells wrapper scripts just to set variables rather
# than running their programs.
libtool_install_magic="$magic"
for arg
do
case $arg in
-f) rm="$rm $arg"; rmforce=yes ;;
-*) rm="$rm $arg" ;;
*) files="$files $arg" ;;
esac
done
if test -z "$rm"; then
$echo "$modename: you must specify an RM program" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
fi
rmdirs=
origobjdir="$objdir"
for file in $files; do
dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
if test "X$dir" = "X$file"; then
dir=.
objdir="$origobjdir"
else
objdir="$dir/$origobjdir"
fi
name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
test "$mode" = uninstall && objdir="$dir"
# Remember objdir for removal later, being careful to avoid duplicates
if test "$mode" = clean; then
case " $rmdirs " in
*" $objdir "*) ;;
*) rmdirs="$rmdirs $objdir" ;;
esac
fi
# Don't error if the file doesn't exist and rm -f was used.
if (test -L "$file") >/dev/null 2>&1 \
|| (test -h "$file") >/dev/null 2>&1 \
|| test -f "$file"; then
:
elif test -d "$file"; then
exit_status=1
continue
elif test "$rmforce" = yes; then
continue
fi
rmfiles="$file"
case $name in
*.la)
# Possibly a libtool archive, so verify it.
if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
. $dir/$name
# Delete the libtool libraries and symlinks.
for n in $library_names; do
rmfiles="$rmfiles $objdir/$n"
done
test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library"
case "$mode" in
clean)
case " $library_names " in
# " " in the beginning catches empty $dlname
*" $dlname "*) ;;
*) rmfiles="$rmfiles $objdir/$dlname" ;;
esac
test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i"
;;
uninstall)
if test -n "$library_names"; then
# Do each command in the postuninstall commands.
cmds=$postuninstall_cmds
save_ifs="$IFS"; IFS='~'
for cmd in $cmds; do
IFS="$save_ifs"
eval cmd=\"$cmd\"
$show "$cmd"
$run eval "$cmd"
if test "$?" -ne 0 && test "$rmforce" != yes; then
exit_status=1
fi
done
IFS="$save_ifs"
fi
if test -n "$old_library"; then
# Do each command in the old_postuninstall commands.
cmds=$old_postuninstall_cmds
save_ifs="$IFS"; IFS='~'
for cmd in $cmds; do
IFS="$save_ifs"
eval cmd=\"$cmd\"
$show "$cmd"
$run eval "$cmd"
if test "$?" -ne 0 && test "$rmforce" != yes; then
exit_status=1
fi
done
IFS="$save_ifs"
fi
# FIXME: should reinstall the best remaining shared library.
;;
esac
fi
;;
*.lo)
# Possibly a libtool object, so verify it.
if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
# Read the .lo file
. $dir/$name
# Add PIC object to the list of files to remove.
if test -n "$pic_object" \
&& test "$pic_object" != none; then
rmfiles="$rmfiles $dir/$pic_object"
fi
# Add non-PIC object to the list of files to remove.
if test -n "$non_pic_object" \
&& test "$non_pic_object" != none; then
rmfiles="$rmfiles $dir/$non_pic_object"
fi
fi
;;
*)
if test "$mode" = clean ; then
noexename=$name
case $file in
*.exe)
file=`$echo $file|${SED} 's,.exe$,,'`
noexename=`$echo $name|${SED} 's,.exe$,,'`
# $file with .exe has already been added to rmfiles,
# add $file without .exe
rmfiles="$rmfiles $file"
;;
esac
# Do a test to see if this is a libtool program.
if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
relink_command=
. $dir/$noexename
# note $name still contains .exe if it was in $file originally
# as does the version of $file that was added into $rmfiles
rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}"
if test "$fast_install" = yes && test -n "$relink_command"; then
rmfiles="$rmfiles $objdir/lt-$name"
fi
if test "X$noexename" != "X$name" ; then
rmfiles="$rmfiles $objdir/lt-${noexename}.c"
fi
fi
fi
;;
esac
$show "$rm $rmfiles"
$run $rm $rmfiles || exit_status=1
done
objdir="$origobjdir"
# Try to remove the ${objdir}s in the directories where we deleted files
for dir in $rmdirs; do
if test -d "$dir"; then
$show "rmdir $dir"
$run rmdir $dir >/dev/null 2>&1
fi
done
exit $exit_status
;;
"")
$echo "$modename: you must specify a MODE" 1>&2
$echo "$generic_help" 1>&2
exit $EXIT_FAILURE
;;
esac
if test -z "$exec_cmd"; then
$echo "$modename: invalid operation mode \`$mode'" 1>&2
$echo "$generic_help" 1>&2
exit $EXIT_FAILURE
fi
fi # test -z "$show_help"
if test -n "$exec_cmd"; then
eval exec $exec_cmd
exit $EXIT_FAILURE
fi
# We need to display help for each of the modes.
case $mode in
"") $echo \
"Usage: $modename [OPTION]... [MODE-ARG]...
Provide generalized library-building support services.
--config show all configuration variables
--debug enable verbose shell tracing
-n, --dry-run display commands without modifying any files
--features display basic configuration information and exit
--finish same as \`--mode=finish'
--help display this help message and exit
--mode=MODE use operation mode MODE [default=inferred from MODE-ARGS]
--quiet same as \`--silent'
--silent don't print informational messages
--tag=TAG use configuration variables from tag TAG
--version print version information
MODE must be one of the following:
clean remove files from the build directory
compile compile a source file into a libtool object
execute automatically set library path, then run a program
finish complete the installation of libtool libraries
install install libraries or executables
link create a library or an executable
uninstall remove libraries from an installed directory
MODE-ARGS vary depending on the MODE. Try \`$modename --help --mode=MODE' for
a more detailed description of MODE.
Report bugs to <bug-libtool@gnu.org>."
exit $EXIT_SUCCESS
;;
clean)
$echo \
"Usage: $modename [OPTION]... --mode=clean RM [RM-OPTION]... FILE...
Remove files from the build directory.
RM is the name of the program to use to delete files associated with each FILE
(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed
to RM.
If FILE is a libtool library, object or program, all the files associated
with it are deleted. Otherwise, only FILE itself is deleted using RM."
;;
compile)
$echo \
"Usage: $modename [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE
Compile a source file into a libtool library object.
This mode accepts the following additional options:
-o OUTPUT-FILE set the output file name to OUTPUT-FILE
-prefer-pic try to building PIC objects only
-prefer-non-pic try to building non-PIC objects only
-static always build a \`.o' file suitable for static linking
COMPILE-COMMAND is a command to be used in creating a \`standard' object file
from the given SOURCEFILE.
The output file name is determined by removing the directory component from
SOURCEFILE, then substituting the C source code suffix \`.c' with the
library object suffix, \`.lo'."
;;
execute)
$echo \
"Usage: $modename [OPTION]... --mode=execute COMMAND [ARGS]...
Automatically set library path, then run a program.
This mode accepts the following additional options:
-dlopen FILE add the directory containing FILE to the library path
This mode sets the library path environment variable according to \`-dlopen'
flags.
If any of the ARGS are libtool executable wrappers, then they are translated
into their corresponding uninstalled binary, and any of their required library
directories are added to the library path.
Then, COMMAND is executed, with ARGS as arguments."
;;
finish)
$echo \
"Usage: $modename [OPTION]... --mode=finish [LIBDIR]...
Complete the installation of libtool libraries.
Each LIBDIR is a directory that contains libtool libraries.
The commands that this mode executes may require superuser privileges. Use
the \`--dry-run' option if you just want to see what would be executed."
;;
install)
$echo \
"Usage: $modename [OPTION]... --mode=install INSTALL-COMMAND...
Install executables or libraries.
INSTALL-COMMAND is the installation command. The first component should be
either the \`install' or \`cp' program.
The rest of the components are interpreted as arguments to that command (only
BSD-compatible install options are recognized)."
;;
link)
$echo \
"Usage: $modename [OPTION]... --mode=link LINK-COMMAND...
Link object files or libraries together to form another library, or to
create an executable program.
LINK-COMMAND is a command using the C compiler that you would use to create
a program from several object files.
The following components of LINK-COMMAND are treated specially:
-all-static do not do any dynamic linking at all
-avoid-version do not add a version suffix if possible
-dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime
-dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols
-export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3)
-export-symbols SYMFILE
try to export only the symbols listed in SYMFILE
-export-symbols-regex REGEX
try to export only the symbols matching REGEX
-LLIBDIR search LIBDIR for required installed libraries
-lNAME OUTPUT-FILE requires the installed library libNAME
-module build a library that can dlopened
-no-fast-install disable the fast-install mode
-no-install link a not-installable executable
-no-undefined declare that a library does not refer to external symbols
-o OUTPUT-FILE create OUTPUT-FILE from the specified objects
-objectlist FILE Use a list of object files found in FILE to specify objects
-precious-files-regex REGEX
don't remove output files matching REGEX
-release RELEASE specify package release information
-rpath LIBDIR the created library will eventually be installed in LIBDIR
-R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries
-static do not do any dynamic linking of uninstalled libtool libraries
-static-libtool-libs
do not do any dynamic linking of libtool libraries
-version-info CURRENT[:REVISION[:AGE]]
specify library version info [each variable defaults to 0]
All other options (arguments beginning with \`-') are ignored.
Every other argument is treated as a filename. Files ending in \`.la' are
treated as uninstalled libtool libraries, other files are standard or library
object files.
If the OUTPUT-FILE ends in \`.la', then a libtool library is created,
only library objects (\`.lo' files) may be specified, and \`-rpath' is
required, except when creating a convenience library.
If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created
using \`ar' and \`ranlib', or on Windows using \`lib'.
If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file
is created, otherwise an executable program is created."
;;
uninstall)
$echo \
"Usage: $modename [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...
Remove libraries from an installation directory.
RM is the name of the program to use to delete files associated with each FILE
(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed
to RM.
If FILE is a libtool library, all the files associated with it are deleted.
Otherwise, only FILE itself is deleted using RM."
;;
*)
$echo "$modename: invalid operation mode \`$mode'" 1>&2
$echo "$help" 1>&2
exit $EXIT_FAILURE
;;
esac
$echo
$echo "Try \`$modename --help' for more information about other modes."
exit $?
# The TAGs below are defined such that we never get into a situation
# in which we disable both kinds of libraries. Given conflicting
# choices, we go for a static library, that is the most portable,
# since we can't tell whether shared libraries were disabled because
# the user asked for that or because the platform doesn't support
# them. This is particularly important on AIX, because we don't
# support having both static and shared libraries enabled at the same
# time on that platform, so we default to a shared-only configuration.
# If a disable-shared tag is given, we'll fallback to a static-only
# configuration. But we'll never go from static-only to shared-only.
# ### BEGIN LIBTOOL TAG CONFIG: disable-shared
disable_libs=shared
# ### END LIBTOOL TAG CONFIG: disable-shared
# ### BEGIN LIBTOOL TAG CONFIG: disable-static
disable_libs=static
# ### END LIBTOOL TAG CONFIG: disable-static
# Local Variables:
# mode:shell-script
# sh-indentation:2
# End:
| zz1126wnx-iperf3 | config/ltmain.sh | Shell | bsd | 198,422 |
#! /bin/sh
# depcomp - compile a program generating dependencies as side-effects
scriptversion=2005-07-09.11
# Copyright (C) 1999, 2000, 2003, 2004, 2005 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# Originally written by Alexandre Oliva <oliva@dcc.unicamp.br>.
case $1 in
'')
echo "$0: No command. Try \`$0 --help' for more information." 1>&2
exit 1;
;;
-h | --h*)
cat <<\EOF
Usage: depcomp [--help] [--version] PROGRAM [ARGS]
Run PROGRAMS ARGS to compile a file, generating dependencies
as side-effects.
Environment variables:
depmode Dependency tracking mode.
source Source file read by `PROGRAMS ARGS'.
object Object file output by `PROGRAMS ARGS'.
DEPDIR directory where to store dependencies.
depfile Dependency file to output.
tmpdepfile Temporary file to use when outputing dependencies.
libtool Whether libtool is used (yes/no).
Report bugs to <bug-automake@gnu.org>.
EOF
exit $?
;;
-v | --v*)
echo "depcomp $scriptversion"
exit $?
;;
esac
if test -z "$depmode" || test -z "$source" || test -z "$object"; then
echo "depcomp: Variables source, object and depmode must be set" 1>&2
exit 1
fi
# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po.
depfile=${depfile-`echo "$object" |
sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`}
tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
rm -f "$tmpdepfile"
# Some modes work just like other modes, but use different flags. We
# parameterize here, but still list the modes in the big case below,
# to make depend.m4 easier to write. Note that we *cannot* use a case
# here, because this file can only contain one case statement.
if test "$depmode" = hp; then
# HP compiler uses -M and no extra arg.
gccflag=-M
depmode=gcc
fi
if test "$depmode" = dashXmstdout; then
# This is just like dashmstdout with a different argument.
dashmflag=-xM
depmode=dashmstdout
fi
case "$depmode" in
gcc3)
## gcc 3 implements dependency tracking that does exactly what
## we want. Yay! Note: for some reason libtool 1.4 doesn't like
## it if -MD -MP comes after the -MF stuff. Hmm.
"$@" -MT "$object" -MD -MP -MF "$tmpdepfile"
stat=$?
if test $stat -eq 0; then :
else
rm -f "$tmpdepfile"
exit $stat
fi
mv "$tmpdepfile" "$depfile"
;;
gcc)
## There are various ways to get dependency output from gcc. Here's
## why we pick this rather obscure method:
## - Don't want to use -MD because we'd like the dependencies to end
## up in a subdir. Having to rename by hand is ugly.
## (We might end up doing this anyway to support other compilers.)
## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like
## -MM, not -M (despite what the docs say).
## - Using -M directly means running the compiler twice (even worse
## than renaming).
if test -z "$gccflag"; then
gccflag=-MD,
fi
"$@" -Wp,"$gccflag$tmpdepfile"
stat=$?
if test $stat -eq 0; then :
else
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
echo "$object : \\" > "$depfile"
alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
## The second -e expression handles DOS-style file names with drive letters.
sed -e 's/^[^:]*: / /' \
-e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile"
## This next piece of magic avoids the `deleted header file' problem.
## The problem is that when a header file which appears in a .P file
## is deleted, the dependency causes make to die (because there is
## typically no way to rebuild the header). We avoid this by adding
## dummy dependencies for each header file. Too bad gcc doesn't do
## this for us directly.
tr ' ' '
' < "$tmpdepfile" |
## Some versions of gcc put a space before the `:'. On the theory
## that the space means something, we add a space to the output as
## well.
## Some versions of the HPUX 10.20 sed can't process this invocation
## correctly. Breaking it into two sed invocations is a workaround.
sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
hp)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
sgi)
if test "$libtool" = yes; then
"$@" "-Wp,-MDupdate,$tmpdepfile"
else
"$@" -MDupdate "$tmpdepfile"
fi
stat=$?
if test $stat -eq 0; then :
else
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files
echo "$object : \\" > "$depfile"
# Clip off the initial element (the dependent). Don't try to be
# clever and replace this with sed code, as IRIX sed won't handle
# lines with more than a fixed number of characters (4096 in
# IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines;
# the IRIX cc adds comments like `#:fec' to the end of the
# dependency line.
tr ' ' '
' < "$tmpdepfile" \
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \
tr '
' ' ' >> $depfile
echo >> $depfile
# The second pass generates a dummy entry for each header file.
tr ' ' '
' < "$tmpdepfile" \
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
>> $depfile
else
# The sourcefile does not contain any dependencies, so just
# store a dummy comment line, to avoid errors with the Makefile
# "include basename.Plo" scheme.
echo "#dummy" > "$depfile"
fi
rm -f "$tmpdepfile"
;;
aix)
# The C for AIX Compiler uses -M and outputs the dependencies
# in a .u file. In older versions, this file always lives in the
# current directory. Also, the AIX compiler puts `$object:' at the
# start of each line; $object doesn't have directory information.
# Version 6 uses the directory in both cases.
stripped=`echo "$object" | sed 's/\(.*\)\..*$/\1/'`
tmpdepfile="$stripped.u"
if test "$libtool" = yes; then
"$@" -Wc,-M
else
"$@" -M
fi
stat=$?
if test -f "$tmpdepfile"; then :
else
stripped=`echo "$stripped" | sed 's,^.*/,,'`
tmpdepfile="$stripped.u"
fi
if test $stat -eq 0; then :
else
rm -f "$tmpdepfile"
exit $stat
fi
if test -f "$tmpdepfile"; then
outname="$stripped.o"
# Each line is of the form `foo.o: dependent.h'.
# Do two passes, one to just change these to
# `$object: dependent.h' and one to simply `dependent.h:'.
sed -e "s,^$outname:,$object :," < "$tmpdepfile" > "$depfile"
sed -e "s,^$outname: \(.*\)$,\1:," < "$tmpdepfile" >> "$depfile"
else
# The sourcefile does not contain any dependencies, so just
# store a dummy comment line, to avoid errors with the Makefile
# "include basename.Plo" scheme.
echo "#dummy" > "$depfile"
fi
rm -f "$tmpdepfile"
;;
icc)
# Intel's C compiler understands `-MD -MF file'. However on
# icc -MD -MF foo.d -c -o sub/foo.o sub/foo.c
# ICC 7.0 will fill foo.d with something like
# foo.o: sub/foo.c
# foo.o: sub/foo.h
# which is wrong. We want:
# sub/foo.o: sub/foo.c
# sub/foo.o: sub/foo.h
# sub/foo.c:
# sub/foo.h:
# ICC 7.1 will output
# foo.o: sub/foo.c sub/foo.h
# and will wrap long lines using \ :
# foo.o: sub/foo.c ... \
# sub/foo.h ... \
# ...
"$@" -MD -MF "$tmpdepfile"
stat=$?
if test $stat -eq 0; then :
else
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
# Each line is of the form `foo.o: dependent.h',
# or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'.
# Do two passes, one to just change these to
# `$object: dependent.h' and one to simply `dependent.h:'.
sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile"
# Some versions of the HPUX 10.20 sed can't process this invocation
# correctly. Breaking it into two sed invocations is a workaround.
sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" |
sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
tru64)
# The Tru64 compiler uses -MD to generate dependencies as a side
# effect. `cc -MD -o foo.o ...' puts the dependencies into `foo.o.d'.
# At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put
# dependencies in `foo.d' instead, so we check for that too.
# Subdirectories are respected.
dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
test "x$dir" = "x$object" && dir=
base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
if test "$libtool" = yes; then
# With Tru64 cc, shared objects can also be used to make a
# static library. This mecanism is used in libtool 1.4 series to
# handle both shared and static libraries in a single compilation.
# With libtool 1.4, dependencies were output in $dir.libs/$base.lo.d.
#
# With libtool 1.5 this exception was removed, and libtool now
# generates 2 separate objects for the 2 libraries. These two
# compilations output dependencies in in $dir.libs/$base.o.d and
# in $dir$base.o.d. We have to check for both files, because
# one of the two compilations can be disabled. We should prefer
# $dir$base.o.d over $dir.libs/$base.o.d because the latter is
# automatically cleaned when .libs/ is deleted, while ignoring
# the former would cause a distcleancheck panic.
tmpdepfile1=$dir.libs/$base.lo.d # libtool 1.4
tmpdepfile2=$dir$base.o.d # libtool 1.5
tmpdepfile3=$dir.libs/$base.o.d # libtool 1.5
tmpdepfile4=$dir.libs/$base.d # Compaq CCC V6.2-504
"$@" -Wc,-MD
else
tmpdepfile1=$dir$base.o.d
tmpdepfile2=$dir$base.d
tmpdepfile3=$dir$base.d
tmpdepfile4=$dir$base.d
"$@" -MD
fi
stat=$?
if test $stat -eq 0; then :
else
rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4"
exit $stat
fi
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4"
do
test -f "$tmpdepfile" && break
done
if test -f "$tmpdepfile"; then
sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile"
# That's a tab and a space in the [].
sed -e 's,^.*\.[a-z]*:[ ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
else
echo "#dummy" > "$depfile"
fi
rm -f "$tmpdepfile"
;;
#nosideeffect)
# This comment above is used by automake to tell side-effect
# dependency tracking mechanisms from slower ones.
dashmstdout)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout, regardless of -o.
"$@" || exit $?
# Remove the call to Libtool.
if test "$libtool" = yes; then
while test $1 != '--mode=compile'; do
shift
done
shift
fi
# Remove `-o $object'.
IFS=" "
for arg
do
case $arg in
-o)
shift
;;
$object)
shift
;;
*)
set fnord "$@" "$arg"
shift # fnord
shift # $arg
;;
esac
done
test -z "$dashmflag" && dashmflag=-M
# Require at least two characters before searching for `:'
# in the target name. This is to cope with DOS-style filenames:
# a dependency such as `c:/foo/bar' could be seen as target `c' otherwise.
"$@" $dashmflag |
sed 's:^[ ]*[^: ][^:][^:]*\:[ ]*:'"$object"'\: :' > "$tmpdepfile"
rm -f "$depfile"
cat < "$tmpdepfile" > "$depfile"
tr ' ' '
' < "$tmpdepfile" | \
## Some versions of the HPUX 10.20 sed can't process this invocation
## correctly. Breaking it into two sed invocations is a workaround.
sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
dashXmstdout)
# This case only exists to satisfy depend.m4. It is never actually
# run, as this mode is specially recognized in the preamble.
exit 1
;;
makedepend)
"$@" || exit $?
# Remove any Libtool call
if test "$libtool" = yes; then
while test $1 != '--mode=compile'; do
shift
done
shift
fi
# X makedepend
shift
cleared=no
for arg in "$@"; do
case $cleared in
no)
set ""; shift
cleared=yes ;;
esac
case "$arg" in
-D*|-I*)
set fnord "$@" "$arg"; shift ;;
# Strip any option that makedepend may not understand. Remove
# the object too, otherwise makedepend will parse it as a source file.
-*|$object)
;;
*)
set fnord "$@" "$arg"; shift ;;
esac
done
obj_suffix="`echo $object | sed 's/^.*\././'`"
touch "$tmpdepfile"
${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@"
rm -f "$depfile"
cat < "$tmpdepfile" > "$depfile"
sed '1,2d' "$tmpdepfile" | tr ' ' '
' | \
## Some versions of the HPUX 10.20 sed can't process this invocation
## correctly. Breaking it into two sed invocations is a workaround.
sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile" "$tmpdepfile".bak
;;
cpp)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout.
"$@" || exit $?
# Remove the call to Libtool.
if test "$libtool" = yes; then
while test $1 != '--mode=compile'; do
shift
done
shift
fi
# Remove `-o $object'.
IFS=" "
for arg
do
case $arg in
-o)
shift
;;
$object)
shift
;;
*)
set fnord "$@" "$arg"
shift # fnord
shift # $arg
;;
esac
done
"$@" -E |
sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
-e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' |
sed '$ s: \\$::' > "$tmpdepfile"
rm -f "$depfile"
echo "$object : \\" > "$depfile"
cat < "$tmpdepfile" >> "$depfile"
sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
msvisualcpp)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout, regardless of -o,
# because we must use -o when running libtool.
"$@" || exit $?
IFS=" "
for arg
do
case "$arg" in
"-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI")
set fnord "$@"
shift
shift
;;
*)
set fnord "$@" "$arg"
shift
shift
;;
esac
done
"$@" -E |
sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::echo "`cygpath -u \\"\1\\"`":p' | sort | uniq > "$tmpdepfile"
rm -f "$depfile"
echo "$object : \\" > "$depfile"
. "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s:: \1 \\:p' >> "$depfile"
echo " " >> "$depfile"
. "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::\1\::p' >> "$depfile"
rm -f "$tmpdepfile"
;;
none)
exec "$@"
;;
*)
echo "Unknown depmode $depmode" 1>&2
exit 1
;;
esac
exit 0
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-end: "$"
# End:
| zz1126wnx-iperf3 | config/depcomp | Shell | bsd | 15,936 |
#! /bin/sh
# Common stub for a few missing GNU programs while installing.
scriptversion=2005-06-08.21
# Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2005
# Free Software Foundation, Inc.
# Originally by Fran,cois Pinard <pinard@iro.umontreal.ca>, 1996.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
if test $# -eq 0; then
echo 1>&2 "Try \`$0 --help' for more information"
exit 1
fi
run=:
# In the cases where this matters, `missing' is being run in the
# srcdir already.
if test -f configure.ac; then
configure_ac=configure.ac
else
configure_ac=configure.in
fi
msg="missing on your system"
case "$1" in
--run)
# Try to run requested program, and just exit if it succeeds.
run=
shift
"$@" && exit 0
# Exit code 63 means version mismatch. This often happens
# when the user try to use an ancient version of a tool on
# a file that requires a minimum version. In this case we
# we should proceed has if the program had been absent, or
# if --run hadn't been passed.
if test $? = 63; then
run=:
msg="probably too old"
fi
;;
-h|--h|--he|--hel|--help)
echo "\
$0 [OPTION]... PROGRAM [ARGUMENT]...
Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an
error status if there is no known handling for PROGRAM.
Options:
-h, --help display this help and exit
-v, --version output version information and exit
--run try to run the given command, and emulate it if it fails
Supported PROGRAM values:
aclocal touch file \`aclocal.m4'
autoconf touch file \`configure'
autoheader touch file \`config.h.in'
automake touch all \`Makefile.in' files
bison create \`y.tab.[ch]', if possible, from existing .[ch]
flex create \`lex.yy.c', if possible, from existing .c
help2man touch the output file
lex create \`lex.yy.c', if possible, from existing .c
makeinfo touch the output file
tar try tar, gnutar, gtar, then tar without non-portable flags
yacc create \`y.tab.[ch]', if possible, from existing .[ch]
Send bug reports to <bug-automake@gnu.org>."
exit $?
;;
-v|--v|--ve|--ver|--vers|--versi|--versio|--version)
echo "missing $scriptversion (GNU Automake)"
exit $?
;;
-*)
echo 1>&2 "$0: Unknown \`$1' option"
echo 1>&2 "Try \`$0 --help' for more information"
exit 1
;;
esac
# Now exit if we have it, but it failed. Also exit now if we
# don't have it and --version was passed (most likely to detect
# the program).
case "$1" in
lex|yacc)
# Not GNU programs, they don't have --version.
;;
tar)
if test -n "$run"; then
echo 1>&2 "ERROR: \`tar' requires --run"
exit 1
elif test "x$2" = "x--version" || test "x$2" = "x--help"; then
exit 1
fi
;;
*)
if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
# We have it, but it failed.
exit 1
elif test "x$2" = "x--version" || test "x$2" = "x--help"; then
# Could not run --version or --help. This is probably someone
# running `$TOOL --version' or `$TOOL --help' to check whether
# $TOOL exists and not knowing $TOOL uses missing.
exit 1
fi
;;
esac
# If it does not exist, or fails to run (possibly an outdated version),
# try to emulate it.
case "$1" in
aclocal*)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified \`acinclude.m4' or \`${configure_ac}'. You might want
to install the \`Automake' and \`Perl' packages. Grab them from
any GNU archive site."
touch aclocal.m4
;;
autoconf)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified \`${configure_ac}'. You might want to install the
\`Autoconf' and \`GNU m4' packages. Grab them from any GNU
archive site."
touch configure
;;
autoheader)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified \`acconfig.h' or \`${configure_ac}'. You might want
to install the \`Autoconf' and \`GNU m4' packages. Grab them
from any GNU archive site."
files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}`
test -z "$files" && files="config.h"
touch_files=
for f in $files; do
case "$f" in
*:*) touch_files="$touch_files "`echo "$f" |
sed -e 's/^[^:]*://' -e 's/:.*//'`;;
*) touch_files="$touch_files $f.in";;
esac
done
touch $touch_files
;;
automake*)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'.
You might want to install the \`Automake' and \`Perl' packages.
Grab them from any GNU archive site."
find . -type f -name Makefile.am -print |
sed 's/\.am$/.in/' |
while read f; do touch "$f"; done
;;
autom4te)
echo 1>&2 "\
WARNING: \`$1' is needed, but is $msg.
You might have modified some files without having the
proper tools for further handling them.
You can get \`$1' as part of \`Autoconf' from any GNU
archive site."
file=`echo "$*" | sed -n 's/.*--output[ =]*\([^ ]*\).*/\1/p'`
test -z "$file" && file=`echo "$*" | sed -n 's/.*-o[ ]*\([^ ]*\).*/\1/p'`
if test -f "$file"; then
touch $file
else
test -z "$file" || exec >$file
echo "#! /bin/sh"
echo "# Created by GNU Automake missing as a replacement of"
echo "# $ $@"
echo "exit 0"
chmod +x $file
exit 1
fi
;;
bison|yacc)
echo 1>&2 "\
WARNING: \`$1' $msg. You should only need it if
you modified a \`.y' file. You may need the \`Bison' package
in order for those modifications to take effect. You can get
\`Bison' from any GNU archive site."
rm -f y.tab.c y.tab.h
if [ $# -ne 1 ]; then
eval LASTARG="\${$#}"
case "$LASTARG" in
*.y)
SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'`
if [ -f "$SRCFILE" ]; then
cp "$SRCFILE" y.tab.c
fi
SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'`
if [ -f "$SRCFILE" ]; then
cp "$SRCFILE" y.tab.h
fi
;;
esac
fi
if [ ! -f y.tab.h ]; then
echo >y.tab.h
fi
if [ ! -f y.tab.c ]; then
echo 'main() { return 0; }' >y.tab.c
fi
;;
lex|flex)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified a \`.l' file. You may need the \`Flex' package
in order for those modifications to take effect. You can get
\`Flex' from any GNU archive site."
rm -f lex.yy.c
if [ $# -ne 1 ]; then
eval LASTARG="\${$#}"
case "$LASTARG" in
*.l)
SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'`
if [ -f "$SRCFILE" ]; then
cp "$SRCFILE" lex.yy.c
fi
;;
esac
fi
if [ ! -f lex.yy.c ]; then
echo 'main() { return 0; }' >lex.yy.c
fi
;;
help2man)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified a dependency of a manual page. You may need the
\`Help2man' package in order for those modifications to take
effect. You can get \`Help2man' from any GNU archive site."
file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'`
if test -z "$file"; then
file=`echo "$*" | sed -n 's/.*--output=\([^ ]*\).*/\1/p'`
fi
if [ -f "$file" ]; then
touch $file
else
test -z "$file" || exec >$file
echo ".ab help2man is required to generate this page"
exit 1
fi
;;
makeinfo)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified a \`.texi' or \`.texinfo' file, or any other file
indirectly affecting the aspect of the manual. The spurious
call might also be the consequence of using a buggy \`make' (AIX,
DU, IRIX). You might want to install the \`Texinfo' package or
the \`GNU make' package. Grab either from any GNU archive site."
# The file to touch is that specified with -o ...
file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'`
if test -z "$file"; then
# ... or it is the one specified with @setfilename ...
infile=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'`
file=`sed -n '/^@setfilename/ { s/.* \([^ ]*\) *$/\1/; p; q; }' $infile`
# ... or it is derived from the source name (dir/f.texi becomes f.info)
test -z "$file" && file=`echo "$infile" | sed 's,.*/,,;s,.[^.]*$,,'`.info
fi
# If the file does not exist, the user really needs makeinfo;
# let's fail without touching anything.
test -f $file || exit 1
touch $file
;;
tar)
shift
# We have already tried tar in the generic part.
# Look for gnutar/gtar before invocation to avoid ugly error
# messages.
if (gnutar --version > /dev/null 2>&1); then
gnutar "$@" && exit 0
fi
if (gtar --version > /dev/null 2>&1); then
gtar "$@" && exit 0
fi
firstarg="$1"
if shift; then
case "$firstarg" in
*o*)
firstarg=`echo "$firstarg" | sed s/o//`
tar "$firstarg" "$@" && exit 0
;;
esac
case "$firstarg" in
*h*)
firstarg=`echo "$firstarg" | sed s/h//`
tar "$firstarg" "$@" && exit 0
;;
esac
fi
echo 1>&2 "\
WARNING: I can't seem to be able to run \`tar' with the given arguments.
You may want to install GNU tar or Free paxutils, or check the
command line arguments."
exit 1
;;
*)
echo 1>&2 "\
WARNING: \`$1' is needed, and is $msg.
You might have modified some files without having the
proper tools for further handling them. Check the \`README' file,
it often tells you about the needed prerequisites for installing
this package. You may also peek at any GNU archive site, in case
some other package would contain this missing \`$1' program."
exit 1
;;
esac
exit 0
# Local variables:
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-end: "$"
# End:
| zz1126wnx-iperf3 | config/missing | Shell | bsd | 11,014 |
# ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_lib_socket_nsl.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_LIB_SOCKET_NSL
#
# DESCRIPTION
#
# This macro figures out what libraries are required on this platform to
# link sockets programs.
#
# The common cases are not to need any extra libraries, or to need
# -lsocket and -lnsl. We need to avoid linking with libnsl unless we need
# it, though, since on some OSes where it isn't necessary it will totally
# break networking. Unisys also includes gethostbyname() in libsocket but
# needs libnsl for socket().
#
# LICENSE
#
# Copyright (c) 2008 Russ Allbery <rra@stanford.edu>
# Copyright (c) 2008 Stepan Kasal <kasal@ucw.cz>
# Copyright (c) 2008 Warren Young <warren@etr-usa.com>
#
# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided the copyright notice
# and this notice are preserved. This file is offered as-is, without any
# warranty.
#serial 6
AU_ALIAS([LIB_SOCKET_NSL], [AX_LIB_SOCKET_NSL])
AC_DEFUN([AX_LIB_SOCKET_NSL],
[
AC_SEARCH_LIBS([gethostbyname], [nsl])
AC_SEARCH_LIBS([socket], [socket], [], [
AC_CHECK_LIB([socket], [socket], [LIBS="-lsocket -lnsl $LIBS"],
[], [-lnsl])])
])
| zz1126wnx-iperf3 | config/ax_lib_socket_nsl.m4 | M4Sugar | bsd | 1,396 |
#!/bin/sh
# install - install a program, script, or datafile
scriptversion=2005-05-14.22
# This originates from X11R5 (mit/util/scripts/install.sh), which was
# later released in X11R6 (xc/config/util/install.sh) with the
# following copyright and license.
#
# Copyright (C) 1994 X Consortium
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Except as contained in this notice, the name of the X Consortium shall not
# be used in advertising or otherwise to promote the sale, use or other deal-
# ings in this Software without prior written authorization from the X Consor-
# tium.
#
#
# FSF changes to this file are in the public domain.
#
# Calling this script install-sh is preferred over install.sh, to prevent
# `make' implicit rules from creating a file called install from it
# when there is no Makefile.
#
# This script is compatible with the BSD install script, but was written
# from scratch. It can only install one file at a time, a restriction
# shared with many OS's install programs.
# set DOITPROG to echo to test this script
# Don't use :- since 4.3BSD and earlier shells don't like it.
doit="${DOITPROG-}"
# put in absolute paths if you don't have them in your path; or use env. vars.
mvprog="${MVPROG-mv}"
cpprog="${CPPROG-cp}"
chmodprog="${CHMODPROG-chmod}"
chownprog="${CHOWNPROG-chown}"
chgrpprog="${CHGRPPROG-chgrp}"
stripprog="${STRIPPROG-strip}"
rmprog="${RMPROG-rm}"
mkdirprog="${MKDIRPROG-mkdir}"
chmodcmd="$chmodprog 0755"
chowncmd=
chgrpcmd=
stripcmd=
rmcmd="$rmprog -f"
mvcmd="$mvprog"
src=
dst=
dir_arg=
dstarg=
no_target_directory=
usage="Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
or: $0 [OPTION]... SRCFILES... DIRECTORY
or: $0 [OPTION]... -t DIRECTORY SRCFILES...
or: $0 [OPTION]... -d DIRECTORIES...
In the 1st form, copy SRCFILE to DSTFILE.
In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
In the 4th, create DIRECTORIES.
Options:
-c (ignored)
-d create directories instead of installing files.
-g GROUP $chgrpprog installed files to GROUP.
-m MODE $chmodprog installed files to MODE.
-o USER $chownprog installed files to USER.
-s $stripprog installed files.
-t DIRECTORY install into DIRECTORY.
-T report an error if DSTFILE is a directory.
--help display this help and exit.
--version display version info and exit.
Environment variables override the default commands:
CHGRPPROG CHMODPROG CHOWNPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG
"
while test -n "$1"; do
case $1 in
-c) shift
continue;;
-d) dir_arg=true
shift
continue;;
-g) chgrpcmd="$chgrpprog $2"
shift
shift
continue;;
--help) echo "$usage"; exit $?;;
-m) chmodcmd="$chmodprog $2"
shift
shift
continue;;
-o) chowncmd="$chownprog $2"
shift
shift
continue;;
-s) stripcmd=$stripprog
shift
continue;;
-t) dstarg=$2
shift
shift
continue;;
-T) no_target_directory=true
shift
continue;;
--version) echo "$0 $scriptversion"; exit $?;;
*) # When -d is used, all remaining arguments are directories to create.
# When -t is used, the destination is already specified.
test -n "$dir_arg$dstarg" && break
# Otherwise, the last argument is the destination. Remove it from $@.
for arg
do
if test -n "$dstarg"; then
# $@ is not empty: it contains at least $arg.
set fnord "$@" "$dstarg"
shift # fnord
fi
shift # arg
dstarg=$arg
done
break;;
esac
done
if test -z "$1"; then
if test -z "$dir_arg"; then
echo "$0: no input file specified." >&2
exit 1
fi
# It's OK to call `install-sh -d' without argument.
# This can happen when creating conditional directories.
exit 0
fi
for src
do
# Protect names starting with `-'.
case $src in
-*) src=./$src ;;
esac
if test -n "$dir_arg"; then
dst=$src
src=
if test -d "$dst"; then
mkdircmd=:
chmodcmd=
else
mkdircmd=$mkdirprog
fi
else
# Waiting for this to be detected by the "$cpprog $src $dsttmp" command
# might cause directories to be created, which would be especially bad
# if $src (and thus $dsttmp) contains '*'.
if test ! -f "$src" && test ! -d "$src"; then
echo "$0: $src does not exist." >&2
exit 1
fi
if test -z "$dstarg"; then
echo "$0: no destination specified." >&2
exit 1
fi
dst=$dstarg
# Protect names starting with `-'.
case $dst in
-*) dst=./$dst ;;
esac
# If destination is a directory, append the input filename; won't work
# if double slashes aren't ignored.
if test -d "$dst"; then
if test -n "$no_target_directory"; then
echo "$0: $dstarg: Is a directory" >&2
exit 1
fi
dst=$dst/`basename "$src"`
fi
fi
# This sed command emulates the dirname command.
dstdir=`echo "$dst" | sed -e 's,/*$,,;s,[^/]*$,,;s,/*$,,;s,^$,.,'`
# Make sure that the destination directory exists.
# Skip lots of stat calls in the usual case.
if test ! -d "$dstdir"; then
defaultIFS='
'
IFS="${IFS-$defaultIFS}"
oIFS=$IFS
# Some sh's can't handle IFS=/ for some reason.
IFS='%'
set x `echo "$dstdir" | sed -e 's@/@%@g' -e 's@^%@/@'`
shift
IFS=$oIFS
pathcomp=
while test $# -ne 0 ; do
pathcomp=$pathcomp$1
shift
if test ! -d "$pathcomp"; then
$mkdirprog "$pathcomp"
# mkdir can fail with a `File exist' error in case several
# install-sh are creating the directory concurrently. This
# is OK.
test -d "$pathcomp" || exit
fi
pathcomp=$pathcomp/
done
fi
if test -n "$dir_arg"; then
$doit $mkdircmd "$dst" \
&& { test -z "$chowncmd" || $doit $chowncmd "$dst"; } \
&& { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } \
&& { test -z "$stripcmd" || $doit $stripcmd "$dst"; } \
&& { test -z "$chmodcmd" || $doit $chmodcmd "$dst"; }
else
dstfile=`basename "$dst"`
# Make a couple of temp file names in the proper directory.
dsttmp=$dstdir/_inst.$$_
rmtmp=$dstdir/_rm.$$_
# Trap to clean up those temp files at exit.
trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
trap '(exit $?); exit' 1 2 13 15
# Copy the file name to the temp name.
$doit $cpprog "$src" "$dsttmp" &&
# and set any options; do chmod last to preserve setuid bits.
#
# If any of these fail, we abort the whole thing. If we want to
# ignore errors from any of these, just make sure not to ignore
# errors from the above "$doit $cpprog $src $dsttmp" command.
#
{ test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } \
&& { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } \
&& { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } \
&& { test -z "$chmodcmd" || $doit $chmodcmd "$dsttmp"; } &&
# Now rename the file to the real destination.
{ $doit $mvcmd -f "$dsttmp" "$dstdir/$dstfile" 2>/dev/null \
|| {
# The rename failed, perhaps because mv can't rename something else
# to itself, or perhaps because mv is so ancient that it does not
# support -f.
# Now remove or move aside any old file at destination location.
# We try this two ways since rm can't unlink itself on some
# systems and the destination file might be busy for other
# reasons. In this case, the final cleanup might fail but the new
# file should still install successfully.
{
if test -f "$dstdir/$dstfile"; then
$doit $rmcmd -f "$dstdir/$dstfile" 2>/dev/null \
|| $doit $mvcmd -f "$dstdir/$dstfile" "$rmtmp" 2>/dev/null \
|| {
echo "$0: cannot unlink or rename $dstdir/$dstfile" >&2
(exit 1); exit 1
}
else
:
fi
} &&
# Now rename the file to the real destination.
$doit $mvcmd "$dsttmp" "$dstdir/$dstfile"
}
}
fi || { (exit 1); exit 1; }
done
# The final little trick to "correctly" pass the exit status to the exit trap.
{
(exit 0); exit 0
}
# Local variables:
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-end: "$"
# End:
| zz1126wnx-iperf3 | config/install-sh | Shell | bsd | 9,233 |
#!/bin/sh
proj="iperf"
tag=`awk '/IPERF_VERSION / {
gsub(/"/, "", $3);
print $3 }' src/version.h`
dirname=`echo $tag $proj | awk '{
gsub(/-ALPHA/, "a", $1);
gsub(/-BETA/, "b", $1);
gsub(/-RELEASE/, "", $1);
print $2"-"$1 }'`
echo tag $tag
echo dirname $dirname
do_tag ()
{
hg tag -m "tagging $tag" $tag
}
do_tar ()
{
tarball=${dirname}.tar.gz
hg archive -t tgz -p ${dirname} -X make_release -X .hgtags -r ${tag} ${tarball}
}
usage ()
{
cat <<EOF
$0: tag|tar
tag -- create a tag using the contents of src/version.h
tar -- create a tarball of the current tag
General use is to do:
./$0 tag
./$0 tar
EOF
}
case $1 in
tag) do_tag ;;
tar) do_tar ;;
*) echo "unknown command: $1"; usage ;;
esac
exit
| zz1126wnx-iperf3 | make_release | Shell | bsd | 754 |
using System.Windows;
using System;
namespace LiveSearch_Parks
{
public partial class App : Application
{
// this will hold our Live Search API Id and is accessible globally
public static string _MSNSearchAppId;
// this will hold our Virtual Earth token and is accessible globally
public static string _virtualEarthToken;
// --------------------------
public App()
{
this.Startup += this.OnStartup;
this.Exit += this.OnExit;
this.UnhandledException += this.Application_UnhandledException;
InitializeComponent();
}
private void OnStartup(object sender, StartupEventArgs e)
{
// Load the main control here
this.RootVisual = new Page();
// InitParams are sent in from the .aspx page
_MSNSearchAppId = e.InitParams["MSNSearchAppID"];
_virtualEarthToken = e.InitParams["clientToken"];
// ------------
}
private void OnExit(object sender, EventArgs e)
{
}
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
// If the app is running outside of the debugger then report the exception using
// the browser's exception mechanism. On IE this will display it a yellow alert
// icon in the status bar and Firefox will display a script error.
if (!System.Diagnostics.Debugger.IsAttached)
{
// NOTE: This will allow the application to continue running after an exception has been thrown
// but not handled.
// For production applications this error handling should be replaced with something that will
// report the error to the website and stop the application.
e.Handled = true;
Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
}
}
private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
{
try
{
string errorMsg = e.ExceptionObject.Message + @"\n" + e.ExceptionObject.StackTrace;
errorMsg = errorMsg.Replace("\"", "\\\"").Replace("\r\n", @"\n");
System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight 2 Application " + errorMsg + "\");");
}
catch (Exception)
{
}
}
}
} | zzihp | trunk/LiveSearch_Parks/LiveSearch_Parks/App.xaml.cs | C# | mit | 2,291 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LiveSearch_Parks")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LiveSearch_Parks")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("48d19969-172f-4838-b7ef-b0e766c92ebb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zzihp | trunk/LiveSearch_Parks/LiveSearch_Parks/Properties/AssemblyInfo.cs | C# | mit | 1,403 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace LiveSearch_Parks
{
public partial class ucPushPin : UserControl
{
bool _enteredPopup = false;
public ucPushPin()
{
InitializeComponent();
// we want to initially hide the popup
cnvPopup.Visibility = Visibility.Collapsed;
}
private void Group_1_MouseEnter(object sender, MouseEventArgs e)
{
// we want to force all other children in the canvas to the back
foreach (ucPushPin pin in (this.Parent as Canvas).Children)
{
pin.SetValue(Canvas.ZIndexProperty, 0);
pin.cnvPopup.Visibility = Visibility.Collapsed;
}
cnvPopup.Visibility = Visibility.Visible;
this.SetValue(Canvas.ZIndexProperty, 1000);
}
private void cnvPopup_MouseEnter(object sender, MouseEventArgs e)
{
_enteredPopup = true;
}
private void Group_1_MouseLeave(object sender, MouseEventArgs e)
{
if (!_enteredPopup)
cnvPopup.Visibility = Visibility.Collapsed;
}
private void cnvPopup_MouseLeave(object sender, MouseEventArgs e)
{
cnvPopup.Visibility = Visibility.Collapsed;
_enteredPopup = false;
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
cnvPopup.Visibility = Visibility.Collapsed;
_enteredPopup = false;
}
}
}
| zzihp | trunk/LiveSearch_Parks/LiveSearch_Parks/ucPushPin.xaml.cs | C# | mit | 1,880 |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Windows.Media.Imaging;
using LiveSearch_Parks.MSN_SearchLiveService;
namespace LiveSearch_Parks
{
public partial class Page : UserControl
{
public Page()
{
// Required to initialize variables
InitializeComponent();
}
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
DoSearch();
}
// put this in after the Page : UserControl declaration
// these constants determine the State for keyword search, and center position of the map.
private const string _searchState = "California";
private const double _searchStateLatitude = 37.387617;
private const double _searchStateLongitude = -119.893799;
// put this in after the Page { } constructor
private string GetSearchString()
{
string searchString = _searchState + " parks ";
if (cbxBike.IsChecked.Value == true)
searchString += "bike ";
if (cbxCamp.IsChecked.Value == true)
searchString += "camp ";
if (cbxBoat.IsChecked.Value == true)
searchString += "boat ";
if (cbxHike.IsChecked.Value == true)
searchString += "hike ";
if (txtTown.Text.Trim().Length > 0)
searchString += txtTown.Text;
return searchString;
}
private void DoSearch()
{
sbBusy.Begin();
// initiate a Live Search request
MSN_SearchLiveService.MSNSearchPortTypeClient s = new MSNSearchPortTypeClient();
s.SearchCompleted += new EventHandler<SearchCompletedEventArgs>(s_SearchCompleted);
SearchRequest searchRequest = new SearchRequest();
int arraySize = 2;
SourceRequest[] sr = new SourceRequest[arraySize];
if (cbxWebPages.IsChecked.Value)
{
sr[0] = new SourceRequest();
sr[0].Source = SourceType.Web;
}
if (cbxImages.IsChecked.Value)
{
sr[1] = new SourceRequest();
sr[1].Source = SourceType.Image;
sr[1].ResultFields = ResultFieldMask.Image | ResultFieldMask.Url;
}
searchRequest.Query = GetSearchString();
searchRequest.Requests = sr;
searchRequest.AppID = App._MSNSearchAppId;
searchRequest.CultureInfo = "en-US";
s.SearchAsync(searchRequest);
}
/// <summary>
/// Defines a search result from Web Page, Image, or Map (used for binding)
/// </summary>
public class SearchResult
{
public int HitNumber { get; set; }
public string ResultUrl { get; set; }
public string ImageUrl { get; set; }
public string Description { get; set; }
public double ImageHeight { get; set; }
public double ImageWidth { get; set; }
}
void s_SearchCompleted(object sender, SearchCompletedEventArgs e)
{
// hide the busy status
sbBusy.Stop();
// clear out any existing hits
int totalHits = 0;
lstResults.ItemsSource = null;
stkImages.Children.Clear();
List<SearchResult> lstWebPages = new List<SearchResult>();
if (e.Error != null)
{
System.Windows.Browser.HtmlPage.Window.Alert("There was a problem contacting the Live Search Server:\n\n" + e.Error.Message + "\n\nUsing Test images only.");
return;
}
foreach (SourceResponse sourceResponse in e.Result.Responses)
{
Result[] sourceResults = sourceResponse.Results;
if (sourceResponse.Total > 0)
{
foreach (Result x in sourceResults)
{
if (x.Image != null && cbxImages.IsChecked.Value)
{
System.Windows.Controls.Image img = new System.Windows.Controls.Image();
img.Height = 100;
img.Margin = new Thickness(5, 0, 5, 0);
Uri ImageUri = new Uri(x.Image.ImageURL, UriKind.Absolute);
ImageSource imgSrc = new System.Windows.Media.Imaging.BitmapImage(ImageUri);
img.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(img_ImageFailed);
img.SetValue(System.Windows.Controls.Image.SourceProperty, imgSrc);
stkImages.Children.Add(img);
totalHits += 1;
}
else
if (cbxWebPages.IsChecked.Value)
{
// web page hit
SearchResult result = new SearchResult();
result.ResultUrl = x.Url;
result.Description = x.Description;
lstWebPages.Add(result);
totalHits += 1;
}
}
}
if (lstResults.Items.Count > 0)
lstResults.SelectedIndex = 0;
if (totalHits == 0)
System.Windows.Browser.HtmlPage.Window.Alert("There were no Web Page or Image results found for your query.");
}
lstResults.ItemsSource = lstWebPages;
//A function to add when you do Virtual Earth
DoMapSearch();
}
void img_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
// by handling this event, we avoid errors when images are not found on web
}
// TODO: Enter DoMapSearch code below!
private void DoMapSearch()
{
// initiates a Virtual Earth Keyword type search
// show the busy status
sbBusy.Begin();
VirtualEarthSearchService.SearchRequest searchRequest = new VirtualEarthSearchService.SearchRequest();
lstResultsMap.ItemsSource = null;
imgMap.Source = null;
// Set the credentials using a valid Virtual Earth token
searchRequest.Credentials = new VirtualEarthSearchService.Credentials();
searchRequest.Credentials.Token = App._virtualEarthToken;
VirtualEarthSearchService.StructuredSearchQuery ssQuery = new VirtualEarthSearchService.StructuredSearchQuery();
ssQuery.Keyword = GetSearchString();
if (txtTown.Text.Trim().Length > 0)
ssQuery.Location = txtTown.Text + ", ";
ssQuery.Location += _searchState;
searchRequest.StructuredQuery = ssQuery;
searchRequest.SearchOptions = new VirtualEarthSearchService.SearchOptions();
searchRequest.SearchOptions.Count = 9;
// Make the search request
VirtualEarthSearchService.SearchServiceClient searchService = new VirtualEarthSearchService.SearchServiceClient();
searchService.SearchCompleted += new EventHandler<LiveSearch_Parks.VirtualEarthSearchService.SearchCompletedEventArgs>(MapSearch_SearchCompleted);
searchService.SearchAsync(searchRequest);
}
void MapSearch_SearchCompleted(object sender, LiveSearch_Parks.VirtualEarthSearchService.SearchCompletedEventArgs e)
{
// The result is a SearchResponse Object
VirtualEarthSearchService.SearchResponse searchResponse = e.Result;
List<SearchResult> lstMapResults = new List<SearchResult>();
cnvMap.Children.Clear();
if (searchResponse.ResultSets[0].Results.Count > 0)
{
// request a map image for these hits with pushpins
ImageryService.MapUriRequest mapUriRequest = new ImageryService.MapUriRequest();
lstResultsMap.ItemsSource = null;
// Set credentials using a valid Virtual Earth Token
mapUriRequest.Credentials = new ImageryService.Credentials();
mapUriRequest.Credentials.Token = App._virtualEarthToken;
// Set the map style and zoom level
ImageryService.MapUriOptions mapUriOptions = new ImageryService.MapUriOptions();
mapUriOptions.Style = ImageryService.MapStyle.Road; // ImageryService.MapStyle.AerialWithLabels;
mapUriOptions.ZoomLevel = 5;
// Set the size of the requested image to match the size of the image control
mapUriOptions.ImageSize = new ImageryService.SizeOfint();
mapUriOptions.ImageSize.Height = (int)imgMap.Height;
mapUriOptions.ImageSize.Width = (int)imgMap.Width;
mapUriRequest.Options = mapUriOptions;
int totalHits = 0;
foreach (LiveSearch_Parks.VirtualEarthSearchService.BusinessSearchResult result in searchResponse.ResultSets[0].Results)
{
SearchResult searchHit = new SearchResult();
searchHit.HitNumber = totalHits + 1;
searchHit.Description = result.Name;
if (result.Website != null)
searchHit.ResultUrl = result.Website.ToString();
lstMapResults.Add(searchHit);
// add the client side pushpin
ucPushPin ucPushPinNew = new ucPushPin();
Point ptPin = LatLongToPixelXY(_searchStateLatitude, _searchStateLongitude, result.LocationData.Locations[0].Latitude, result.LocationData.Locations[0].Longitude, mapUriOptions.ZoomLevel.Value);
if (ptPin.X < cnvMap.Width - ucPushPinNew.Width && ptPin.Y < cnvMap.Height - ucPushPinNew.Height)
{
ucPushPinNew.SetValue(Canvas.LeftProperty, Convert.ToDouble(ptPin.X));
ucPushPinNew.SetValue(Canvas.TopProperty, Convert.ToDouble(ptPin.Y));
ucPushPinNew.SetValue(Canvas.ZIndexProperty, 1000);
if (searchHit.ResultUrl != null)
{
ucPushPinNew.lnkUrl.NavigateUri = new Uri(searchHit.ResultUrl, UriKind.Absolute);
ucPushPinNew.lnkUrl.Content = searchHit.ResultUrl;
}
ucPushPinNew.txtDescription.Text = searchHit.Description;
cnvMap.Children.Add(ucPushPinNew);
}
totalHits++;
}
// Set the location of the requested image
mapUriRequest.Center = new ImageryService.Location();
mapUriRequest.Center.Latitude = _searchStateLatitude;
mapUriRequest.Center.Longitude = _searchStateLongitude;
ImageryService.ImageryServiceClient imageryService = new ImageryService.ImageryServiceClient();
imageryService.GetMapUriCompleted += new EventHandler<LiveSearch_Parks.ImageryService.GetMapUriCompletedEventArgs>(imageryService_GetMapUriCompleted);
imageryService.GetMapUriAsync(mapUriRequest);
lstResultsMap.ItemsSource = lstMapResults;
}
else
System.Windows.Browser.HtmlPage.Window.Alert("There were no Map results found for your query.");
// hide the busy status
sbBusy.Stop();
}
void imageryService_GetMapUriCompleted(object sender, LiveSearch_Parks.ImageryService.GetMapUriCompletedEventArgs e)
{
// this is the callback handler, executed when the GetMapUri asynchronous call completes
// The result is an MapUriResponse Object
ImageryService.MapUriResponse mapUriResponse = e.Result;
//Note that we have to replace the {token} value in the image Uri
BitmapImage bmpImg = new BitmapImage(new Uri(
mapUriResponse.Uri.Replace("{token}", App._virtualEarthToken)));
imgMap.Source = bmpImg;
}
/// <summary>
/// Converts a point from latitude/longitude WGS-84 coordinates (in degrees)
/// into pixel XY coordinates at a specified level of detail.
/// </summary>
/// <param name="latitude">Latitude of the point, in degrees.</param>
/// <param name="longitude">Longitude of the point, in degrees.</param>
/// <param name="levelOfDetail">Level of detail, from 1 (lowest detail)
/// to 23 (highest detail).</param>
/// <param name="pixelX">Output parameter receiving the X coordinate in pixels.</param>
/// <param name="pixelY">Output parameter receiving the Y coordinate in pixels.</param>
public Point LatLongToPixelXY(double centerLatitude, double centerLongitude, double latitude, double longitude, int levelOfDetail)
{
double metersPerPixel = Math.Abs(156543.04 * Math.Cos(centerLatitude) / (Math.Pow(2, levelOfDetail + 1)));
double x = centerLongitude - (MetersToDecimalDegrees(metersPerPixel * imgMap.Width / 2));
double y = centerLatitude + (MetersToDecimalDegrees(metersPerPixel * imgMap.Height / 2));
double width = MetersToDecimalDegrees(metersPerPixel * (imgMap.Width));
double height = MetersToDecimalDegrees(metersPerPixel * (imgMap.Height));
return ToPagePoint(longitude, latitude, x, y, width, height, imgMap);
}
/// <summary>
/// Converts lat/long position on a map to a pixel x,y position on the screen
/// </summary>
/// <param name="mapX">The longitude</param>
/// <param name="mapY">The latitude</param>
/// <returns></returns>
public static Point ToPagePoint(double mapX, double mapY, double mapLeft, double mapTop, double mapWidth, double mapHeight, System.Windows.Controls.Image mapImage)
{
double diffX, diffY;
diffX = (mapX - mapLeft);
diffY = (mapTop - mapY);
double iX = (diffX / mapWidth) * mapImage.Width;
double iY = (diffY / mapHeight) * mapImage.Height;
return new Point(iX, iY);
}
/// <summary>
/// Gets a value in decimal degrees equal to the number of meters passed in
/// </summary>
public static double MetersToDecimalDegrees(double meters)
{
double degrees = meters * .00001 / 0.676656;
return degrees;
}
}
} | zzihp | trunk/LiveSearch_Parks/LiveSearch_Parks/Page.xaml.cs | C# | mit | 15,456 |
#sidebar {
width: 150px;
}
p.MsoNormal
{margin-bottom:.0001pt;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
margin-left: 0in;
margin-right: 0in;
margin-top: 0in;
}
p.MsoListParagraph
{margin-top:0in;
margin-right:0in;
margin-bottom:0in;
margin-left:.5in;
margin-bottom:.0001pt;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
color: black;
}
#sidebar_top {
font-family: Calibri;
color: #FFFFFF;
background-color: #000000;
text-align: center;
}
#container {
width: 960px;
}
#LiveSearch_App {
width: 790px;
height: 600px;
float: right;
}
| zzihp | trunk/LiveSearch_Parks/LiveSearch_Parks.Web/global.css | CSS | mit | 622 |
<%@ Page Language="c#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Web.UI.SilverlightControls" %>
<%@ Import Namespace="LiveSearch_Parks.Web.net.virtualearth.common.staging" %>
<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"
TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
// set up the login credentials for Live Search API and Virtual Earth
// it is best to limit exposure of these on client side!
string MSNSearchAppID = "2E08617E619A56E62BDB7525108FCD110553A819";
string virtualEarthAccountID = "136035";
string virtualEarthPassword = "V1rtual!";
CommonService commonService = new CommonService();
commonService.Url =
"https://staging.common.virtualearth.net/find-30/common.asmx";
commonService.Credentials = new System.Net.NetworkCredential(virtualEarthAccountID,
virtualEarthPassword);
// Create the TokenSpecification object to pass to GetClientToken.
TokenSpecification tokenSpec = new TokenSpecification();
// Use the ‘Page’ object to retrieve the end-client’s IPAddress.
tokenSpec.ClientIPAddress = Page.Request.UserHostAddress;
// The maximum allowable token duration is 480 minutes (8 hours).
// The minimum allowable duration is 15 minutes.
tokenSpec.TokenValidityDurationMinutes = 480;
// Now get a token from the Virtual Earth Platform service
string veToken = commonService.GetClientToken(tokenSpec);
// and pass it to the Silverlight control
System.Web.UI.SilverlightControls.Silverlight Xaml1 = (System.Web.UI.SilverlightControls.Silverlight)this.FindControl("Xaml1");
Xaml1.InitParameters = "clientToken=" + veToken + ",MSNSearchAppID=" + MSNSearchAppID;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;">
<head runat="server">
<title>Global Electronics - Parks & Recreation Search</title>
<link href="global.css" rel="stylesheet" type="text/css">
</style>
</head>
<body style="height:100%;margin:0;">
<div id="container">
<div id="LiveSearch_App">
<form id="form1" runat="server" style="height:100%;">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div style="height:100%;">
<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/LiveSearch_Parks.xap" MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />
</div>
</form>
</div>
<div id="sidebar">
<div id="sidebar_top" style="height: 63px">
Global Electronics<br />
Healthpage</div>
<p class="MsoNormal">
<span style="color: #008000; font-size: x-large; font-weight: normal">
Get Healthy</span></p>
<p class="MsoNormal">
<span style="color: #008000; font-size: x-large; font-weight: bold">
Enjoy the Outdoors</span></p>
<p class="MsoNormal">
<span style="color: #000000">At Global Electronics we
want employees, and visitors, at our corporate offices to enjoy the
great outdoors. </span></p>
<p class="MsoNormal">
<span style="color: #000000">We have created the California Park Finder to locate
the outdoor activities that meet your needs and fit your lifestyle.</span></p>
<p class="MsoListParagraph" style="text-indent: -.25in; margin-left: 0.25in;">
<span style=" color: #000000">
<span style="">1.<span style="font: 7.0pt;">
</span></span></span><span style="color: #000000">Click
the icons that represents the activities you would like to locate.</span></p>
<p class="MsoListParagraph" style="text-indent: -.25in; margin-left: 0.25in;">
<span style=" color: #000000">
<span style="">2.<span style="font: 7.0pt;">
</span></span></span><span style="color: #000000">Press
the Go button</span></p>
<p class="MsoListParagraph" style="text-indent: -.25in; margin-left: 0.25in; color: #000000">
<span style=" color: #000000">
<span style="">3.<span style="font: 7.0pt;">
</span></span></span><span style="color: #000000">Use the
results and map to find a great location to enjoy!</span></p>
</div>
</div>
</body>
</html> | zzihp | trunk/LiveSearch_Parks/LiveSearch_Parks.Web/LiveSearch_ParksTestPage.aspx | ASP.NET | mit | 4,560 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<!-- saved from url=(0014)about:internet -->
<head>
<title>LiveSearch_Parks</title>
<style type="text/css">
html, body {
height: 100%;
overflow: auto;
}
body {
padding: 0;
margin: 0;
}
#silverlightControlHost {
height: 100%;
}
</style>
<script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript">
function onSilverlightError(sender, args) {
var appSource = "";
if (sender != null && sender != 0) {
appSource = sender.getHost().Source;
}
var errorType = args.ErrorType;
var iErrorCode = args.ErrorCode;
var errMsg = "Unhandled Error in Silverlight 2 Application " + appSource + "\n" ;
errMsg += "Code: "+ iErrorCode + " \n";
errMsg += "Category: " + errorType + " \n";
errMsg += "Message: " + args.ErrorMessage + " \n";
if (errorType == "ParserError")
{
errMsg += "File: " + args.xamlFile + " \n";
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
else if (errorType == "RuntimeError")
{
if (args.lineNumber != 0)
{
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
errMsg += "MethodName: " + args.methodName + " \n";
}
throw new Error(errMsg);
}
</script>
</head>
<body>
<!-- Runtime errors from Silverlight will be displayed here.
This will contain debugging information and should be removed or hidden when debugging is completed -->
<div id='errorLocation' style="font-size: small;color: Gray;"></div>
<div id="silverlightControlHost">
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value="ClientBin/LiveSearch_Parks.xap"/>
<param name="onerror" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="2.0.31005.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
</a>
</object>
<iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>
</div>
</body>
</html>
| zzihp | trunk/LiveSearch_Parks/LiveSearch_Parks.Web/LiveSearch_ParksTestPage.html | HTML | mit | 2,977 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Global Electronics Healthpage</title>
<style type="text/css">
#sidebar {
width: 150px;
}
p.MsoNormal
{margin-bottom:.0001pt;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
margin-left: 0in;
margin-right: 0in;
margin-top: 0in;
}
p.MsoListParagraph
{margin-top:0in;
margin-right:0in;
margin-bottom:0in;
margin-left:.5in;
margin-bottom:.0001pt;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
color: black;
}
#sidebar_top {
font-family: Calibri;
color: #FFFFFF;
background-color: #000000;
text-align: center;
}
#container {
width: 960px;
}
#LiveSearch_App {
width: 790px;
height: 600px;
float: right;
}
</style>
</head>
<body>
<div id="container">
<div id="LiveSearch_App">
</div>
<div id="sidebar">
<div id="sidebar_top" style="height: 63px">
Global Electronics<br />
Healthpage</div>
<p class="MsoNormal">
<span style="color: #008000; font-size: x-large; font-weight: normal">
Get Healthy</span></p>
<p class="MsoNormal">
<span style="color: #008000; font-size: x-large; font-weight: bold">
Enjoy the Outdoors</span></p>
<p class="MsoNormal">
<span style="color: #000000">At Global Electronics we
want employees, and visitors, at our corporate offices to enjoy the
great outdoors. </span></p>
<p class="MsoNormal">
<span style="color: #000000">We have created the California Park Finder to locate
the outdoor activities that meet your needs and fit your lifestyle.</span></p>
<p class="MsoListParagraph" style="text-indent: -.25in; margin-left: 0.25in;">
<span style=" color: #000000">
<span style="">1.<span style="font: 7.0pt;">
</span></span></span><span style="color: #000000">Click
the icons that represents the activities you would like to locate.</span></p>
<p class="MsoListParagraph" style="text-indent: -.25in; margin-left: 0.25in;">
<span style=" color: #000000">
<span style="">2.<span style="font: 7.0pt;">
</span></span></span><span style="color: #000000">Press
the Where Can I Go button</span></p>
<p class="MsoListParagraph" style="text-indent: -.25in; margin-left: 0.25in; color: #000000">
<span style=" color: #000000">
<span style="">3.<span style="font: 7.0pt;">
</span></span></span><span style="color: #000000">Use the
results and map to find a great location to enjoy!</span></p>
</div>
</div>
</body>
</html>
| zzihp | trunk/LiveSearch_Parks/LiveSearch_Parks.Web/global_electronics_healthpage.html | HTML | mit | 2,862 |
if (!window.Silverlight)
{
window.Silverlight = { };
}
// Silverlight control instance counter for memory mgt
Silverlight._silverlightCount = 0;
Silverlight.fwlinkRoot='http://go2.microsoft.com/fwlink/?LinkID=';
Silverlight.onGetSilverlight = null;
Silverlight.onSilverlightInstalled = function () {window.location.reload(false);};
//////////////////////////////////////////////////////////////////
// isInstalled, checks to see if the correct version is installed
//////////////////////////////////////////////////////////////////
Silverlight.isInstalled = function(version)
{
var isVersionSupported=false;
var container = null;
try
{
var control = null;
try
{
control = new ActiveXObject('AgControl.AgControl');
if ( version == null )
{
isVersionSupported = true;
}
else if ( control.IsVersionSupported(version) )
{
isVersionSupported = true;
}
control = null;
}
catch (e)
{
var plugin = navigator.plugins["Silverlight Plug-In"] ;
if ( plugin )
{
if ( version === null )
{
isVersionSupported = true;
}
else
{
var actualVer = plugin.description;
if ( actualVer === "1.0.30226.2")
actualVer = "2.0.30226.2";
var actualVerArray =actualVer.split(".");
while ( actualVerArray.length > 3)
{
actualVerArray.pop();
}
while ( actualVerArray.length < 4)
{
actualVerArray.push(0);
}
var reqVerArray = version.split(".");
while ( reqVerArray.length > 4)
{
reqVerArray.pop();
}
var requiredVersionPart ;
var actualVersionPart
var index = 0;
do
{
requiredVersionPart = parseInt(reqVerArray[index]);
actualVersionPart = parseInt(actualVerArray[index]);
index++;
}
while (index < reqVerArray.length && requiredVersionPart === actualVersionPart);
if ( requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart) )
{
isVersionSupported = true;
}
}
}
}
}
catch (e)
{
isVersionSupported = false;
}
if (container)
{
document.body.removeChild(container);
}
return isVersionSupported;
}
Silverlight.WaitForInstallCompletion = function()
{
if ( ! Silverlight.isBrowserRestartRequired && Silverlight.onSilverlightInstalled )
{
try
{
navigator.plugins.refresh();
}
catch(e)
{
}
if ( Silverlight.isInstalled(null) )
{
Silverlight.onSilverlightInstalled();
}
else
{
setTimeout(Silverlight.WaitForInstallCompletion, 3000);
}
}
}
Silverlight.__startup = function()
{
Silverlight.isBrowserRestartRequired = Silverlight.isInstalled(null);//(!window.ActiveXObject || Silverlight.isInstalled(null));
if ( !Silverlight.isBrowserRestartRequired)
{
Silverlight.WaitForInstallCompletion();
}
if (window.removeEventListener) {
window.removeEventListener('load', Silverlight.__startup , false);
}
else {
window.detachEvent('onload', Silverlight.__startup );
}
}
if (window.addEventListener)
{
window.addEventListener('load', Silverlight.__startup , false);
}
else
{
window.attachEvent('onload', Silverlight.__startup );
}
///////////////////////////////////////////////////////////////////////////////
// createObject(); Params:
// parentElement of type Element, the parent element of the Silverlight Control
// source of type String
// id of type string
// properties of type String, object literal notation { name:value, name:value, name:value},
// current properties are: width, height, background, framerate, isWindowless, enableHtmlAccess, inplaceInstallPrompt: all are of type string
// events of type String, object literal notation { name:value, name:value, name:value},
// current events are onLoad onError, both are type string
// initParams of type Object or object literal notation { name:value, name:value, name:value}
// userContext of type Object
/////////////////////////////////////////////////////////////////////////////////
Silverlight.createObject = function(source, parentElement, id, properties, events, initParams, userContext)
{
var slPluginHelper = new Object();
var slProperties = properties;
var slEvents = events;
slPluginHelper.version = slProperties.version;
slProperties.source = source;
slPluginHelper.alt = slProperties.alt;
//rename properties to their tag property names
if ( initParams )
slProperties.initParams = initParams;
if ( slProperties.isWindowless && !slProperties.windowless)
slProperties.windowless = slProperties.isWindowless;
if ( slProperties.framerate && !slProperties.maxFramerate)
slProperties.maxFramerate = slProperties.framerate;
if ( id && !slProperties.id)
slProperties.id = id;
// remove elements which are not to be added to the instantiation tag
delete slProperties.ignoreBrowserVer;
delete slProperties.inplaceInstallPrompt;
delete slProperties.version;
delete slProperties.isWindowless;
delete slProperties.framerate;
delete slProperties.data;
delete slProperties.src;
delete slProperties.alt;
// detect that the correct version of Silverlight is installed, else display install
if (Silverlight.isInstalled(slPluginHelper.version))
{
//move unknown events to the slProperties array
for (var name in slEvents)
{
if ( slEvents[name])
{
if ( name == "onLoad" && typeof slEvents[name] == "function" && slEvents[name].length != 1 )
{
var onLoadHandler = slEvents[name];
slEvents[name]=function (sender){ return onLoadHandler(document.getElementById(id), userContext, sender)};
}
var handlerName = Silverlight.__getHandlerName(slEvents[name]);
if ( handlerName != null )
{
slProperties[name] = handlerName;
slEvents[name] = null;
}
else
{
throw "typeof events."+name+" must be 'function' or 'string'";
}
}
}
slPluginHTML = Silverlight.buildHTML(slProperties);
}
//The control could not be instantiated. Show the installation prompt
else
{
slPluginHTML = Silverlight.buildPromptHTML(slPluginHelper);
}
// insert or return the HTML
if(parentElement)
{
parentElement.innerHTML = slPluginHTML;
}
else
{
return slPluginHTML;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// create HTML that instantiates the control
//
///////////////////////////////////////////////////////////////////////////////
Silverlight.buildHTML = function( slProperties)
{
var htmlBuilder = [];
htmlBuilder.push('<object type=\"application/x-silverlight\" data="data:application/x-silverlight,"');
if ( slProperties.id != null )
{
htmlBuilder.push(' id="' + slProperties.id + '"');
}
if ( slProperties.width != null )
{
htmlBuilder.push(' width="' + slProperties.width+ '"');
}
if ( slProperties.height != null )
{
htmlBuilder.push(' height="' + slProperties.height + '"');
}
htmlBuilder.push(' >');
delete slProperties.id;
delete slProperties.width;
delete slProperties.height;
for (var name in slProperties)
{
if (slProperties[name])
{
htmlBuilder.push('<param name="'+Silverlight.HtmlAttributeEncode(name)+'" value="'+Silverlight.HtmlAttributeEncode(slProperties[name])+'" />');
}
}
htmlBuilder.push('<\/object>');
return htmlBuilder.join('');
}
// createObjectEx, takes a single parameter of all createObject parameters enclosed in {}
Silverlight.createObjectEx = function(params)
{
var parameters = params;
var html = Silverlight.createObject(parameters.source, parameters.parentElement, parameters.id, parameters.properties, parameters.events, parameters.initParams, parameters.context);
if (parameters.parentElement == null)
{
return html;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Builds the HTML to prompt the user to download and install Silverlight
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.buildPromptHTML = function(slPluginHelper)
{
var slPluginHTML = "";
var urlRoot = Silverlight.fwlinkRoot;
var shortVer = slPluginHelper.version ;
if ( slPluginHelper.alt )
{
slPluginHTML = slPluginHelper.alt;
}
else
{
if (! shortVer )
{
shortVer="";
}
slPluginHTML = "<a href='javascript:Silverlight.getSilverlight(\"{1}\");' style='text-decoration: none;'><img src='{2}' alt='Get Microsoft Silverlight' style='border-style: none'/></a>";
slPluginHTML = slPluginHTML.replace('{1}', shortVer );
slPluginHTML = slPluginHTML.replace('{2}', urlRoot + '108181');
}
return slPluginHTML;
}
Silverlight.getSilverlight = function(version)
{
if (Silverlight.onGetSilverlight )
{
Silverlight.onGetSilverlight();
}
var shortVer = "";
var reqVerArray = String(version).split(".");
if (reqVerArray.length > 1)
{
var majorNum = parseInt(reqVerArray[0] );
if ( isNaN(majorNum) || majorNum < 2 )
{
shortVer = "1.0";
}
else
{
shortVer = reqVerArray[0]+'.'+reqVerArray[1];
}
}
var verArg = "";
if (shortVer.match(/^\d+\056\d+$/) )
{
verArg = "&v="+shortVer;
}
Silverlight.followFWLink("114576" + verArg);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Navigates to a url based on fwlinkid
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.followFWLink = function(linkid)
{
top.location=Silverlight.fwlinkRoot+String(linkid);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Encodes special characters in input strings as charcodes
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.HtmlAttributeEncode = function( strInput )
{
var c;
var retVal = '';
if(strInput == null)
{
return null;
}
for(var cnt = 0; cnt < strInput.length; cnt++)
{
c = strInput.charCodeAt(cnt);
if (( ( c > 96 ) && ( c < 123 ) ) ||
( ( c > 64 ) && ( c < 91 ) ) ||
( ( c > 43 ) && ( c < 58 ) && (c!=47)) ||
( c == 95 ))
{
retVal = retVal + String.fromCharCode(c);
}
else
{
retVal = retVal + '&#' + c + ';';
}
}
return retVal;
}
///////////////////////////////////////////////////////////////////////////////
//
// Default error handling function to be used when a custom error handler is
// not present
//
///////////////////////////////////////////////////////////////////////////////
Silverlight.default_error_handler = function (sender, args)
{
var iErrorCode;
var errorType = args.ErrorType;
iErrorCode = args.ErrorCode;
var errMsg = "\nSilverlight error message \n" ;
errMsg += "ErrorCode: "+ iErrorCode + "\n";
errMsg += "ErrorType: " + errorType + " \n";
errMsg += "Message: " + args.ErrorMessage + " \n";
if (errorType == "ParserError")
{
errMsg += "XamlFile: " + args.xamlFile + " \n";
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
else if (errorType == "RuntimeError")
{
if (args.lineNumber != 0)
{
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
errMsg += "MethodName: " + args.methodName + " \n";
}
alert (errMsg);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Releases event handler resources when the page is unloaded
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.__cleanup = function ()
{
for (var i = Silverlight._silverlightCount - 1; i >= 0; i--) {
window['__slEvent' + i] = null;
}
Silverlight._silverlightCount = 0;
if (window.removeEventListener) {
window.removeEventListener('unload', Silverlight.__cleanup , false);
}
else {
window.detachEvent('onunload', Silverlight.__cleanup );
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Releases event handler resources when the page is unloaded
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.__getHandlerName = function (handler)
{
var handlerName = "";
if ( typeof handler == "string")
{
handlerName = handler;
}
else if ( typeof handler == "function" )
{
if (Silverlight._silverlightCount == 0)
{
if (window.addEventListener)
{
window.addEventListener('onunload', Silverlight.__cleanup , false);
}
else
{
window.attachEvent('onunload', Silverlight.__cleanup );
}
}
var count = Silverlight._silverlightCount++;
handlerName = "__slEvent"+count;
window[handlerName]=handler;
}
else
{
handlerName = null;
}
return handlerName;
} | zzihp | trunk/LiveSearch_Parks/LiveSearch_Parks.Web/Silverlight.js | JavaScript | mit | 15,533 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LiveSearch_Parks.Web")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LiveSearch_Parks.Web")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3d5900ae-111a-45be-96b3-d9e4606ca793")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zzihp | trunk/LiveSearch_Parks/LiveSearch_Parks.Web/Properties/AssemblyInfo.cs | C# | mit | 1,411 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LiveSearch_Parks.Web
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
| zzihp | trunk/LiveSearch_Parks/LiveSearch_Parks.Web/Default.aspx.cs | C# | mit | 344 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="LiveSearch_Parks.Web._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
| zzihp | trunk/LiveSearch_Parks/LiveSearch_Parks.Web/Default.aspx | ASP.NET | mit | 455 |
/** Automatically generated file. DO NOT MODIFY */
package wyf.wpf;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | zzh-android-game | trunk/gen/wyf/wpf/BuildConfig.java | Java | asf20 | 149 |
// zz3unzip.cc -- sample utility to convert uncompressed files to zz3 compressed files
//
// Copyright (C) 2015 Rudy Albachten rudy@albachten.com
//
// 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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#include <iostream>
#include "zz3.h"
using std::string;
using std::cout;
using std::endl;
bool endswith(const char *name, const char *sfx)
{
size_t len1 = strlen(name);
size_t len2 = strlen(sfx);
if (len1 <= len2) return false;
return 0 == strcmp(name + len1 - len2, sfx);
}
void zz3unzip(const char *ipath)
{
char buff[32768];
if (!endswith(ipath, ".zz3")) {
cout << ipath << ": not a zz3 file";
exit(1);
}
string opath(ipath, ipath + strlen(ipath) - 4);
// get access and modification times from sourcefile
struct stat statbuf;
if (0 != stat(ipath, &statbuf)) {
perror(ipath);
exit(1);
}
struct timeval src_times[2];
TIMESPEC_TO_TIMEVAL(&src_times[0], &statbuf.st_atim);
TIMESPEC_TO_TIMEVAL(&src_times[1], &statbuf.st_mtim);
cout << "Decompressing " << ipath << "..." << endl;
ZZ3FILE *ifp = zz3_open(ipath, "r");
FILE *ofp = fopen(opath.c_str(), "w");
while (1) {
size_t len = zz3_read(ifp, buff, sizeof(buff));
if (len == 0) break;
size_t len2 = fwrite(buff, 1, len, ofp);
assert(len == len2);
}
fclose(ofp);
zz3_close(ifp);
// copy access & modification times from sourcefile to destfile
if (0 != utimes(opath.c_str(), src_times)) {
perror(opath.c_str());
exit(1);
}
}
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i) {
zz3unzip(argv[i]);
}
cout << "Done." << endl;
exit(0);
}
| zz3lib | trunk/zz3unzip.cc | C++ | asf20 | 2,392 |
// zz3.cc -- implementation of the zz3 library
//
// Copyright (C) 2015 Rudy Albachten rudy@albachten.com
//
// 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 <assert.h>
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <limits>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include "zz3.h"
#include <zlib.h>
using std::cout;
using std::endl;
using std::string;
/*
* File Format:
* ZZ3FILE : "zz3_X.X\n" SIZE BLOCKSIZE MAPLOC compressed-data MAP
* SIZE : uint64 (0 if map is not present)
* BLOCKSIZE : uint32 (0 if map is not present)
* MAPLOC : uint64 (0 if map is not present)
* MAP : 'M' BLOCK* '0' 'F' BLOCK* '0' 'E'
* BLOCK : BLOCK1 | BLOCK2
* BLOCK1 : OFFSET LENGTH
* BLOCK2 : '1' COUNT (for empty blocks in a sparse file)
* OFFSET : uintx
* LENGTH : uintx
* COUNT : uintx
*
* uint32 : 32bit unsigned (MSB first)
* uint64 : 64bit unsigned (MSB first)
* uintx : variable length unsigned int, bit7 is continuation bit, MSB first, 64bits max
*
* NOTES:
* seek/tell fpos/flen:
* seek/tell can set/report position to anywhere - even beyond flen
* read beyond flen returns 0 bytes without error and without moving fpos
* write beyond flen implicitly fills intermediate bytes with nuls ('\0') and moves flen (see "holes" below)
* only writes can move flen
* all writes in append mode reset fpos to flen before writing, reads in "a+" mode use the current fpos
* reads and writes can be intermixed without seeking - even though many systems require intervening seeks
* seeking within the current block and then reading will not reload the block
* eof:
* return true for eof() whenever the current fpos is at or past the end-of-file position
* note that this is different from posix where eof is a flag set whenever an attempt is made to read past eof
* unget:
* only one character is saved (in "pushback")
* unget(-1) effectively clears the unget buffer
* if unget buffer is anything but -1, the next character read will be char(pushback & 0xFF) without moving fpos
* typically the pushed back character matches the previous character in the file - but, even if it doesn't, the file is not changed
* "seeks" and "writes" clear the unget buffer
* "dirty" flag
* physical file sets the dirty flag (e.g. it sets the maploc to 0 in the header) when the map is missing or incorrect
* new files (modes w/w+) start out "dirty" because they don't have a map on disk yet
* existing files (modes r/r+/a/a+) start out "clean" and are marked dirty when a compressed block is updated/added to the physical file
* flush() will flush the current write buffer, write the map, set the maploc in the header, and clear the dirty flag
* holes:
* holes are created by writing with fpos beyond flen
* holes are always followed by data - there is no way to create a hole at the end of the file.
* zero length writes don't move flen and don't create holes
* any block that wasn't filled before seeking may be "short" and has implicit nils to fill the block
* when reading compressed data, always pad the block with nils - any nils before flen are part of a hole and any past flen will be ignored
* when reading:
* the buffer contains the entire block and ptr1 can be moved at will
* ptr1 always points to the next character to read (buffer.begin() <= ptr1 <= buffer.end())
* ptr2 == buffer.end()
* when writing:
* only the characters in the range [ptr1, ptr2) are valid in the buffer
* ptr2 points at the next character location for writing
* when the buffer is flushed we may have to read data before ptr1 or after ptr2 and merge with the new data
* after flushing a block, the buffer contains the whole block and can be used for reading that block
* when switching from read to write we can move ptr1 to buffer.begin() so we don't have to reread the data before ptr1 on flush
*/
namespace {
const char *MAGIC_STRING = "zz3_1.0\n";
const uint32_t DEFAULT_BLOCKSIZE = 8096;
const int DEFAULT_EFFORT = 1;
typedef std::vector<unsigned char> CharBuff;
typedef std::vector<unsigned char>::iterator BuffIter;
typedef std::vector<unsigned char>::const_iterator ConstBuffIter;
struct Block {
Block() : cpos(0), clen(0) {}
Block(uint64_t pos, uint32_t len) : cpos(pos), clen(len) {}
bool empty() const {return cpos == 0 && clen == 0;}
uint64_t cpos;
uint32_t clen;
};
struct CompareBySize {
bool operator()(const Block &lhs, const Block &rhs) {
return (lhs.clen < rhs.clen) || (lhs.clen == rhs.clen && lhs.cpos < rhs.cpos);
}
};
struct CompareByPos {
bool operator()(const Block *lhs, const Block *rhs) {
return lhs->cpos < rhs->cpos;
}
};
class noncopyable {
public:
noncopyable() {}
private:
noncopyable(const noncopyable &); // not-implemented
noncopyable& operator=(const noncopyable &); // not-implemented
};
class Blockmap : noncopyable {
public:
Blockmap() {}
Block &get(size_t i) {
if (blocks.size() <= i) blocks.resize(i + 1);
return blocks[i];
}
Block &operator[](size_t i) {
return blocks.at(i);
}
size_t size() const {
return blocks.size();
}
void show() const;
void write(FILE *fp);
void read(FILE *fp);
void add_free(Block block);
bool get_free(Block &block);
void clear() {
blocks.clear();
freeblocks_by_position.clear();
freeblocks_by_size.clear();
}
private:
typedef std::set<Block, CompareBySize> FreeBlocksBySize;
typedef std::set<const Block*, CompareByPos> FreeBlocksByPos;
std::vector<Block> blocks;
FreeBlocksBySize freeblocks_by_size;
FreeBlocksByPos freeblocks_by_position;
};
} // anonymous namespace
struct _zz3file {
string pathname;
uint32_t blocksize;
int effort;
FILE *fh;
bool readable;
bool writeable;
bool reading;
bool writing;
bool append;
bool dirty;
int pushback;
uint64_t fpos;
uint64_t flen;
uint64_t maploc;
Blockmap blockmap;
size_t blocknum;
CharBuff buffer;
CharBuff cbuffer;
BuffIter ptr1;
BuffIter ptr2;
};
namespace {
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// General i/o & misc functions
void write_u1(FILE *fp, unsigned char x)
{
if (fwrite(&x, 1, 1, fp) != 1) throw zz3error("io error");
}
void write_u32(FILE *fp, uint32_t x)
{
unsigned i = 4;
do {
char c = static_cast<char>((x >> (--i * 8)) & 0xff);
if (fwrite(&c, 1, 1, fp) != 1) throw zz3error("io error");
} while (i);
}
void write_u64(FILE *fp, uint64_t x)
{
unsigned i = 8;
do {
char c = static_cast<char>((x >> (--i * 8)) & 0xff);
if (fwrite(&c, 1, 1, fp) != 1) throw zz3error("io error");
} while (i);
}
void write_u(FILE *fp, uint64_t x)
{
do {
unsigned char bits = 0x7F & x;
if (x >>= 7) bits |= 0x80;
write_u1(fp, bits);
} while (x);
}
void write_string(FILE *fp, const char *x)
{
size_t len = strlen(x);
if (fwrite(x, 1, len, fp) != len) throw zz3error("io error");
}
unsigned char read_u1(FILE *fp)
{
unsigned char result;
if (fread(&result, 1, 1, fp) != 1) throw zz3error("io error");
return result;
}
uint32_t read_u32(FILE *fp)
{
uint32_t result = 0;
unsigned char x;
unsigned i = 4;
do {
if (fread(&x, 1, 1, fp) != 1) throw zz3error("io error");
result |= (uint32_t(x) << (8 * --i));
} while (i);
return result;
}
uint64_t read_u64(FILE *fp)
{
uint64_t result = 0;
unsigned char x;
unsigned i = 8;
do {
if (fread(&x, 1, 1, fp) != 1) throw zz3error("io error");
result |= (uint64_t(x) << (8 * --i));
} while (i);
return result;
}
uint64_t read_u(FILE *fp)
{
uint64_t result = 0;
unsigned char x;
unsigned shift = 0;
do {
x = read_u1(fp);
result |= static_cast<uint64_t>(x & 0x7f) << shift;
shift += 7;
} while (x & 0x80);
return result;
}
void read_string(FILE *fp, char *s, size_t len)
{
if (fread(s, 1, len, fp) != len) throw zz3error("io error");
}
void expect_string(FILE *fp, const char *s)
{
char buff[64];
size_t len = strlen(s);
assert(len < sizeof(buff));
read_string(fp, buff, len);
if (0 != strncmp(buff, s, len)) throw zz3error("format_error");
}
void showbuffer(const CharBuff &buffer)
{
for (size_t i = 0; i < buffer.size(); ++i) {
if (isprint(buffer[i])) cout << buffer[i];
else cout << ".";
}
cout << "\n";
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Blockmap methods
void Blockmap::show() const
{
cout << "BLOCKMAP:\n";
for (size_t i = 0; i < blocks.size(); ++i) {
if (blocks[i].cpos == 0 and blocks[i].clen == 0) {
cout << "block[" << i << "] EMPTY\n";
} else {
uint64_t endpos = blocks[i].cpos + blocks[i].clen;
cout << "block[" << i << "] pos=" << blocks[i].cpos << " (0x" << std::hex << blocks[i].cpos << std::dec << ")"
<< " end=" << endpos << " (0x" << std::hex << endpos << std::dec << ")"
<< " len=" << blocks[i].clen << " (0x" << std::hex << blocks[i].clen << std::dec << ")\n";
}
size_t j = i;
while (true) {
if (j + 1 >= blocks.size()) break;
if (blocks[j + 1].cpos != 0) break;
if (blocks[j + 1].clen != 0) break;
++j;
}
if (i != j) cout << "* " << (j - i) << " more empty blocks\n";
i = j;
}
FreeBlocksByPos::const_iterator iter = freeblocks_by_position.begin();
FreeBlocksByPos::const_iterator end = freeblocks_by_position.end();
for ( ; iter != end; ++iter) {
const Block *block = *iter;
cout << "freeblock = (" << block->cpos << ", " << block->clen << ")\n";
}
}
void Blockmap::write(FILE *fp)
{
write_string(fp, "M");
size_t holes = 0;
for (size_t i = 0; i < blocks.size(); ++i) {
const Block &block = blocks[i];
if (block.cpos == 0 && block.clen == 0) {
++holes;
} else {
if (holes) {
write_u(fp, 1);
write_u(fp, holes);
holes = 0;
}
assert(block.cpos != 0);
assert(block.clen != 0);
write_u(fp, block.cpos);
write_u(fp, block.clen);
}
}
assert(!holes);
write_u(fp, 0);
write_string(fp, "F");
FreeBlocksBySize::const_iterator iter = freeblocks_by_size.begin();
FreeBlocksBySize::const_iterator end = freeblocks_by_size.end();
for ( ; iter != end; ++iter) {
const Block &block = *iter;
assert(block.cpos != 0);
write_u(fp, block.cpos);
write_u(fp, block.clen);
}
write_u(fp, 0);
write_string(fp, "E");
}
void Blockmap::read(FILE *fp)
{
blocks.clear();
freeblocks_by_position.clear();
freeblocks_by_size.clear();
expect_string(fp, "M");
size_t i = 0;
while (true) {
uint64_t pos = read_u(fp);
uint64_t len = 0;
if (pos == 0) break;
len = read_u(fp);
assert(len <= std::numeric_limits<uint32_t>::max());
if (pos == 1) {
i += len;
// the blocks will get created with pos = len = 0 when we create the next non-hole block
} else {
Block &block = this->get(i++);
block.cpos = pos;
block.clen = static_cast<uint32_t>(len);
}
}
expect_string(fp, "F");
Block block;
for (size_t i = 0; ; ++i) {
block.cpos = read_u(fp);
if (block.cpos == 0) break;
assert(block.cpos != 1);
block.clen = static_cast<uint32_t>(read_u(fp));
add_free(block);
}
expect_string(fp, "E");
}
void Blockmap::add_free(Block block)
{
if (!block.clen) return;
const Block *prev = NULL;
const Block *next = NULL;
if (!freeblocks_by_position.empty()) {
FreeBlocksByPos::iterator iter = freeblocks_by_position.lower_bound(&block);
if (iter != freeblocks_by_position.end()) next = *iter;
if (iter != freeblocks_by_position.begin()) prev = *--iter;
}
assert(!prev || (prev->cpos + prev->clen) <= block.cpos);
if (prev && (prev->cpos + prev->clen) == block.cpos) {
// coallesce with previous
block.cpos = prev->cpos;
block.clen += prev->clen;
freeblocks_by_position.erase(prev);
freeblocks_by_size.erase(*prev);
}
assert(!next || (block.cpos + block.clen) <= next->cpos);
if (next && (block.cpos + block.clen) == next->cpos) {
// coallesce with next
block.clen += next->clen;
freeblocks_by_position.erase(next);
freeblocks_by_size.erase(*next);
}
std::pair<FreeBlocksBySize::iterator, bool> result1 = freeblocks_by_size.insert(block);
assert(result1.second);
freeblocks_by_position.insert(&*result1.first);
}
bool Blockmap::get_free(Block &block)
{
block.cpos = 0; // important - otherwise an exact match that occurs at a lower cpos would be ignored
std::set<Block>::iterator iter = freeblocks_by_size.lower_bound(block);
if (iter == freeblocks_by_size.end()) return false;
Block fblock(*iter);
freeblocks_by_position.erase(&*iter);
freeblocks_by_size.erase(iter);
block.cpos = fblock.cpos;
fblock.cpos += block.clen;
fblock.clen -= block.clen;
add_free(fblock);
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// zz3 helper functions
void fatal(string pathname, const string &msg)
{
throw zz3error(pathname + ": " + msg);
}
void fatal(ZZ3FILE *zf, const string &msg)
{
fatal(zf->pathname, msg);
}
void fatal_from_errno(ZZ3FILE *zf)
{
fatal(zf->pathname, strerror(errno));
// if (errno < 0 || errno >= sys_nerr) {
// fatal(zf->pathname, "unknown system error");
// } else fatal(zf->pathname, sys_errlist[errno]);
}
void check_mode(const char *pathname, const char *mode)
{
if (NULL != strchr("rwa", mode[0]) && (mode[1] == '\0' || 0 == strcmp(mode + 1, "+"))) return;
throw zz3error(string(pathname) + ": bad mode \"" + mode + "\"");
}
int constrain_effort(int effort)
{
return effort < 0 ? 0 :
effort > 9 ? 9 : effort;
}
void read_header(ZZ3FILE *zf)
{
char buff[256];
if (0 != fseek(zf->fh, 0L, SEEK_SET)) fatal_from_errno(zf);
if (!fgets(buff, sizeof(buff), zf->fh)) fatal_from_errno(zf);
if (0 != strcmp(buff, MAGIC_STRING)) fatal(zf, "bad header");
zf->flen = read_u64(zf->fh);
zf->blocksize = read_u32(zf->fh);
zf->maploc = read_u64(zf->fh);
if (zf->maploc == 0) fatal(zf, "incomplete file");
// cout << "flen=" << zf->flen << endl;
// cout << "blocksize=" << zf->blocksize << endl;
// cout << "maploc=" << zf->maploc << endl;
}
void write_header(ZZ3FILE *zf)
{
if (0 != fseek(zf->fh, 0L, SEEK_SET)) fatal_from_errno(zf);
if (0 > fputs(MAGIC_STRING, zf->fh)) fatal_from_errno(zf);
write_u64(zf->fh, zf->flen);
write_u32(zf->fh, zf->blocksize);
write_u64(zf->fh, zf->maploc);
}
void write_dirty_header(ZZ3FILE *zf)
{
if (0 != fseek(zf->fh, 0L, SEEK_SET)) fatal_from_errno(zf);
if (0 > fputs(MAGIC_STRING, zf->fh)) fatal_from_errno(zf);
write_u64(zf->fh, 0);
write_u32(zf->fh, 0);
write_u64(zf->fh, 0);
}
void read_tables(ZZ3FILE *zf)
{
if (0 != fseek(zf->fh, zf->maploc, SEEK_SET)) fatal_from_errno(zf);
zf->blockmap.read(zf->fh);
}
void write_tables(ZZ3FILE *zf)
{
if (0 != fseek(zf->fh, zf->maploc, SEEK_SET)) fatal_from_errno(zf);
zf->blockmap.write(zf->fh);
}
bool ptr2_at_eof(ZZ3FILE *zf)
{
uint64_t bnum = zf->flen / zf->blocksize;
if (bnum != zf->blocknum) return false;
ConstBuffIter end_of_file = zf->buffer.begin() + (zf->flen - bnum * zf->blocksize);
assert(zf->buffer.begin() <= end_of_file && end_of_file <= zf->buffer.end());
assert(zf->ptr2 <= end_of_file);
return zf->ptr2 == end_of_file;
}
void read_block(ZZ3FILE *zf)
{
static const Block EMPTYBLOCK;
const Block &block = (zf->blocknum < zf->blockmap.size()) ? zf->blockmap[zf->blocknum] : EMPTYBLOCK;
if (block.cpos == 0) {
// block is a hole - all nils
zf->buffer.assign(zf->buffer.size(), '\0');
return;
}
uLongf len1 = block.clen;
uLongf len2 = zf->buffer.size();
assert(len1 != 0);
assert(len1 <= zf->cbuffer.size());
if (block.cpos != static_cast<uint64_t>(ftell(zf->fh))) {
// we won't need to seek if we're reading a file sequentially that has all it's blocks in-order
if (0 != fseek(zf->fh, block.cpos, SEEK_SET)) fatal_from_errno(zf);
}
if (1 != fread(&zf->cbuffer[0], len1, 1, zf->fh)) fatal_from_errno(zf);
if (Z_OK != uncompress(&zf->buffer[0], &len2, &zf->cbuffer[0], len1)) fatal(zf, "uncompress error");
if (len2 < zf->buffer.size()) {
fill(zf->buffer.begin() + len2, zf->buffer.end(), '\0'); // pad with nils
}
}
void flush_block(ZZ3FILE *zf)
{
if (!zf || !zf->writing || zf->ptr1 == zf->ptr2) return;
if (!zf->dirty) {
zf->dirty = true;
write_dirty_header(zf);
}
assert(zf->ptr1 < zf->ptr2);
assert(zf->buffer.begin() <= zf->ptr1 && zf->ptr1 < zf->buffer.end());
assert(zf->buffer.begin() < zf->ptr2 && zf->ptr2 <= zf->buffer.end());
BuffIter saved_ptr2 = zf->ptr2;
// if partially writing into a block we must merge any prefix/suffix data from the existing block
// don't worry about the truncation of the last block - it is padded with nils so all blocks are the same size
if (zf->ptr1 != zf->buffer.begin() || ((zf->ptr2 != zf->buffer.end()) && !ptr2_at_eof(zf))) {
CharBuff savedata(zf->buffer);
read_block(zf);
BuffIter src = savedata.begin() + (zf->ptr1 - zf->buffer.begin());
copy(src, src + (zf->ptr2 - zf->ptr1), zf->ptr1);
}
zf->ptr1 = zf->buffer.begin();
zf->ptr2 = zf->buffer.end();
// tiny optimization - trim off trailing nils - all blocks are padded with trailing nils as needed when decompressing
while (zf->ptr2 > zf->ptr1 && zf->ptr2[-1] == '\0') --zf->ptr2;
// if entire block is nil keep one nil character
if (zf->ptr1 == zf->ptr2) ++zf->ptr2;
uLongf csize = zf->cbuffer.size();
if (Z_OK != compress2(&zf->cbuffer[0], &csize, &zf->buffer[0], zf->ptr2 - zf->ptr1, zf->effort)) fatal(zf, "compress failed");
// find a location for the compressed data
Block &block = zf->blockmap.get(zf->blocknum);
if (block.clen != csize) {
zf->blockmap.add_free(block);
assert(csize <= std::numeric_limits<uint32_t>::max());
block.clen = static_cast<uint32_t>(csize);
if (!zf->blockmap.get_free(block)) {
block.cpos = zf->maploc;
zf->maploc += block.clen;
}
}
// write the compressed block
if (block.cpos != static_cast<uint64_t>(ftell(zf->fh))) {
// we won't need to seek if we're writing a brand new file sequentially and adding each block at the end
if (0 != fseek(zf->fh, block.cpos, SEEK_SET)) fatal_from_errno(zf);
}
if (block.clen != fwrite(&zf->cbuffer[0], 1, csize, zf->fh)) fatal_from_errno(zf);
// if readable, switch to reading since the buffer contains all the data for the block
if (zf->readable) {
zf->writing = false;
zf->reading = true;
zf->ptr1 = saved_ptr2;
zf->ptr2 = zf->buffer.end();
} else {
// restore ptr2 since we're in write mode and ptr2 is the next write location
zf->ptr2 = saved_ptr2;
}
}
size_t raw_read(ZZ3FILE *zf, char *buff, size_t count, bool check_stop_char, char stop_char)
{
if (!zf || !zf->fh) return 0;
size_t total_pushback = 0;
if (zf->pushback != -1) {
if (!zf->readable) fatal(zf, "reading not allowed");
total_pushback = 1;
--count;
*buff++ = char(unsigned(zf->pushback) & 0xFF);
zf->pushback = -1;
}
if (zf->writing) {
// seek() is already optimized to flush writes and switch to reading the block
// and the buffer will contain the whole block
zz3_seek(zf, zf->fpos);
}
// don't allow reading past flen
if ((zf->fpos + count) > zf->flen) count = (zf->flen > zf->fpos) ? (zf->flen - zf->fpos) : 0;
if (count == 0) {
if (!zf->readable) fatal(zf, "reading not allowed");
return total_pushback;
}
if (!zf->reading) {
if (!zf->readable) fatal(zf, "reading not allowed");
if (count == 0) return 0;
uint64_t bnum = zf->fpos / zf->blocksize;
if (bnum > std::numeric_limits<size_t>::max()) fatal(zf, "position overflow");
zf->blocknum = static_cast<size_t>(bnum);
read_block(zf);
zf->ptr1 = zf->buffer.begin() + (zf->fpos - bnum * static_cast<uint64_t>(zf->blocksize));
zf->ptr2 = zf->buffer.end();
zf->reading = true;
}
// in read mode, the whole buffer is always equal to the whole block and ptr1 points to the next data to read
size_t remaining = count;
do {
if (zf->ptr1 == zf->ptr2) {
++zf->blocknum;
read_block(zf);
zf->ptr1 = zf->buffer.begin();
}
char c = *buff++ = *zf->ptr1++;
--remaining;
if (check_stop_char && c == stop_char) break;
} while (remaining);
size_t total_read = count - remaining;
zf->fpos += total_read;
return total_read + total_pushback;
}
size_t raw_write(ZZ3FILE *zf, const char *buff, size_t count)
{
if (!zf || !zf->fh) fatal(zf, "file not open");
if (count == 0) {
if (!zf->writeable) fatal(zf, "writing not allowed");
return 0;
}
if (zf->reading) {
// ptr1 is the current position and ptr2 is buffer.end()
// the buffer contains the whole block
zf->ptr2 = zf->ptr1;
zf->ptr1 = zf->buffer.begin();
zf->pushback = -1;
zf->reading = false;
zf->writing = true;
}
if (!zf->writing) {
if (!zf->writeable) fatal(zf, "writing not allowed");
zf->writing = true;
uint64_t bnum = zf->fpos / zf->blocksize;
if (bnum > std::numeric_limits<size_t>::max()) fatal(zf, "write overflow");
zf->blocknum = static_cast<size_t>(bnum);
zf->ptr1 = zf->ptr2 = zf->buffer.begin() + (zf->fpos - bnum * zf->blocksize);
}
size_t remaining = count;
do {
if (zf->ptr2 == zf->buffer.end()) {
flush_block(zf);
if (zf->blocknum == std::numeric_limits<size_t>::max()) fatal(zf, "write overflow");
++zf->blocknum;
zf->ptr1 = zf->ptr2 = zf->buffer.begin();
}
*zf->ptr2++ = *buff++;
} while (--remaining);
zf->fpos += count;
if (zf->fpos > zf->flen) zf->flen = zf->fpos;
return count;
}
} // anonymous namespace
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// zz3 public methods
ZZ3FILE *zz3_open(const char *path, const char *mode)
{
return zz3_open(path, mode, DEFAULT_BLOCKSIZE, DEFAULT_EFFORT);
}
ZZ3FILE *zz3_open(const char *path, const char *mode, uint32_t blocksize, int effort)
{
check_mode(path, mode);
if (blocksize > std::numeric_limits<uint32_t>::max()) fatal(path, "ridiculously large blocksize");
effort = constrain_effort(effort);
FILE *fh = fopen(path, mode[0] == 'a' ? "r+" : mode);
if (!fh) return NULL;
ZZ3FILE *zf = new ZZ3FILE;
zf->fh = fh;
zf->pathname = path;
zf->blocksize = blocksize;
zf->effort = (effort < 0) ? 0 : (effort > 9) ? 9 : effort;
zf->readable = mode[0] == 'r' || mode[1] == '+'; // r . . r+ w+ a+
zf->writeable = mode[0] == 'w' || mode[0] == 'a' || mode[1] == '+'; // . w a r+ w+ a+
zf->append = (mode[0] == 'a');
zf->reading = zf->writing = zf->dirty = false;
zf->pushback = -1;
zf->fpos = zf->flen = zf->maploc = 0;
zf->blocknum = 0;
if (mode[0] == 'r' || mode[0] == 'a') {
read_header(zf);
read_tables(zf);
} else {
write_dirty_header(zf);
zf->maploc = static_cast<uint64_t>(ftell(fh));
zf->dirty = true;
zf->writing = true;
}
zf->buffer.resize(zf->blocksize);
zf->cbuffer.resize(compressBound(zf->blocksize));
zf->ptr1 = zf->ptr2 = zf->buffer.begin();
// cout << (void*)zf << ": zz3_open(" << path << ", " << mode << ", " << blocksize << ", " << effort << ")\n";
return zf;
}
void zz3_flush(ZZ3FILE *zf)
{
if (!zf || !zf->fh) return;
flush_block(zf);
if (zf->dirty) {
zf->dirty = false;
write_tables(zf);
write_header(zf);
// TODO: remove lastfree and truncate file
}
}
void zz3_close(ZZ3FILE *zf)
{
// cout << (void*)zf << ": zz3_close()\n";
if (!zf || !zf->fh) return;
zz3_flush(zf);
fclose(zf->fh);
zf->fh = NULL;
zf->pathname.clear();
zf->blockmap.clear();
zf->buffer.clear();
zf->cbuffer.clear();
delete zf;
}
string zz3_pathname(ZZ3FILE *zf)
{
if (!zf || !zf->fh) return string();
return zf->pathname;
}
int zz3_effort(ZZ3FILE *zf)
{
return zf ? zf->effort : -1;
}
uint32_t zz3_blocksize(ZZ3FILE *zf)
{
return zf ? zf->blocksize : 0;
}
void zz3_set_effort(ZZ3FILE *zf, int effort)
{
if (!zf || !zf->fh) return;
zf->effort = constrain_effort(effort);
}
uint64_t zz3_length(ZZ3FILE *zf)
{
return (zf && zf->fh) ? zf->flen : 0;
}
void zz3_seek(ZZ3FILE *zf, uint64_t newpos)
{
if (!zf || !zf->fh) return;
uint64_t bnum = newpos / zf->blocksize;
if (bnum > std::numeric_limits<size_t>::max()) fatal(zf, "position overflow");
zf->fpos = newpos;
if (zf->writing) {
flush_block(zf);
zf->writing = false;
if (zf->readable && bnum == zf->blocknum) {
zf->reading = true;
zf->ptr2 = zf->buffer.end();
}
}
if (zf->reading && bnum != zf->blocknum) zf->reading = false;
if (zf->reading) zf->ptr1 = zf->buffer.begin() + (zf->fpos - bnum * zf->blocksize);
}
uint64_t zz3_tell(ZZ3FILE *zf)
{
return (zf && zf->fh) ? zf->fpos : static_cast<uint64_t>(-1);
}
bool zz3_eof(ZZ3FILE *zf)
{
return (zf && zf->fh) ? zf->fpos >= zf->flen : true;
}
int zz3_getc(ZZ3FILE *zf)
{
char c;
size_t x = raw_read(zf, &c, 1, false, '\0');
return x == 1 ? (int)(unsigned char)c : -1;
}
int zz3_ungetc(ZZ3FILE *zf, int c)
{
if (!zf || !zf->fh) return -1;
zf->pushback = c;
return c;
}
int zz3_peek(ZZ3FILE *zf)
{
char c;
size_t len = raw_read(zf, &c, 1, false, '\0');
if (len != 1) return -1;
zz3_ungetc(zf, (int)(unsigned char)c);
return (int)(unsigned char)c;
}
int zz3_putc(ZZ3FILE *zf, int c)
{
char c2 = (char)c;
size_t len = raw_write(zf, &c2, 1);
return (len == 1) ? c : -1;
}
size_t zz3_read(ZZ3FILE *zf, char *buff, size_t bufflen)
{
return raw_read(zf, buff, bufflen, false, '\0');
}
size_t zz3_read(ZZ3FILE *zf, string &str, size_t maxlen)
{
if (!zf || !zf->fh) return 0;
size_t remaining = zf->fpos > zf->flen ? 0 : zf->flen - zf->fpos;
size_t len = maxlen < remaining ? maxlen : remaining;
str.resize(len);
size_t len2 = raw_read(zf, &str[0], len, false, '\0');
assert(len == len2);
return len2;
}
size_t zz3_write(ZZ3FILE *zf, const char *buff, size_t count)
{
return raw_write(zf, buff, count);
}
size_t zz3_write(ZZ3FILE *zf, const string &str)
{
return raw_write(zf, str.c_str(), str.size());
}
size_t zz3_puts(ZZ3FILE *zf, const char *buff)
{
return raw_write(zf, buff, strlen(buff));
}
size_t zz3_gets(ZZ3FILE *zf, const char *buff, size_t bufflen);
size_t zz3_getline(ZZ3FILE *zf, char *buff, size_t bufflen)
{
return raw_read(zf, buff, bufflen, true, '\n');
}
size_t zz3_getline(ZZ3FILE *zf, string &line)
{
return zz3_getline(zf, line, '\n');
}
size_t zz3_getline(ZZ3FILE *zf, string &line, char delim, uint64_t maxlen)
{
char buffer[4096];
line.clear();
while (1) {
size_t len = std::min(maxlen - line.size(), sizeof(buffer));
len = raw_read(zf, buffer, len, true, delim);
if (len == 0) break;
line.append(buffer, buffer + len);
if (buffer[len - 1] == delim) break;
if (line.size() >= maxlen) break;
}
return line.size();
}
size_t zz3_getline(ZZ3FILE *zf, string &line, char delim)
{
char buffer[4096];
line.clear();
while (1) {
size_t len = raw_read(zf, buffer, sizeof(buffer), true, delim);
if (len == 0) break;
line.append(buffer, buffer + len);
if (buffer[len - 1] == delim) break;
}
return line.size();
}
void zz3_showmap(ZZ3FILE *zf)
{
if (!zf || !zf->fh) return;
zf->blockmap.show();
}
void zz3_showblocks(ZZ3FILE *zf)
{
if (!zf || !zf->fh) return;
flush_block(zf);
zf->reading = false;
for (zf->blocknum = 0; zf->blocknum < zf->blockmap.size(); ++zf->blocknum) {
Block &block = zf->blockmap[zf->blocknum];
if (block.empty()) continue;
read_block(zf);
cout << "block[" << zf->blocknum << "]=";
showbuffer(zf->buffer);
}
zf->blocknum = 0;
zf->ptr1 = zf->ptr2 = zf->buffer.begin();
}
| zz3lib | trunk/zz3.cc | C++ | asf20 | 30,330 |
// zz3cat.cc -- sample utility to decompress zz3 files to stdout
//
// Copyright (C) 2015 Rudy Albachten rudy@albachten.com
//
// 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 <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string>
#include <iostream>
#include "zz3.h"
using std::string;
using std::cout;
using std::endl;
void zz3cat(const char *ipath)
{
char buff[32768];
ZZ3FILE *ifp = zz3_open(ipath, "r");
while (1) {
size_t len = zz3_read(ifp, buff, sizeof(buff));
if (len == 0) break;
size_t len2 = fwrite(buff, 1, len, stdout);
assert(len == len2);
}
zz3_close(ifp);
}
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i) {
zz3cat(argv[i]);
}
exit(0);
}
| zz3lib | trunk/zz3cat.cc | C++ | asf20 | 1,273 |
// zz3.i - swig interface file for python to use the zz3 library
//
// Copyright (C) 2015 Rudy Albachten rudy@albachten.com
//
// 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.
//
%module "zz3";
%feature("autodoc", "1");
%{
#include "zz3.h"
#include <iostream>
#include <boost/shared_ptr.hpp>
using std::cout;
%}
%include "std_string.i"
%include "stdint.i"
%feature("kwargs") Zz3File::Zz3File;
%feature("kwargs") open;
%newobject open;
%newobject Zz3File::__iter__;
%newobject Zz3File::__enter__;
%feature("python:slot", "tp_iter", functype="getiterfunc") Zz3File::__iter__;
%feature("python:slot", "tp_iternext", functype="iternextfunc") Zz3File::__iternext__;
%ignore zz3_file_closed;
%ignore zz3_io_error;
%ignore zz3_stop_iteration;
%ignore Zz3File::getname;
%typemap(throws) zz3_stop_iteration {
(void)$1;
SWIG_SetErrorObj(PyExc_StopIteration, SWIG_Py_Void());
SWIG_fail;
}
%typemap(throws) zz3_io_error {
PyErr_SetString(PyExc_IOError, $1.what());
SWIG_fail;
}
%ignore Zz3File::Zz3File(const Zz3File &);
%catches(zz3_io_error) Zz3File::Zz3File;
%catches(zz3_io_error) open;
%catches(zz3_stop_iteration) Zz3File::__iternext__;
%exception {
try {
$action
} catch (zz3error &e) {
PyErr_SetString(PyExc_RuntimeError, e.what());
SWIG_fail;
} catch (zz3_file_closed &e) {
PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
SWIG_fail;
} catch (std::exception &e) {
PyErr_SetString(PyExc_RuntimeError, e.what());
SWIG_fail;
}
}
%inline %{
struct zz3_stop_iteration {};
struct zz3_file_closed {};
class zz3_io_error {
public:
zz3_io_error(const std::string &msg) : msg_(msg) {}
const char *what() const {return msg_.c_str();}
private:
std::string msg_;
};
class Zz3File {
public:
Zz3File(const Zz3File &zfile) : zf(zfile.zf) {
// cout << "copied Zz3File " << (void*)this << "\n";
}
Zz3File(const char *path, const char *mode = "r", uint64_t blocksize = 8096, int effort = 1)
: zf(zz3_open(path, mode, blocksize, effort), zz3_close) {
// cout << "alloc Zz3File " << (void*)this << "\n";
if (!zf) throw zz3_io_error(std::string("Cannot open file: '") + path + "' mode: '" + mode + "'");
}
~Zz3File() {
// cout << "free Zz3File " << (void*)this << "\n";
}
void close() {
if (!zf) throw zz3_file_closed();
zz3_flush(zf.get());
zf.reset();
}
void flush() {
zz3_flush(zf.get());
}
std::string read(int maxlen=-1) {
if (!zf) throw zz3_file_closed();
std::string result;
zz3_read(zf.get(), result, maxlen);
return result;
}
std::string readline(int maxlen=-1) {
if (!zf) throw zz3_file_closed();
std::string result;
if (maxlen == -1) {
zz3_getline(zf.get(), result);
} else {
zz3_getline(zf.get(), result, '\n', maxlen);
}
return result;
}
std::string getname() {
return zz3_pathname(zf.get());
}
void rewind() {
if (!zf) throw zz3_file_closed();
zz3_seek(zf.get(), 0);
}
uint64_t tell() {
if (!zf) throw zz3_file_closed();
return zz3_tell(zf.get());
}
void seek(int64_t offset, int whence=0) {
if (!zf) throw zz3_file_closed();
switch (whence) {
case 0: break;
case 1: offset += zz3_tell(zf.get()); break;
case 2: offset += zz3_length(zf.get()); break;
default: throw zz3error("invalid value for whence argument");
}
if (offset < 0) offset = 0;
zz3_seek(zf.get(), offset);
}
void write(std::string data) {
if (!zf) throw zz3_file_closed();
zz3_write(zf.get(), data);
}
Zz3File *__iter__() {
if (!zf) throw zz3_file_closed();
return new Zz3File(*this);
}
std::string __iternext__() {
if (!zf) throw zz3_file_closed();
if (zz3_eof(zf.get())) throw zz3_stop_iteration();
std::string result;
zz3_getline(zf.get(), result);
return result;
}
Zz3File *__enter__() {
return new Zz3File(*this);
}
void __exit__(PyObject *, PyObject *, PyObject *) {
this->close();
}
private:
boost::shared_ptr<ZZ3FILE> zf;
};
Zz3File *open(const char *filename, const char *mode="r", uint64_t blocksize = 8096, int compresslevel = 1) {
return new Zz3File(filename, mode, blocksize, compresslevel);
}
%}
%extend Zz3File {
std::string name;
}
%{
void Zz3File_name_set(Zz3File *zf, const std::string &name)
{
throw zz3error("filename is readonly");
}
std::string Zz3File_name_get(Zz3File *zf)
{
return zf->getname();
}
%}
| zz3lib | trunk/zz3.i | SWIG | asf20 | 5,229 |
CXX = g++
SWIG = /home/ralbacht/opt/swig-2.0.8/bin/swig
OPT = -g -O -DNDEBUG
BOOST_ROOT = /home/ralbacht/opt/boost_1_54_0
all : libzz3.so _zz3.so zz3zip zz3unzip zz3cat
zz3.o : zz3.h zz3.cc
$(CXX) $(OPT) -c -Wall -Wconversion -fpic zz3.cc
libzz3.so : zz3.o
$(CXX) $(OPT) -shared -o libzz3.so zz3.o
zz3_wrap.cc : zz3.i
$(SWIG) -c++ -builtin -O -python -o zz3_wrap.cc zz3.i
zz3_wrap.o: zz3.h zz3_wrap.cc
$(CXX) $(OPT) -I/tools/share/python/2.7.1/linux64/include/python2.7 -I$(BOOST_ROOT)/include -c -Wall -Wno-unused -fpic zz3_wrap.cc
_zz3.so : zz3_wrap.o
$(CXX) -shared -o _zz3.so zz3_wrap.o -Wl,--enable-new-dtags -Wl,-rpath,\$$ORIGIN -L. -lzz3 -lz
% : %.cc zz3.o
$(CXX) $(OPT) $< -o $@ zz3.o -lz
clean:
rm -f *.o *.so *_wrap.* zz3.py zz3.pyc zz3zip zz3unzip zz3cat
| zz3lib | trunk/Makefile | Makefile | asf20 | 782 |
// zz3zip.cc -- sample utility to convert zz3 compressed files to uncompressed files
//
// Copyright (C) 2015 Rudy Albachten rudy@albachten.com
//
// 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 <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include "zz3.h"
using std::string;
using std::cout;
using std::endl;
void zz3zip(const string &ipath, const string &opath, uint32_t blocksize, int effort, bool verbose)
{
char buff[32768];
FILE *ifp = (ipath == "-") ? stdin : fopen(ipath.c_str(), "r");
if (blocksize == 0) {
blocksize = 8192;
if (ifp != stdin && 0 == fseek(ifp, 0, SEEK_END)) {
long filelen = ftell(ifp);
while ((filelen / blocksize) > 65536) blocksize *= 2;
fseek(ifp, 0, SEEK_SET);
}
}
if (verbose) {
cout << "compressing: " << (ifp == stdin ? "stdin" : ipath) << endl;
cout << "blocksize: " << blocksize << endl;
}
ZZ3FILE *ofp = zz3_open(opath.c_str(), "w", blocksize, effort);
while (1) {
size_t len = fread(buff, 1, sizeof(buff), ifp);
if (len == 0) break;
zz3_write(ofp, buff, len);
}
uint64_t total = zz3_tell(ofp);
zz3_close(ofp);
if (verbose) {
struct stat statbuf;
int rc = stat(opath.c_str(), &statbuf);
if (rc != 0) {
perror(opath.c_str());
exit(1);
}
uint64_t compressed = statbuf.st_size;
double reduction = 100.0 * double(total - compressed) / double(total);
uint64_t blockcount = total / blocksize;
if (blocksize * blockcount != total) ++blockcount;
cout << "blockcount: " << blockcount << endl;
cout << "uncompressed: " << total << endl;
cout << "compressed: " << compressed << endl;
cout << "reduction: " << reduction << "%" << endl;
}
if (ifp != stdin) fclose(ifp);
}
int main(int argc, char *argv[])
{
uint32_t blocksize = 0;
int effort = 6;
bool verbose = false;
for (int i = 1; i < argc; ++i) {
if (0 == strncmp(argv[i], "--blocksize", strlen(argv[i])) && strlen(argv[i]) >= 3 && (i + 1) < argc) {
blocksize = static_cast<uint32_t>(atoi(argv[++i]));
} else if (0 == strncmp(argv[i], "--effort", strlen(argv[i])) && strlen(argv[i]) >= 3 && (i + 1) < argc) {
effort = atoi(argv[++i]);
} else if (0 == strncmp(argv[i], "--verbose", strlen(argv[i])) && strlen(argv[i]) >= 3 && (i + 1) < argc) {
verbose = true;
} else if (0 == strcmp("-", argv[i]) && (i + 1) < argc) {
string ipath(argv[i]);
string opath(argv[++i]);
zz3zip(ipath, opath, blocksize, effort, verbose);
} else {
string ipath(argv[i]);
// get access and modification times from sourcefile
struct stat statbuf;
if (0 != stat(ipath.c_str(), &statbuf)) {
perror(ipath.c_str());
exit(1);
}
struct timeval src_times[2];
TIMESPEC_TO_TIMEVAL(&src_times[0], &statbuf.st_atim);
TIMESPEC_TO_TIMEVAL(&src_times[1], &statbuf.st_mtim);
string opath(ipath);
opath += ".zz3";
zz3zip(ipath, opath, blocksize, effort, verbose);
// copy access & modification times from sourcefile
if (0 != utimes(opath.c_str(), src_times)) {
perror(opath.c_str());
exit(1);
}
}
}
exit(0);
}
| zz3lib | trunk/zz3zip.cc | C++ | asf20 | 4,138 |
// zz3.h -- interface of the 'zz3' ssekable compressed files library
//
// Copyright (C) 2015 Rudy Albachten rudy@albachten.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef ZZ3_LIB_INCLUDED
#define ZZ3_LIB_INCLUDED
#include <stdint.h>
#include <string>
#include <stdexcept>
class zz3error : public std::runtime_error {
public:
zz3error(const char *msg) : std::runtime_error(msg) {}
zz3error(const std::string &msg) : std::runtime_error(msg.c_str()) {}
};
typedef struct _zz3file ZZ3FILE;
ZZ3FILE *zz3_open(const char *path, const char *mode);
ZZ3FILE *zz3_open(const char *path, const char *mode, uint32_t blocksize, int effort);
void zz3_flush(ZZ3FILE *zf);
void zz3_close(ZZ3FILE *zf);
std::string zz3_pathname(ZZ3FILE *zf);
int zz3_effort(ZZ3FILE *zf);
uint32_t zz3_blocksize(ZZ3FILE *zf);
void zz3_set_effort(ZZ3FILE *zf, int effort);
uint64_t zz3_length(ZZ3FILE *zf);
void zz3_seek(ZZ3FILE *zf, uint64_t pos);
uint64_t zz3_tell(ZZ3FILE *zf);
bool zz3_eof(ZZ3FILE *zf);
int zz3_getc(ZZ3FILE *zf);
int zz3_ungetc(ZZ3FILE *zf, int c);
int zz3_peek(ZZ3FILE *zf);
int zz3_putc(ZZ3FILE *zf, int c);
size_t zz3_read(ZZ3FILE *zf, char *buff, size_t bufflen);
size_t zz3_read(ZZ3FILE *zf, std::string &str, uint64_t maxlen);
size_t zz3_write(ZZ3FILE *zf, const char *buff, size_t bufflen);
size_t zz3_write(ZZ3FILE *zf, const std::string &str);
size_t zz3_puts(ZZ3FILE *zf, const char *buff);
size_t zz3_getline(ZZ3FILE *zf, char *buff, size_t bufflen);
size_t zz3_getline(ZZ3FILE *zf, std::string &line);
size_t zz3_getline(ZZ3FILE *zf, std::string &line, char delim);
size_t zz3_getline(ZZ3FILE *zf, std::string &line, char delim, uint64_t maxlen);
void zz3_showmap(ZZ3FILE *zf);
void zz3_showblocks(ZZ3FILE *zf);
#endif
| zz3lib | trunk/zz3.h | C++ | asf20 | 2,255 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is RSJ Software GmbH code.
*
* The Initial Developer of the Original Code is
* RSJ Software GmbH.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributors:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <stdio.h>
#include <windows.h>
#include <winbase.h>
// ----------------------------------------------------------------------------
int main (int ArgC,
char *ArgV[])
{
const char *sourceName;
const char *targetName;
HANDLE targetHandle;
void *versionPtr;
DWORD versionLen;
int lastError;
int ret = 0;
if (ArgC < 3) {
fprintf(stderr,
"Usage: %s <source> <target>\n",
ArgV[0]);
exit (1);
}
sourceName = ArgV[1];
targetName = ArgV[2];
if ((versionLen = GetFileVersionInfoSize(sourceName,
NULL)) == 0) {
fprintf(stderr,
"Could not retrieve version len from %s\n",
sourceName);
exit (2);
}
if ((versionPtr = calloc(1,
versionLen)) == NULL) {
fprintf(stderr,
"Error allocating temp memory\n");
exit (3);
}
if (!GetFileVersionInfo(sourceName,
NULL,
versionLen,
versionPtr)) {
fprintf(stderr,
"Could not retrieve version info from %s\n",
sourceName);
exit (4);
}
if ((targetHandle = BeginUpdateResource(targetName,
FALSE)) == INVALID_HANDLE_VALUE) {
fprintf(stderr,
"Could not begin update of %s\n",
targetName);
free(versionPtr);
exit (5);
}
if (!UpdateResource(targetHandle,
RT_VERSION,
MAKEINTRESOURCE(VS_VERSION_INFO),
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
versionPtr,
versionLen)) {
lastError = GetLastError();
fprintf(stderr,
"Error %d updating resource\n",
lastError);
ret = 6;
}
if (!EndUpdateResource(targetHandle,
FALSE)) {
fprintf(stderr,
"Error finishing update\n");
ret = 7;
}
free(versionPtr);
return (ret);
}
| zzhongster-npactivex | transver/transver.cpp | C++ | mpl11 | 3,963 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
replaceDocument();
pageDOMLoaded = true;
if (needNotifyBar) {
showNotifyBar();
}
window.addEventListener('load', replaceDocument, false);
| zzhongster-npactivex | chrome/inject_doreplace.js | JavaScript | mpl11 | 333 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var tabStatus = {};
var version;
var firstRun = false;
var firstUpgrade = false;
var blackList = [
/^https?:\/\/[^\/]*\.taobao\.com\/.*/i,
/^https?:\/\/[^\/]*\.alipay\.com\/.*/i
];
var MAX_LOG = 400;
(function getVersion() {
$.ajax('manifest.json', {
success: function (v){
v = JSON.parse(v);
version = v.version;
trackVersion(version);
}
});
})();
function startListener() {
chrome.extension.onConnect.addListener(function(port) {
if (!port.sender.tab) {
console.error('Not connect from tab');
return;
}
initPort(port);
});
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (!sender.tab) {
console.error('Request from non-tab');
} else if (request.command == 'Configuration') {
var config = setting.getPageConfig(request.href);
sendResponse(config);
if (request.top) {
resetTabStatus(sender.tab.id);
var dummy = {href: request.href, clsid: 'NULL', urldetect: true};
if (!config.pageRule &&
setting.getFirstMatchedRule(
dummy, setting.defaultRules)) {
detectControl(dummy, sender.tab.id, 0);
}
}
} else if (request.command == 'GetNotification') {
getNotification(request, sender, sendResponse);
} else if (request.command == 'DismissNotification') {
chrome.tabs.sendRequest(
sender.tab.id, {command:'DismissNotificationPage'});
sendResponse({});
} else if (request.command = "BlockSite") {
setting.blocked.push({type:"wild", value:request.site});
setting.update();
sendResponse({});
}
}
);
}
var blocked = {};
function notifyUser(request, tabId) {
var s = tabStatus[tabId];
if (s.notify && (s.urldetect || s.count > s.actived)) {
console.log("Notify the user on tab ", tabId);
chrome.tabs.sendRequest(tabId, {command: "NotifyUser", tabid: tabId}, null);
}
}
var greenIcon = chrome.extension.getURL('icon16.png');
var grayIcon = chrome.extension.getURL('icon16-gray.png');
var errorIcon = chrome.extension.getURL('icon16-error.png');
var responseCommands = {};
function resetTabStatus(tabId) {
tabStatus[tabId] = {
count: 0,
actived: 0,
error: 0,
urldetect: 0,
notify: true,
issueId: null,
logs: {"0":[]},
objs: {"0":[]},
frames: 1,
tracking: false
};
}
function initPort(port) {
var tabId = port.sender.tab.id;
if (!(tabId in tabStatus)) {
resetTabStatus(tabId);
}
var status = tabStatus[tabId];
var frameId = tabStatus[tabId].frames++;
status.logs[frameId] = [];
status.objs[frameId] = [];
port.onMessage.addListener(function(request) {
var resp = responseCommands[request.command];
if (resp) {
delete request.command;
resp(request, tabId, frameId);
} else {
console.error("Unknown command " + request.command);
}
});
port.onDisconnect.addListener(function() {
for (var i = 0; i < status.objs[frameId].length; ++i) {
countTabObject(status, status.objs[frameId][i], -1);
}
showTabStatus(tabId);
if (status.tracking) {
if (status.count == 0) {
// Open the log page.
window.open('log.html?tabid=' + tabId);
status.tracking = false;
}
} else {
// Clean up after 1 min.
window.setTimeout(function() {
status.logs[frameId] = [];
status.objs[frameId] = [];
}, 60 * 1000);
}
});
}
chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) {
if (tabStatus[tabId]) {
tabStatus[tabId].removed = true;
var TIMEOUT = 1000 * 60 * 5;
// clean up after 5 mins.
window.setTimeout(function() {
delete tabStatus[tabId];
}, TIMEOUT);
}
});
function countTabObject(status, info, delta) {
for (var i = 0; i < blackList.length; ++i) {
if (info.href.match(blackList[i])) {
return;
}
}
if (setting.getFirstMatchedRule(info, setting.blocked)) {
status.notify = false;
}
if (info.urldetect) {
status.urldetect += delta;
// That's not a object.
return;
}
if (info.actived) {
status.actived += delta;
if (delta > 0) {
trackUse(info.rule);
}
} else if (delta > 0) {
trackNotUse(info.href);
}
status.count += delta;
var issue = setting.getMatchedIssue(info);
if (issue) {
status.error += delta;
status.issueId = issue.identifier;
if (delta > 0) {
trackIssue(issue);
}
}
}
function showTabStatus(tabId) {
if (tabStatus[tabId].removed) {
return;
}
var status = tabStatus[tabId];
var title = "";
var iconPath = greenIcon;
if (!status.count && !status.urldetect) {
chrome.pageAction.hide(tabId);
return;
} else {
chrome.pageAction.show(tabId);
}
if (status.urldetect) {
// Matched some rule.
iconPath = grayIcon;
title = $$('status_urldetect');
} else if (status.count == 0) {
// Do nothing..
} else if (status.error != 0) {
// Error
iconPath = errorIcon;
title = $$('status_error');
} else if (status.count != status.actived) {
// Disabled..
iconPath = grayIcon;
title = $$('status_disabled');
} else {
// OK
iconPath = greenIcon;
title = $$('status_ok');
}
chrome.pageAction.setIcon({
tabId: tabId,
path: iconPath
});
chrome.pageAction.setTitle({
tabId: tabId,
title: title
});
chrome.pageAction.setPopup({
tabId: tabId,
popup: 'popup.html?tabid=' + tabId
});
}
function detectControl(request, tabId, frameId) {
var status = tabStatus[tabId];
if (frameId != 0 && status.objs[0].length) {
// Remove the item to identify the page.
countTabObject(status, status.objs[0][0], -1);
status.objs[0] = [];
}
status.objs[frameId].push(request);
countTabObject(status, request, 1);
showTabStatus(tabId);
notifyUser(request, tabId);
}
responseCommands.DetectControl = detectControl;
responseCommands.Log = function(request, tabId, frameId) {
var logs = tabStatus[tabId].logs[frameId];
if (logs.length < MAX_LOG) {
logs.push(request.message);
} else if (logs.length == MAX_LOG) {
logs.push('More logs clipped');
}
}
function generateLogFile(tabId) {
var status = tabStatus[tabId];
if (!status) {
return 'No log for tab ' + tabId;
}
var ret = '---------- Start of log --------------\n';
ret += 'UserAgent: ' + navigator.userAgent + '\n';
ret += 'Extension version: ' + version + '\n';
ret += '\n';
var frameCount = 0;
for (var i = 0; i < status.frames; ++i) {
if (status.objs[i].length == 0 && status.logs[i].length == 0) {
continue;
}
if (frameCount) {
ret += '\n\n';
}
++frameCount;
ret += '------------ Frame ' + (i + 1) + ' ------------------\n';
ret += 'Objects:\n';
for (var j = 0; j < status.objs[i].length; ++j) {
ret += JSON.stringify(status.objs[i][j]) + '\n';
}
ret += '\n';
ret += 'Log:\n';
for (var j = 0; j < status.logs[i].length; ++j) {
ret += status.logs[i][j] + '\n';
}
}
ret += '\n---------------- End of log ---------------\n';
ret += stringHash(ret);
if (frameCount == 0) {
return "No log for tab " + tabId;
}
return ret;
}
function getNotification(request, sender, sendResponse) {
var tabid = sender.tab.id;
chrome.tabs.get(tabid, function(tab) {
var config = {};
config.tabId = tab.id;
config.site = tab.url.replace(/[^:]*:\/\/([^\/]*).*/, '$1');
config.sitePattern = tab.url.replace(/([^:]*:\/\/[^\/]*).*/, '$1/*');
if (tabStatus[tabid].urldetect) {
config.message = $$('status_urldetect');
} else {
config.message = $$('status_disabled');
}
config.closeMsg = $$('bar_close');
config.enableMsg = $$('bar_enable');
config.blockMsg = $$('bar_block', config.site);
sendResponse(config);
});
}
| zzhongster-npactivex | chrome/common.js | JavaScript | mpl11 | 8,404 |