diff --git a/src/CMakeLists.txt b/CMakeLists.txt
similarity index 100%
rename from src/CMakeLists.txt
rename to CMakeLists.txt
diff --git a/src/all.sln b/all.sln
similarity index 100%
rename from src/all.sln
rename to all.sln
diff --git a/src/eressea/doc/bugs.txt b/doc/bugs.txt
similarity index 100%
rename from src/eressea/doc/bugs.txt
rename to doc/bugs.txt
diff --git a/src/eressea/doc/changes.txt b/doc/changes.txt
similarity index 100%
rename from src/eressea/doc/changes.txt
rename to doc/changes.txt
diff --git a/src/eressea/doc/coding.txt b/doc/coding.txt
similarity index 100%
rename from src/eressea/doc/coding.txt
rename to doc/coding.txt
diff --git a/src/eressea/doc/directories.txt b/doc/directories.txt
similarity index 100%
rename from src/eressea/doc/directories.txt
rename to doc/directories.txt
diff --git a/src/eressea/doc/new-source.gif b/doc/new-source.gif
similarity index 100%
rename from src/eressea/doc/new-source.gif
rename to doc/new-source.gif
diff --git a/src/eressea/doc/spells_uebersicht.txt b/doc/spells_uebersicht.txt
similarity index 100%
rename from src/eressea/doc/spells_uebersicht.txt
rename to doc/spells_uebersicht.txt
diff --git a/src/eressea/doc/synonyme-rassen b/doc/synonyme-rassen
similarity index 100%
rename from src/eressea/doc/synonyme-rassen
rename to doc/synonyme-rassen
diff --git a/src/eressea/doc/todo.txt b/doc/todo.txt
similarity index 100%
rename from src/eressea/doc/todo.txt
rename to doc/todo.txt
diff --git a/src/eressea/doc/triggers.txt b/doc/triggers.txt
similarity index 100%
rename from src/eressea/doc/triggers.txt
rename to doc/triggers.txt
diff --git a/src/eressea/eressea.sln b/eressea.sln
similarity index 100%
rename from src/eressea/eressea.sln
rename to eressea.sln
diff --git a/src/eressea/eressea.vcproj b/eressea.vcproj
similarity index 100%
rename from src/eressea/eressea.vcproj
rename to eressea.vcproj
diff --git a/src/eressea/res/buildings/castle-2.xml b/res/buildings/castle-2.xml
similarity index 100%
rename from src/eressea/res/buildings/castle-2.xml
rename to res/buildings/castle-2.xml
diff --git a/src/basic/res/buildings/castle.xml b/res/buildings/castle.xml
similarity index 100%
rename from src/basic/res/buildings/castle.xml
rename to res/buildings/castle.xml
diff --git a/src/eressea/res/catalog-e3a.xml b/res/catalog-e3a.xml
similarity index 100%
rename from src/eressea/res/catalog-e3a.xml
rename to res/catalog-e3a.xml
diff --git a/src/eressea/res/catalog-eressea.xml b/res/catalog-eressea.xml
similarity index 100%
rename from src/eressea/res/catalog-eressea.xml
rename to res/catalog-eressea.xml
diff --git a/src/eressea/res/config-e3a.xml b/res/config-e3a.xml
similarity index 100%
rename from src/eressea/res/config-e3a.xml
rename to res/config-e3a.xml
diff --git a/src/eressea/res/config-eressea.xml b/res/config-eressea.xml
similarity index 100%
rename from src/eressea/res/config-eressea.xml
rename to res/config-eressea.xml
diff --git a/src/eressea/res/directions.xml b/res/directions.xml
similarity index 100%
rename from src/eressea/res/directions.xml
rename to res/directions.xml
diff --git a/src/eressea/res/e3a/armor.xml b/res/e3a/armor.xml
similarity index 100%
rename from src/eressea/res/e3a/armor.xml
rename to res/e3a/armor.xml
diff --git a/src/eressea/res/e3a/armor/chainmail.xml b/res/e3a/armor/chainmail.xml
similarity index 100%
rename from src/eressea/res/e3a/armor/chainmail.xml
rename to res/e3a/armor/chainmail.xml
diff --git a/src/eressea/res/e3a/armor/laenmail.xml b/res/e3a/armor/laenmail.xml
similarity index 100%
rename from src/eressea/res/e3a/armor/laenmail.xml
rename to res/e3a/armor/laenmail.xml
diff --git a/src/eressea/res/e3a/armor/laenshield.xml b/res/e3a/armor/laenshield.xml
similarity index 100%
rename from src/eressea/res/e3a/armor/laenshield.xml
rename to res/e3a/armor/laenshield.xml
diff --git a/src/eressea/res/e3a/armor/plate.xml b/res/e3a/armor/plate.xml
similarity index 100%
rename from src/eressea/res/e3a/armor/plate.xml
rename to res/e3a/armor/plate.xml
diff --git a/src/eressea/res/e3a/armor/rustychainmail.xml b/res/e3a/armor/rustychainmail.xml
similarity index 100%
rename from src/eressea/res/e3a/armor/rustychainmail.xml
rename to res/e3a/armor/rustychainmail.xml
diff --git a/src/eressea/res/e3a/armor/rustyshield.xml b/res/e3a/armor/rustyshield.xml
similarity index 100%
rename from src/eressea/res/e3a/armor/rustyshield.xml
rename to res/e3a/armor/rustyshield.xml
diff --git a/src/eressea/res/e3a/armor/scale.xml b/res/e3a/armor/scale.xml
similarity index 100%
rename from src/eressea/res/e3a/armor/scale.xml
rename to res/e3a/armor/scale.xml
diff --git a/src/eressea/res/e3a/armor/shield.xml b/res/e3a/armor/shield.xml
similarity index 100%
rename from src/eressea/res/e3a/armor/shield.xml
rename to res/e3a/armor/shield.xml
diff --git a/src/eressea/res/e3a/armor/towershield.xml b/res/e3a/armor/towershield.xml
similarity index 100%
rename from src/eressea/res/e3a/armor/towershield.xml
rename to res/e3a/armor/towershield.xml
diff --git a/src/eressea/res/e3a/buildings.xml b/res/e3a/buildings.xml
similarity index 100%
rename from src/eressea/res/e3a/buildings.xml
rename to res/e3a/buildings.xml
diff --git a/src/eressea/res/e3a/equipment.xml b/res/e3a/equipment.xml
similarity index 100%
rename from src/eressea/res/e3a/equipment.xml
rename to res/e3a/equipment.xml
diff --git a/src/eressea/res/e3a/items.xml b/res/e3a/items.xml
similarity index 100%
rename from src/eressea/res/e3a/items.xml
rename to res/e3a/items.xml
diff --git a/src/eressea/res/e3a/luxuries.xml b/res/e3a/luxuries.xml
similarity index 100%
rename from src/eressea/res/e3a/luxuries.xml
rename to res/e3a/luxuries.xml
diff --git a/src/eressea/res/e3a/messages.xml b/res/e3a/messages.xml
similarity index 100%
rename from src/eressea/res/e3a/messages.xml
rename to res/e3a/messages.xml
diff --git a/src/eressea/res/e3a/races.xml b/res/e3a/races.xml
similarity index 100%
rename from src/eressea/res/e3a/races.xml
rename to res/e3a/races.xml
diff --git a/src/eressea/res/e3a/resources.xml b/res/e3a/resources.xml
similarity index 100%
rename from src/eressea/res/e3a/resources.xml
rename to res/e3a/resources.xml
diff --git a/src/eressea/res/e3a/resources/iron.xml b/res/e3a/resources/iron.xml
similarity index 100%
rename from src/eressea/res/e3a/resources/iron.xml
rename to res/e3a/resources/iron.xml
diff --git a/src/eressea/res/e3a/resources/mallornseed.xml b/res/e3a/resources/mallornseed.xml
similarity index 100%
rename from src/eressea/res/e3a/resources/mallornseed.xml
rename to res/e3a/resources/mallornseed.xml
diff --git a/src/eressea/res/e3a/resources/seed.xml b/res/e3a/resources/seed.xml
similarity index 100%
rename from src/eressea/res/e3a/resources/seed.xml
rename to res/e3a/resources/seed.xml
diff --git a/src/eressea/res/e3a/resources/stone.xml b/res/e3a/resources/stone.xml
similarity index 100%
rename from src/eressea/res/e3a/resources/stone.xml
rename to res/e3a/resources/stone.xml
diff --git a/src/eressea/res/e3a/shipnames.xml b/res/e3a/shipnames.xml
similarity index 100%
rename from src/eressea/res/e3a/shipnames.xml
rename to res/e3a/shipnames.xml
diff --git a/src/eressea/res/e3a/ships.xml b/res/e3a/ships.xml
similarity index 100%
rename from src/eressea/res/e3a/ships.xml
rename to res/e3a/ships.xml
diff --git a/src/eressea/res/e3a/spells.xml b/res/e3a/spells.xml
similarity index 100%
rename from src/eressea/res/e3a/spells.xml
rename to res/e3a/spells.xml
diff --git a/src/eressea/res/e3a/strings.xml b/res/e3a/strings.xml
similarity index 100%
rename from src/eressea/res/e3a/strings.xml
rename to res/e3a/strings.xml
diff --git a/src/eressea/res/e3a/terrains.xml b/res/e3a/terrains.xml
similarity index 100%
rename from src/eressea/res/e3a/terrains.xml
rename to res/e3a/terrains.xml
diff --git a/src/eressea/res/e3a/weapons.xml b/res/e3a/weapons.xml
similarity index 100%
rename from src/eressea/res/e3a/weapons.xml
rename to res/e3a/weapons.xml
diff --git a/src/eressea/res/e3a/weapons/crossbow.xml b/res/e3a/weapons/crossbow.xml
similarity index 100%
rename from src/eressea/res/e3a/weapons/crossbow.xml
rename to res/e3a/weapons/crossbow.xml
diff --git a/src/eressea/res/e3a/weapons/greatbow.xml b/res/e3a/weapons/greatbow.xml
similarity index 100%
rename from src/eressea/res/e3a/weapons/greatbow.xml
rename to res/e3a/weapons/greatbow.xml
diff --git a/src/eressea/res/e3a/weapons/greatsword.xml b/res/e3a/weapons/greatsword.xml
similarity index 100%
rename from src/eressea/res/e3a/weapons/greatsword.xml
rename to res/e3a/weapons/greatsword.xml
diff --git a/src/eressea/res/e3a/weapons/halberd.xml b/res/e3a/weapons/halberd.xml
similarity index 100%
rename from src/eressea/res/e3a/weapons/halberd.xml
rename to res/e3a/weapons/halberd.xml
diff --git a/src/eressea/res/e3a/weapons/laensword.xml b/res/e3a/weapons/laensword.xml
similarity index 100%
rename from src/eressea/res/e3a/weapons/laensword.xml
rename to res/e3a/weapons/laensword.xml
diff --git a/src/eressea/res/e3a/weapons/mallorncrossbow.xml b/res/e3a/weapons/mallorncrossbow.xml
similarity index 100%
rename from src/eressea/res/e3a/weapons/mallorncrossbow.xml
rename to res/e3a/weapons/mallorncrossbow.xml
diff --git a/src/eressea/res/e3a/weapons/mallornlance.xml b/res/e3a/weapons/mallornlance.xml
similarity index 100%
rename from src/eressea/res/e3a/weapons/mallornlance.xml
rename to res/e3a/weapons/mallornlance.xml
diff --git a/src/eressea/res/e3a/weapons/rustygreatsword.xml b/res/e3a/weapons/rustygreatsword.xml
similarity index 100%
rename from src/eressea/res/e3a/weapons/rustygreatsword.xml
rename to res/e3a/weapons/rustygreatsword.xml
diff --git a/src/eressea/res/e3a/weapons/rustyhalberd.xml b/res/e3a/weapons/rustyhalberd.xml
similarity index 100%
rename from src/eressea/res/e3a/weapons/rustyhalberd.xml
rename to res/e3a/weapons/rustyhalberd.xml
diff --git a/src/eressea/res/eressea/artrewards.xml b/res/eressea/artrewards.xml
similarity index 100%
rename from src/eressea/res/eressea/artrewards.xml
rename to res/eressea/artrewards.xml
diff --git a/src/eressea/res/eressea/buildings.xml b/res/eressea/buildings.xml
similarity index 100%
rename from src/eressea/res/eressea/buildings.xml
rename to res/eressea/buildings.xml
diff --git a/src/eressea/res/eressea/equipment.xml b/res/eressea/equipment.xml
similarity index 100%
rename from src/eressea/res/eressea/equipment.xml
rename to res/eressea/equipment.xml
diff --git a/src/eressea/res/eressea/items.xml b/res/eressea/items.xml
similarity index 100%
rename from src/eressea/res/eressea/items.xml
rename to res/eressea/items.xml
diff --git a/src/eressea/res/eressea/races.xml b/res/eressea/races.xml
similarity index 100%
rename from src/eressea/res/eressea/races.xml
rename to res/eressea/races.xml
diff --git a/src/eressea/res/eressea/spellinfo.xml b/res/eressea/spellinfo.xml
similarity index 100%
rename from src/eressea/res/eressea/spellinfo.xml
rename to res/eressea/spellinfo.xml
diff --git a/src/eressea/res/eressea/spells.xml b/res/eressea/spells.xml
similarity index 100%
rename from src/eressea/res/eressea/spells.xml
rename to res/eressea/spells.xml
diff --git a/src/eressea/res/eressea/strings.xml b/res/eressea/strings.xml
similarity index 100%
rename from src/eressea/res/eressea/strings.xml
rename to res/eressea/strings.xml
diff --git a/src/eressea/res/eressea/terrains.xml b/res/eressea/terrains.xml
similarity index 100%
rename from src/eressea/res/eressea/terrains.xml
rename to res/eressea/terrains.xml
diff --git a/src/eressea/res/names-dragons.xml b/res/names-dragons.xml
similarity index 100%
rename from src/eressea/res/names-dragons.xml
rename to res/names-dragons.xml
diff --git a/src/eressea/res/names-ghouls.xml b/res/names-ghouls.xml
similarity index 100%
rename from src/eressea/res/names-ghouls.xml
rename to res/names-ghouls.xml
diff --git a/src/eressea/res/names-skeletons.xml b/res/names-skeletons.xml
similarity index 100%
rename from src/eressea/res/names-skeletons.xml
rename to res/names-skeletons.xml
diff --git a/src/eressea/res/names-undead.xml b/res/names-undead.xml
similarity index 100%
rename from src/eressea/res/names-undead.xml
rename to res/names-undead.xml
diff --git a/src/eressea/res/names-zombies.xml b/res/names-zombies.xml
similarity index 100%
rename from src/eressea/res/names-zombies.xml
rename to res/names-zombies.xml
diff --git a/src/eressea/res/races/dragon.xml b/res/races/dragon.xml
similarity index 100%
rename from src/eressea/res/races/dragon.xml
rename to res/races/dragon.xml
diff --git a/src/eressea/res/races/goblin-2.xml b/res/races/goblin-2.xml
similarity index 100%
rename from src/eressea/res/races/goblin-2.xml
rename to res/races/goblin-2.xml
diff --git a/src/eressea/res/races/goblin-3.xml b/res/races/goblin-3.xml
similarity index 100%
rename from src/eressea/res/races/goblin-3.xml
rename to res/races/goblin-3.xml
diff --git a/src/eressea/res/races/wyrm.xml b/res/races/wyrm.xml
similarity index 100%
rename from src/eressea/res/races/wyrm.xml
rename to res/races/wyrm.xml
diff --git a/src/eressea/res/races/youngdragon.xml b/res/races/youngdragon.xml
similarity index 100%
rename from src/eressea/res/races/youngdragon.xml
rename to res/races/youngdragon.xml
diff --git a/scripts/cgi-bin/eressea-confirm.py b/scripts/cgi-bin/eressea-confirm.py
deleted file mode 100755
index 0a972f920..000000000
--- a/scripts/cgi-bin/eressea-confirm.py
+++ /dev/null
@@ -1,95 +0,0 @@
-#!/usr/bin/env python
-
-# If (password, custid) exist in the database, and the user is in state
-# 'WAITING', he will be changed to 'CONFIRMED'.
-
-import sys
-import MySQLdb
-import cgi
-import os
-import re
-
-# specify the filename of the template file
-HTMLTemplate = "eressea.html"
-DefaultTitle = "Eressea Anmeldung"
-dbname = "eressea"
-db=None
-tutorial_id=1 # the tuorial game has id 1
-
-# define a new function called Display
-# it takes one parameter - a string to Display
-def Display(Content, Title=DefaultTitle):
- TemplateHandle = open(HTMLTemplate, "r") # open in read only mode
- # read the entire file as a string
- TemplateInput = TemplateHandle.read()
- TemplateHandle.close() # close the file
-
- # this defines an exception string in case our
- # template file is messed up
- BadTemplateException = "There was a problem with the HTML template."
-
- SubResult = re.subn("", Title, TemplateInput)
- SubResult = re.subn("", Content, SubResult[0])
- if SubResult[1] == 0:
- raise BadTemplateException
-
- print "Content-Type: text/html\n\n"
- print SubResult[0]
- return
-
-
-def GetKey(Form, key):
- if Form.has_key(key):
- value=Form[key].value
- if value!="":
- return value
- return None
-
-
-def genpasswd():
- newpasswd=""
- chars = string.letters + string.digits
- for i in range(8):
- newpasswd = newpasswd + choice(chars)
- return newpasswd
-
-
-#Display("Derzeit ist wegen einer technischen Umstellung keine Anmeldung möglich")
-#sys.exit(0)
-
-Form = cgi.FieldStorage()
-
-custid=GetKey(Form, "custid")
-password=GetKey(Form, "password")
-
-if (password==None) or (custid==None):
- output="
Um Deine Anmeldung zu bestätigen musst Du das Formular vollständig ausfüllen.\n "
- for key in Form.keys():
- output=output+" "+str(key)+"="+str(Form[key])
- Display(output)
-else:
- db=MySQLdb.connect(db=dbname)
- cursor=db.cursor()
- try:
- custid=int(custid)
- except:
- custid=0
- query = "select u.status, s.id, s.game from users u, subscriptions s where u.id="+str(custid)+" and s.status in ('WAITING', 'CONFIRMED') and u.status not in ('INVALID', 'BANNED') and s.password='"+password+"'"
- exist=cursor.execute(query)
- if exist==0:
- Display('
Kundennummer oder Schlüssel falsch. Bitte beachte, dass Du beim Schlüssel auf Groß- und Kleinschreibung achten mußt.')
- else:
- status, sid, gid = cursor.fetchone()
- if os.environ.has_key('REMOTE_ADDR'):
- ip=os.environ['REMOTE_ADDR']
- cursor.execute("REPLACE userips (ip, user) VALUES ('"+ip+"', "+str(custid)+")")
- if status=='NEW' or status=='TUTORIAL':
- if tutorial_id!=None and gid==tutorial_id:
- # user confirms his tutorial participation
- cursor.execute("update users set status='TUTORIAL' where id="+str(custid))
- else:
- cursor.execute("update users set status='ACTIVE' where id="+str(custid))
- cursor.execute("update subscriptions set status='CONFIRMED' where id="+str(sid))
-
- Display("
Deine Anmeldung wurde bestätigt.");
- db.close()
diff --git a/scripts/cgi-bin/eressea-register.py b/scripts/cgi-bin/eressea-register.py
deleted file mode 100755
index 1d6c37a67..000000000
--- a/scripts/cgi-bin/eressea-register.py
+++ /dev/null
@@ -1,209 +0,0 @@
-#!/usr/bin/env python
-
-## this cgi script adds a new user to the eressea DB,
-## as well as a new subscription entry. it logs IP addresses for registrations.
-
-import sys
-import MySQLdb
-import os
-import cgi
-import re
-import string
-import smtplib
-from whrandom import choice
-
-# specify the filename of the template file
-HTMLTemplate = "eressea.html"
-MailTemplate="register.mail"
-DefaultTitle = "Eressea Anmeldung"
-dbname = "eressea"
-From = "accounts@eressea-pbem.de"
-locale="de"
-smtpserver = 'localhost'
-db=None
-game_id=0 # Eressea Main game
-tutorial_id=1 # 1 to active, None to disable tutorials
-
-# define a new function called Display
-# it takes one parameter - a string to Display
-def Display(Content, Title=DefaultTitle):
- TemplateHandle = open(HTMLTemplate, "r") # open in read only mode
- # read the entire file as a string
- TemplateInput = TemplateHandle.read()
- TemplateHandle.close() # close the file
-
- # this defines an exception string in case our
- # template file is messed up
- BadTemplateException = "There was a problem with the HTML template."
-
- SubResult = re.subn("", Title, TemplateInput)
- SubResult = re.subn("", Content, SubResult[0])
- if SubResult[1] == 0:
- raise BadTemplateException
-
- print "Content-Type: text/html\n\n"
- print SubResult[0]
- return
-
-
-def Send(email, custid, sid, firstname, password, game):
- cursor=db.cursor()
- cursor.execute("select count(*), g.name from games g, subscriptions s where g.id="+str(game)+" AND (s.status='WAITING' or s.status='CONFIRMED') AND g.id=s.game GROUP BY g.id")
- position, name = cursor.fetchone()
- TemplateHandle = open(MailTemplate+"."+string.lower(name)+"."+locale, "r") # open in read only mode
- # read the entire file as a string
- TemplateInput = TemplateHandle.read()
- TemplateHandle.close() # close the file
-
- SubResult = re.subn("", firstname, TemplateInput)
- SubResult = re.subn("", password, SubResult[0])
- SubResult = re.subn("", str(int(position)), SubResult[0])
- SubResult = re.subn("", name, SubResult[0])
- SubResult = re.subn("", str(int(custid)), SubResult[0])
- subject={"de":"Anmeldung","en":"Registration"}
- Msg="From: "+From+"\nTo: "+email+"\nSubject: "+name+" "+subject[locale]+"\n\n"
- Msg=Msg+SubResult[0]
- server=smtplib.SMTP(smtpserver)
- server.sendmail(From, email, Msg)
- server.close()
- return
-
-def GetKey(Form, key):
- if Form.has_key(key):
- value=Form[key].value
- if value!="":
- return value
- return None
-
-def ValidEmail(email):
- if string.find(email, "@")==-1:
- return 0
- elif string.find(email, " ")!=-1:
- return 0
- return 1
-
-def genpasswd():
- newpasswd=""
- chars = string.letters + string.digits
- for i in range(8):
- newpasswd = newpasswd + choice(chars)
- return newpasswd
-
-#Display("Derzeit ist wegen einer technischen Umstellung keine Anmeldung möglich")
-#sys.exit(0)
-
-Form = cgi.FieldStorage()
-
-email=GetKey(Form, "email")
-firstname=GetKey(Form, "firstname")
-lastname=GetKey(Form, "lastname")
-#info=GetKey(Form, "info")
-address=GetKey(Form, "address")
-city=GetKey(Form, "city")
-country=GetKey(Form, "country")
-phone=GetKey(Form, "phone")
-race=GetKey(Form, "race")
-locale=GetKey(Form, "locale")
-
-referrer=GetKey(Form, "referrer")
-firsttime=GetKey(Form, "firsttime")
-bonus=GetKey(Form, "bonus")
-
-if (locale==None) or (lastname==None) or (race==None) or (firstname==None) or (address==None) or (city==None):
- output="
Um Dich zu Eressea anzumelden musst Du das Formular vollständig ausfüllen.\n "
- for key in Form.keys():
- output=output+" "+key+": "+Form[key].value+"\n"
- Display(output)
-elif ValidEmail(email)==0:
- output="
Um Dich zu Eressea anzumelden musst Du eine gültige Email-Adresse angeben.\n "
- Display(output)
-else:
- db=MySQLdb.connect(db=dbname)
- cursor=db.cursor()
- # check if he is already entered in the main game:
- exist=cursor.execute("select u.id from users u, subscriptions s where s.user=u.id AND s.game="+str(game_id)+" AND u.email='"+email+"' and (s.status='WAITING' or s.status='CONFIRMED')")
- if exist:
- text={"de":"Du stehst bereits auf der Warteliste","en":"You are already on the waiting list"}
- Display('
'+text[locale])
- else:
- bans=cursor.execute('select regex, reason from bannedemails')
- while bans:
- bans=bans-1
- regexp, reason = cursor.fetchone()
- if (re.match(regexp, email, re.IGNORECASE))!=None:
- Display('Deine Email-Adresse ist für Eressea nicht zugelassen. '+reason)
- sys.exit(0)
-
- # create a new user record
- fields = "firstname, lastname, locale, email, address, city"
- values = "'"+firstname+"', '"+lastname+"', '"+locale+"', '"+email+"', '"+address+"', '"+city+"'"
- if phone!=None:
- fields=fields+", phone"
- values=values+", '"+phone+"'"
-# if info!=None:
-# fields=fields+", info"
-# values=values+", '"+info+"'"
- if country!=None:
- fields=fields+", country"
- values=values+", "+country+""
- if referrer!=None:
- fields=fields+", referrer"
- values=values+", '"+referrer+"'"
- if firsttime!=None:
- fields=fields+", firsttime"
- if firsttime=='yes':
- values=values+", 1"
- else:
- values=values+", 0"
- exist=cursor.execute("select password, status, id from users where email='"+email+"'")
- custid=0
- status='NEW'
- if exist:
- # user exists, update his data
- password, status, custid=cursor.fetchone()
- if status=='BANNED':
- Display('Dein Account ist gesperrt. Bitte wende Dich an accounts@eressea-pbem.de falls Du Fragen zu dieser Meldung hast.')
- sys.exit(0)
- fields=fields+", id, status"
- values=values+", "+str(custid)+", '"+status+"'"
- command="REPLACE"
- cursor.execute("REPLACE into users ("+fields+") VALUES ("+values+")")
- else:
- password = genpasswd()
- fields=fields+", password, status"
- values=values+", '"+password+"', 'NEW'"
- cursor.execute("INSERT into users ("+fields+") VALUES ("+values+")")
- cursor.execute("SELECT LAST_INSERT_ID() from dual")
- custid=cursor.fetchone()[0]
-
- # track IP addresses
- ip=None
- if os.environ.has_key('REMOTE_ADDR'):
- ip=os.environ['REMOTE_ADDR']
- if ip!=None:
- cursor.execute("REPLACE userips (ip, user) VALUES ('"+ip+"', "+str(int(custid))+")")
-
- game = game_id
- if tutorial_id!=None and status!='ACTIVE':
- game=tutorial_id
- exist = cursor.execute("select id, password from subscriptions where status='WAITING' AND user="+str(custid)+" and game="+str(game))
- if exist:
- sid, password = cursor.fetchone()
- else:
- # add a subscription record
- password = genpasswd()
- values="'WAITING', '"+password+"'"
- fields="status, password"
- if bonus!=None:
- fields=fields+", bonus"
- if bonus=='yes':
- values=values+", 1"
- else:
- values=values+", 0"
- cursor.execute("insert into subscriptions (user, race, game, "+fields+") VALUES ("+str(int(custid))+", '"+race+"', "+str(game)+", "+values+")")
- cursor.execute("SELECT LAST_INSERT_ID() from dual")
- sid = cursor.fetchone()[0]
- Send(email, custid, sid, firstname, password, game)
- text={"de":"Deine Anmeldung wurde bearbeitet. Eine EMail mit Hinweisen ist unterwegs zu Dir", "en":"Your application was processed. An email containing further instructions is being sent to you"}
- Display("
"+text[locale]+".")
- db.close()
diff --git a/scripts/cgi-bin/info.py b/scripts/cgi-bin/info.py
deleted file mode 100755
index 86aa74ca0..000000000
--- a/scripts/cgi-bin/info.py
+++ /dev/null
@@ -1,319 +0,0 @@
-#!/usr/bin/env python
-
-import sys
-import MySQLdb
-import cgi
-import re
-import smtplib
-
-# specify the filename of the template file
-scripturl="http://eressea.upb.de/cgi-bin/eressea/info.py"
-TemplateFile = "/home/enno/www/cgi-bin/vinyambar.html"
-DefaultTitle = "Vinyambar Datenbank"
-dbname = "vinyambar"
-From = "accounts@vinyambar.de"
-smtpserver = 'localhost'
-Errors = ""
-
-# define a new function called Display
-# it takes one parameter - a string to Display
-def Display(Content, Title=DefaultTitle):
- TemplateHandle = open(TemplateFile, "r") # open in read only mode
- # read the entire file as a string
- TemplateInput = TemplateHandle.read()
- TemplateHandle.close() # close the file
-
-# for key in Form.keys():
-# Content=Content+" "+str(key)+"="+str(Form[key])
-
- # this defines an exception string in case our
- # template file is messed up
- BadTemplateException = "There was a problem with the HTML template."
-
- SubResult = re.subn("", Title, TemplateInput)
- SubResult = re.subn("", Content, SubResult[0])
- if SubResult[1] == 0:
- raise BadTemplateException
-
- print "Content-Type: text/html\n\n"
- print SubResult[0]
- return
-
-
-def SendTransfer(userid, factionid, game):
- db = MySQLdb.connect(db=dbname)
- cursor=db.cursor()
- cursor.execute("select email, firstname from users where id="+str(userid))
- email, firstname = cursor.fetchone()
- Msg="From: "+From+"\nTo: "+email+"\nSubject: Vinambar Passwort\n\n"
- Msg=Msg+"Hallo, "+firstname+"\n"
- Msg=Msg+"Ein Spieler hat Dir seine Partei " + factionid + " im Spiel " + game + "\n"
- Msg=Msg+"übertragen. Um die Partei zu übernehmen, gehe bitte auf die Webseite \n"
- Msg=Msg+"http://www.vinyambar.de/accounts.shtml, und akzeptiere dort den Transfer.\n"
- server=smtplib.SMTP(smtpserver)
- server.sendmail(From, email, Msg)
- server.close()
- db.close()
- return
-
-
-def SendPass(email):
- try:
- db = MySQLdb.connect(db=dbname)
- cursor=db.cursor()
-# print custid
- cursor.execute("select id, email, password from users where email='"+email+"'")
- custid, email, password = cursor.fetchone()
- Msg="From: "+From+"\nTo: "+email+"\nSubject: Vinambar Passwort\n\n"
- Msg=Msg+"Deine Kundennummer ist: "+str(int(custid))+"\n"
- Msg=Msg+"Dein Vinyambar-Passwort lautet: "+password+"\n"
- Msg=Msg+"\nDiese Mail wurde an Dich versandt, weil Du (oder jemand anders) \n"
- Msg=Msg+"es im Formular auf http://www.vinyambar.de/accounts.shtml angefordert hat.\n"
- server=smtplib.SMTP(smtpserver)
- server.sendmail(From, email, Msg)
- server.close()
- db.close()
- Display('
Beim Versenden des Passwortes ist ein Fehler aufgetreten. Eventuell ist die email-Adresse unbekannt
', 'Kundendaten für '+email)
-
-
-def ShowInfo(custid, Password):
- global Errors
- db = MySQLdb.connect(db=dbname)
- cursor = db.cursor()
- query=("select firstname, lastname, email, address, city, country, phone, status "+
- "from users "+
- "where id="+str(custid)+" and password='"+Password+"' ")
-
- results = cursor.execute(query)
- if results != 0:
- firstname, lastname, email, address, city, country, phone, status = cursor.fetchone()
- if status=='WAITING':
- cursor.execute("update users set status='CONFIRMED' where id="+str(custid))
- cursor.execute("select max(date), max(id) from transactions")
- lastdate, id = cursor.fetchone()
-
- nraces = cursor.execute("select distinct race, name from races where locale='de'")
- races=[('', 'Keine Anmeldung')]
- while nraces>0:
- nraces = nraces - 1
- races.append(cursor.fetchone())
-
- output = '
Letzter Buchungstag: '+str(lastdate)[0:10]+'
"
- else:
- output = "Die Kundennummer oder das angegebene Passwort sind nicht korrekt."
- db.close()
- Display(output, "Kundendaten #"+str(custid))
- Errors = ""
-
-def TransferFaction(sid, faction, olduser, newuser, game, gid):
- db = MySQLdb.connect(db=dbname)
- update = db.cursor()
- exist = update.execute("select id from users where id="+str(int(newuser)))
- if exist==1:
- update.execute("INSERT into transfers (subscription, src, dst, reason) values ("+str(int(sid))+", "+str(int(olduser))+", "+str(int(newuser))+", 'TRANSFER')")
- update.execute("UPDATE subscriptions set status='TRANSFERED', user=" + str(newuser) + " where id="+str(sid))
- SendTransfer(newuser, faction, game);
- db.close()
- return
-
-def Save(custid, Password):
- global Errors
- validkeys=['email','address','lastname','firstname','city','password','phone']
- values='id='+str(custid)
- for key in Form.keys():
- if key in validkeys:
- values=values+", "+key+"='"+Form[key].value+"'"
- db = MySQLdb.connect(db=dbname)
- cursor=db.cursor()
- cursor.execute('UPDATE users SET '+values+' where id='+str(custid))
-
- ngames = cursor.execute("select id from games where status='WAITING'")
- while ngames > 0:
- ngames=ngames - 1
- gid = cursor.fetchone()[0]
- key="race_"+str(int(gid))
- update = db.cursor()
- if Form.has_key(key):
- newrace=Form[key].value
- if newrace=='':
- newrace=None
- if newrace==None:
- update.execute('delete from subscriptions where user='+str(int(custid))+' and game='+str(int(gid)))
- else:
- exist=update.execute('select id, race from subscriptions where game='+str(int(gid))+' and user='+str(int(custid)))
- if exist>0:
- sid, race = update.fetchone()
- if race!=newrace:
- update.execute("update subscriptions set race='"+newrace+"' where id="+str(int(sid)))
- else:
- update.execute("insert subscriptions (race, user, status, game) values ('"+newrace+"', "+str(int(custid))+", 'WAITING', "+str(int(gid))+")")
- else:
- update.execute('delete from subscriptions where user='+str(int(custid))+' and game='+str(int(gid)))
-
- nfactions = cursor.execute("select g.id, g.name, s.id, faction from games g, subscriptions s where s.status='ACTIVE' and s.user="+str(custid) + " and s.game=g.id")
- while nfactions > 0:
- gid, game, sid, faction = cursor.fetchone()
- if Form.has_key("cancel_"+faction):
- update = db.cursor()
- update.execute("UPDATE subscriptions set status='CANCELLED' where id="+str(int(sid)))
- elif Form.has_key("transfer_"+faction):
- newuser = int(Form["transfer_"+faction].value)
- TransferFaction(sid, faction, custid, newuser, game, gid)
- nfactions = nfactions - 1
-
- nfactions = cursor.execute("select g.id, g.name, s.id, faction from games g, subscriptions s where s.status='TRANSFERED' and s.user="+str(custid) + " and s.game=g.id")
- while nfactions > 0:
- gid, game, sid, faction = cursor.fetchone()
- if Form.has_key("accept_"+faction):
- update = db.cursor()
- i = update.execute("SELECT count(*) from subscriptions where status='ACTIVE' and game="+str(int(gid)))
- if i==0:
- update.execute("UPDATE subscriptions set status='ACTIVE' where id="+str(int(sid)))
- else:
- Errors=Errors+"Du hast bereits eine Aktive Partei in "+game+" \n"
- nfactions = nfactions - 1
-
- nfactions = cursor.execute("select g.name, s.id, faction from games g, subscriptions s where s.status='CANCELLED' and s.user="+str(custid) + " and s.game=g.id")
- while nfactions > 0:
- game, sid, faction = cursor.fetchone()
- if Form.has_key("activate_"+faction):
- update = db.cursor()
- update.execute("UPDATE subscriptions set status='ACTIVE' where id="+str(int(sid)))
- nfactions = nfactions - 1
-
- db.close()
- ShowInfo(custid, Password)
-# Display("Noch nicht implementiert", "Daten speichern für Kunde #"+str(custid))
-
-
-Form = cgi.FieldStorage()
-
-if Form.has_key("user"):
- custid = int(Form["user"].value)
-else:
- custid = 0
-
-if Form.has_key("pass"):
- Password = Form["pass"].value
-else:
- Password=""
-
-if Form.has_key("sendpass"):
- if Form.has_key("email"):
- Email = Form["email"].value
- else:
- Email=""
- SendPass(Email)
-elif Form.has_key("save"):
- Save(custid, Password)
-else:
- ShowInfo(custid, Password)
diff --git a/scripts/cgi-bin/poll2001.py b/scripts/cgi-bin/poll2001.py
deleted file mode 100755
index 7ca2d4ee3..000000000
--- a/scripts/cgi-bin/poll2001.py
+++ /dev/null
@@ -1,213 +0,0 @@
-#!/usr/bin/env python
-
-import sys
-import MySQLdb
-import cgi
-import re
-
-# specify the filename of the template file
-TemplateFile = "vinyambar.html"
-DefaultTitle = "Eressea Umfrage 2001"
-dbname = "eressea"
-myurl="http://eressea.upb.de/cgi-bin/eressea/poll2001.py"
-
-# define a new function called Display
-# it takes one parameter - a string to Display
-print "Content-Type: text/html\n\n"
-def Display(Content, Title=DefaultTitle):
- TemplateHandle = open(TemplateFile, "r") # open in read only mode
- # read the entire file as a string
- TemplateInput = TemplateHandle.read()
- TemplateHandle.close() # close the file
-
- # this defines an exception string in case our
- # template file is messed up
- BadTemplateException = "There was a problem with the HTML template."
-
- SubResult = re.subn("", Title, TemplateInput)
- SubResult = re.subn("", Content, SubResult[0])
- if SubResult[1] == 0:
- raise BadTemplateException
-
- print SubResult[0]
-
-def ReadForm(Form):
- output=""
-
- if (Form.has_key('faction') & Form.has_key('password'))==0:
- Display('Partei oder Passwort nicht angegeben')
- sys.exit()
- faction=Form['faction'].value
- password=Form['password'].value
- db = MySQLdb.connect(db=dbname)
- cursor = db.cursor()
- num = cursor.execute('SELECT password from factions where id=\''+faction+'\' and password=\''+password+'\'')
- if num==0:
- Display('Partei oder Passwort ungültig')
- sys.exit()
-
- fields="faction"
- values="'"+faction+"'"
- booleans=['otherpbem', 'party','othertools','crtools','magellan','emap','ehmv','echeck','vorlage','esurvey','mercator', 'madmax', 'slow', 'fast']
- for field in booleans:
- if Form.has_key(field):
- fields=fields+", "+field
- values=values+", 1"
- ints=['age','country','turn','starts','socializer','killer','explorer','achiever']
- for field in ints:
- if Form.has_key(field):
- fields=fields+", "+field
- values=values+", "+Form[field].value
- strings=['referer','refererother','fun','toolsother', 'freetext']
- for field in strings:
- if Form.has_key(field):
- fields=fields+", "+field
- values=values+", '"+Form[field].value+"'"
- query="REPLACE poll ("+fields+") VALUES ("+values+")"
- # print query
- cursor.execute(query)
-
- Display('Danke für die Teilnahme an der Umfrage.\n
Ergebnisse ansehen\n')
-
-def ShowResult():
- db = MySQLdb.connect(db=dbname)
- cursor = db.cursor()
- results=cursor.execute('SELECT factions.email, poll.freetext, poll.age, countries.name FROM factions, poll, countries WHERE factions.id=poll.faction AND countries.id=poll.country')
- answers=int(results)
- ages = {}
- countries = {}
- comments = "
Kommentare
\n"
- while results > 0:
- results=results-1
- email, freetext, age, country=cursor.fetchone()
-
- if freetext!=None:
- name=""
-# if email==None:
-# email="unknown"
-# name = " ("+re.subn('@', " at ", email)[0]+")"
- comments=comments+"
"+freetext+name+"\n"
- if age!=None:
- if (ages.has_key(age)):
- ages[age]=ages[age]+1
- else:
- ages[age]=1;
- if country!=None:
- if (countries.has_key(country)):
- countries[country]=countries[country]+1
- else:
- countries[country]=1;
-
- personaltext="
Spielerprofil
\n"
- personals={ 'age': 'Alter', 'turn':'Startrunde', 'starts':'Anzahl Starts'}
- for key in personals.keys():
- cursor.execute("SELECT AVG("+key+"), MIN("+key+"), MAX("+key+") FROM poll")
- kavg, kmin, kmax = cursor.fetchone()
- personaltext=personaltext+personals[key]+": "+str(int(kmin))+" bis "+str(int(kmax))+" (Durchschnitt "+str(kavg)+") \n"
- cursor.execute("select count(*) from poll where party=1")
- value = cursor.fetchone()[0]
- personaltext=personaltext+str(int(value))+" der "+str(answers)+" Spieler haben schon einmal wegen Eressea eine Party frühzeitig verlassen."
-
- funtypes= {
- 'quitting':'Ich höre auf',
- 'okay':'Geht so',
- 'greatfun':'Macht großen Spaß',
- 'bestgame':'Bestes Spiel der Welt'
- }
- funtext ="
Spielspaß
\n
\n"
- for key in funtypes.keys():
- cursor.execute("SELECT COUNT(*) FROM poll WHERE fun='"+key+"'")
- value = int(cursor.fetchone()[0])
- funtext=funtext+"
\n"
- for tool in toolnames:
- results=cursor.execute('SELECT count(*) from poll where '+tool+'=1')
- if results==1:
- num=int(cursor.fetchone()[0]);
- tooltext=tooltext+"
"+tool+'
'+str(num)+' ('+str(int(num*100.0/answers))+'%)
\n'
- tooltext=tooltext+"
...andere
\n"
- num=cursor.execute("SELECT DISTINCT toolsother FROM poll where toolsother is not null order by toolsother")
- while num!=0:
- num=num-1
- text=str(cursor.fetchone()[0])
- tooltext=tooltext+text+" \n"
-
- referernames= {'friends':'Freunde & Familie','pbemdirect':'PBEM Webseiten','other':'Andere', 'otherpbem':'Andere PBEM', 'searchengi':'Suchmaschinen','press':'Presse','yahoo':'Yahoo & Co,' }
- referertext="
Wie bist Du zu Eressea gekommen?
\n
\n"
- for referer in referernames.keys():
- results=cursor.execute("SELECT count(*) from poll where referer='"+referer+"'")
- if results==1:
- num=int(cursor.fetchone()[0]);
- referertext=referertext+"
"+referernames[referer]+'
'+str(num)+"
\n"
- referertext=referertext+"
...andere
\n"
- num=cursor.execute("SELECT DISTINCT refererother FROM poll where refererother is not null order by refererother")
- while num!=0:
- num=num-1
- text=str(cursor.fetchone()[0])
- referertext=referertext+text+" \n"
-
- scenarionames={'fast':'Zweimal pro Woche','slow':'Alle zwei Wochen','madmax':'Endzeit-Eressea'}
- scenariotext="
Kommerzielle Szenarios
\n
\n"
- for scenario in scenarionames.keys():
- results=cursor.execute('SELECT count(*) from poll where '+scenario+'=1')
- if results==1:
- scenariotext=scenariotext+"
"+scenarionames[scenario]+'
'+str(int(cursor.fetchone()[0]))+'
\n'
- scenariotext=scenariotext+"
\n"
-# agefile=open('poll2001-age.dat', 'w')
-# countryfile=open('poll2001-country.dat', 'w')
-# for age in ages.keys():
-# agefile.write(str(int(age)) + '\t' + str(ages[age]) + '\n')
- countrytext = "
Heimatländer
\n
"
- for country in countries.keys():
-# countryfile.write(country + '\t' + str(countries[country]) + '\n')
- countrytext=countrytext+"
"+country + '
' + str(countries[country]) + '
\n'
- countrytext=countrytext+"
\n"
-# agefile.close()
-# countryfile.close()
- Display(personaltext+countrytext+typetext+funtext+scenariotext+referertext+tooltext+comments)
-
-Form = cgi.FieldStorage()
-if Form.has_key('faction'):
- ReadForm(Form)
-else:
- ShowResult()
-
-#+--------------+-------------+------+-----+---------+-------+
-#| Field | Type | Null | Key | Default | Extra |
-#+--------------+-------------+------+-----+---------+-------+
-#| faction | varchar(6) | YES | | NULL | |
-#| age | int(11) | YES | | NULL | |
-#| country | int(11) | YES | | NULL | |
-#| turn | int(11) | YES | | NULL | |
-#| starts | int(11) | YES | | NULL | |
-#| otherpbem | tinyint(1) | | | 0 | |
-#| party | tinyint(1) | | | 0 | |
-#| referer | varchar(10) | YES | | NULL | |
-#| refererother | varchar(64) | YES | | NULL | |
-#| fun | varchar(10) | YES | | NULL | |
-#| socializer | int(11) | YES | | NULL | |
-#| killer | int(11) | YES | | NULL | |
-#| explorer | int(11) | YES | | NULL | |
-#| achiever | int(11) | YES | | NULL | |
-#| scenarios | varchar(10) | YES | | NULL | |
-#| magellan | tinyint(1) | | | 0 | |
-#| emap | tinyint(1) | | | 0 | |
-#| ehmv | tinyint(1) | | | 0 | |
-#| vorlage | tinyint(1) | | | 0 | |
-#| esurvey | tinyint(1) | | | 0 | |
-#| mercator | tinyint(1) | | | 0 | |
-#| echeck | tinyint(1) | | | 0 | |
-#| toolsother | varchar(64) | YES | | NULL | |
-#+--------------+-------------+------+-----+---------+-------+
-
diff --git a/scripts/cgi-bin/register.mail.de b/scripts/cgi-bin/register.mail.de
deleted file mode 100644
index d910c47d4..000000000
--- a/scripts/cgi-bin/register.mail.de
+++ /dev/null
@@ -1,22 +0,0 @@
-Hallo ,
-
-Du stehst mit deiner Anmeldung bei Eressea auf der Warteliste für neue Parteien
-derzeit an Position . Um Deine Anmeldung zu bestätigen, gehe bitte
-auf die folgende Webseite, und gib dort zur Bestätigung deine Kundennummer
-und den Bestätigungsschlüssel ein.
-
- http://eressea-pbem.de/confirm.html
- Kundennummer:
- Schlüssel:
-
-Um sicherzustellen, das nur interessierte Spieler in der Warteliste sind,
-muß diese Prozedur einmal wöchentlich wiederholt werden. Du bekommst daher
-wöchentlich eine Erinnerungsmail, in der Du auch deine aktuelle Position in
-der Warteliste sehen kannst.
-
-Solltest Du den Schlüssel bis Sonntag früh nicht eingegeben haben, wird
-deine Anmeldung aus der Warteliste entfernt, und Du bekommst keine weiteren
-Mails von uns.
-
-
-Das Eressea-Team
diff --git a/scripts/cgi-bin/register.mail.en b/scripts/cgi-bin/register.mail.en
deleted file mode 100644
index 77e6a0b82..000000000
--- a/scripts/cgi-bin/register.mail.en
+++ /dev/null
@@ -1,20 +0,0 @@
-Hello ,
-
-You are now entered into the waiting list of Eressea, at position .
-To confirm your subscription, please go to the following URL and enter your
-Customer-ID and confirmation key.
-
- http://eressea-pbem.de/en/confirm.html
- Customer ID:
- Key:
-
-To make sure that only those players interested in playing remain on the
-list, you need to repeat this procedure once every week. We will send you this
-reminder by mail, in which you'll also see your updated position on the
-waiting list.
-
-If you do not enter the key before sunday morning 9:00 CET, your
-registration will be considered cancelled, and you will receive no further
-email from us.
-
-The Eressea Team
diff --git a/scripts/cgi-bin/standin.py b/scripts/cgi-bin/standin.py
deleted file mode 100755
index abcceb691..000000000
--- a/scripts/cgi-bin/standin.py
+++ /dev/null
@@ -1,125 +0,0 @@
-#!/usr/bin/env python
-
-import smtplib
-import MySQLdb
-import cgi
-import re
-
-# specify the filename of the template file
-scripturl='http://eressea.upb.de/cgi-bin/eressea/standin.py'
-TemplateFile = "vinyambar.html"
-DefaultTitle = "Vinyambar Parteibörse"
-dbname = "vinyambar"
-From = "accounts@vinyambar.de"
-Errors = ""
-db = MySQLdb.connect(db=dbname)
-smtpserver='localhost'
-notify='accounts@vinyambar.de'
-minnmr=0
-
-# define a new function called Display
-# it takes one parameter - a string to Display
-def Display(Content, Title=DefaultTitle):
- TemplateHandle = open(TemplateFile, "r") # open in read only mode
- # read the entire file as a string
- TemplateInput = TemplateHandle.read()
- TemplateHandle.close() # close the file
-
-# for key in Form.keys():
-# Content=Content+" "+str(key)+"="+str(Form[key])
-
- # this defines an exception string in case our
- # template file is messed up
- BadTemplateException = "There was a problem with the HTML template."
-
- SubResult = re.subn("", Title, TemplateInput)
- SubResult = re.subn("", Content, SubResult[0])
- if SubResult[1] == 0:
- raise BadTemplateException
-
- print "Content-Type: text/html\n\n"
- print SubResult[0]
- return
-
-def ShowPage():
- cursor=db.cursor()
- maxturn = {}
- games = cursor.execute("SELECT max(lastturn), game from subscriptions GROUP by game")
- while games>0:
- games=games-1
- lastturn, game = cursor.fetchone()
- maxturn[game] = lastturn
- output='
Um eine der folgenden Parteien zu übernehmen, musst du zuerst ein Spielerkonto anlegen. Wenn Du eines hast, markiere die Partei, die Du übernehmen willst, und trage Kundennummer und Kundenpasswort ein.'
- query = "SELECT g.id, g.name, s.faction, s.lastturn, s.id, r.name, s.info from games g, subscriptions s, races r where s.game=g.id and s.race=r.race and s.status='CANCELLED' order by s.lastturn DESC"
- results = cursor.execute(query)
- output=output+'
'
- Display(output)
- return
-
-Form = cgi.FieldStorage()
-
-custid=None
-password=None
-if Form.has_key("user"):
- custid = int(Form["user"].value)
-
-if Form.has_key("pass"):
- password = Form["pass"].value
-
-if (password!=None) & (custid!=None):
- cursor=db.cursor()
- output=""
- if cursor.execute("select firstname, lastname, email, id from users where password='"+password+"' and id="+str(int(custid)))==1:
- firstname, lastname, email, custid = cursor.fetchone()
- c = cursor.execute("SELECT id, game, password, faction, user from subscriptions where status='CANCELLED'")
- while c>0:
- c=c-1
- sid, gid, newpass, faction, uid = cursor.fetchone()
- if Form.has_key("accept_"+str(int(sid))):
- update = db.cursor()
- update.execute("INSERT into transfers (subscription, src, dst, reason) values ("+str(int(sid))+", "+str(int(uid))+", "+str(int(custid))+", 'STANDIN')")
- update.execute("UPDATE subscriptions set user=" + str(int(custid)) + ", status='ACTIVE' where id=" + str(int(sid)))
- output=output+"Die Partei " + faction + " wurde Dir überschrieben. Eine Email mit dem Passwort und weiteren Hinweisen ist unterwegs zu Dir. "
- server=smtplib.SMTP(smtpserver)
-
- Msg="From: "+From+"\nTo: "+email+"\nSubject: Vinambar Parteiuebernahme\n\n"
- Msg=Msg+"Das Passwort für deine neue Vinyambar-Partei "+faction+" lautet\n"
- Msg=Msg+" "+newpass+"\n"
- Msg=Msg+"\nUm den Report der letzten Woche zu erhalten, schicke eine Mail mit dem Betreff\n"
- Msg=Msg+"VIN"+str(int(gid))+" REPORT "+faction+" \""+newpass+"\" an die Adresse "
- Msg=Msg+"vinyambar@eressea.amber.kn-bremen.de"
- server.sendmail(From, email, Msg)
-
- Msg="From: "+From+"\nTo: "+notify+"\nSubject: Vinambar Parteiuebernahme\n\n"
- Msg=Msg+"Die Partei "+faction+" wurde übernommen.\n"
- Msg=Msg+" Spieler: "+str(int(custid))+"\n"
- Msg=Msg+" Name : "+firstname+" "+lastname+"\n"
- Msg=Msg+" email : "+email+"\n"
- server.sendmail(From, notify, Msg)
-
- server.close()
- else:
- output="Fehler in Passwort oder Kundennummer "
- Display(output)
-else:
- ShowPage()
-
-db.close()
diff --git a/scripts/cgi-bin/vinyambar-register.py b/scripts/cgi-bin/vinyambar-register.py
deleted file mode 100755
index 39c3a6f99..000000000
--- a/scripts/cgi-bin/vinyambar-register.py
+++ /dev/null
@@ -1,132 +0,0 @@
-#!/usr/bin/env python
-
-import sys
-import MySQLdb
-import os
-import cgi
-import re
-import string
-import smtplib
-from whrandom import choice
-
-# specify the filename of the template file
-scripturl="http://eressea.upb.de/cgi-bin/eressea/vinyambar-register.py"
-HTMLTemplate = "vinyambar.html"
-MailTemplate="vinyambar-register.mail"
-DefaultTitle = "Vinyambar Anmeldung"
-dbname = "vinyambar"
-From = "accounts@vinyambar.de"
-locale="de"
-smtpserver = 'localhost'
-db=None
-
-# define a new function called Display
-# it takes one parameter - a string to Display
-def Display(Content, Title=DefaultTitle):
- TemplateHandle = open(HTMLTemplate, "r") # open in read only mode
- # read the entire file as a string
- TemplateInput = TemplateHandle.read()
- TemplateHandle.close() # close the file
-
- # this defines an exception string in case our
- # template file is messed up
- BadTemplateException = "There was a problem with the HTML template."
-
- SubResult = re.subn("", Title, TemplateInput)
- SubResult = re.subn("", Content, SubResult[0])
- if SubResult[1] == 0:
- raise BadTemplateException
-
- print "Content-Type: text/html\n\n"
- print SubResult[0]
- return
-
-
-def Send(email, custid, firstname, password, position):
- TemplateHandle = open(MailTemplate+"."+locale, "r") # open in read only mode
- # read the entire file as a string
- TemplateInput = TemplateHandle.read()
- TemplateHandle.close() # close the file
-
- SubResult = re.subn("", firstname, TemplateInput)
- SubResult = re.subn("", password, SubResult[0])
- SubResult = re.subn("", str(int(position)), SubResult[0])
- SubResult = re.subn("", str(int(custid)), SubResult[0])
-
- Msg="From: "+From+"\nTo: "+email+"\nSubject: Vinyambar Anmeldung\n\n"
- Msg=Msg+SubResult[0]
- server=smtplib.SMTP(smtpserver)
- server.sendmail(From, email, Msg)
- server.close()
- return
-
-
-def GetKey(Form, key):
- if Form.has_key(key):
- value=Form[key].value
- if value!="":
- return value
- return None
-
-def ValidEmail(email):
- if string.find(email, "@")==-1:
- return 0
- elif string.find(email, " ")!=-1:
- return 0
- return 1
-
-def genpasswd():
- newpasswd=""
- chars = string.letters + string.digits
- for i in range(8):
- newpasswd = newpasswd + choice(chars)
- return newpasswd
-
-
-Form = cgi.FieldStorage()
-
-email=GetKey(Form, "email")
-firstname=GetKey(Form, "firstname")
-lastname=GetKey(Form, "lastname")
-address=GetKey(Form, "address")
-city=GetKey(Form, "city")
-country=GetKey(Form, "country")
-phone=GetKey(Form, "phone")
-
-if (locale==None) or (lastname==None) or (firstname==None) or (address==None) or (city==None):
- output="
Um Dich zu Vinyambar anzumelden musst Du das Formular vollständig ausfüllen.\n "
- for key in Form.keys():
- output=output+" "+key+": "+Form[key].value+"\n"
- Display(output)
-elif ValidEmail(email)==0:
- output="
Um Dich zu Vinyambar anzumelden musst Du eine gültige Email-Adresse angeben.\n "
- Display(output)
-else:
- db=MySQLdb.connect(db=dbname)
- cursor=db.cursor()
- exist=cursor.execute("select id from users where email='"+email+"'")
- if exist>0:
- Display('
Du hast bereits einen Eintrag in der Datenbank.')
- else:
- password=genpasswd()
- fields = "firstname, lastname, locale, email, address, city, status, password"
- values = "'"+firstname+"', '"+lastname+"', '"+locale+"', '"+email+"', '"+address+"', '"+city+"', 'WAITING', '"+password+"'"
- if phone!=None:
- fields=fields+", phone"
- values=values+", '"+phone+"'"
- if country!=None:
- fields=fields+", country"
- values=values+", "+country+""
- cursor.execute("insert into users ("+fields+") VALUES ("+values+")")
- cursor.execute("SELECT LAST_INSERT_ID() from dual")
- custid=cursor.fetchone()[0]
- if os.environ.has_key('REMOTE_ADDR'):
- ip=os.environ['REMOTE_ADDR']
- if ip!=None:
- cursor.execute("REPLACE userips (ip, user) VALUES ('"+ip+"', "+str(int(custid))+")")
- cursor.execute("select count(*) from users where status='WAITING' or status='CONFIRMED'")
- waiting=cursor.fetchone()[0]
- Send(email, custid, firstname, password, waiting)
- text={"de":"Deine Anmeldung wurde bearbeitet. Eine EMail mit Hinweisen ist unterwegs zu Dir", "en":"Your application was processed. An email containing further instructions is being sent to you"}
- Display("
"+text[locale]+".")
- db.close()
diff --git a/scripts/cvsuser/build.sh b/scripts/cvsuser/build.sh
deleted file mode 100755
index 64a3f949b..000000000
--- a/scripts/cvsuser/build.sh
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/bin/bash
-echo "running build.sh"
-module=eressea
-rootdir=/home/cvs/checkout/${module}
-# www=$rootdir/www-data -- no web archives of eressea source
-subdir="source"
-
-date >> ${rootdir}/buildlog
-
-echo ==---------------------==
-echo `date` : Rebuilding ${module}
-echo ==---------------------==
-
-for sub in $subdir
-do
- # update the source tree
- cd $rootdir/$sub
- cvs -q update -drP
- # create the source archive
- # cd $rootdir
- # tar czf ${www}/downloads/${module}-${sub}.tar.gz ${sub}
-done
-cat >| parameters
-${rootdir}/senddiff.pl `cat parameters` 2>&1 >> /tmp/senddiff.log
diff --git a/scripts/cvsuser/commit-source.sh b/scripts/cvsuser/commit-source.sh
deleted file mode 100755
index 11518142b..000000000
--- a/scripts/cvsuser/commit-source.sh
+++ /dev/null
@@ -1,42 +0,0 @@
-#!/bin/sh
-NOTIFY="eressea-design@eressea.kn-bremen.de"
-#NOTIFY="enno@eressea.upb.de"
-NEWFILE="/tmp/commit.source.$$"
-OLDFILE="/tmp/commit.source.last"
-
-BUILDNO=0
-BUILDLOG="/home/cvs/.build/eressea-source.log"
-BUILDFILE="/home/cvs/.build/eressea-source.no"
-if [ -e $BUILDFILE ]; then
- BUILDNO=`cat $BUILDFILE`
-fi
-
-perl -e '$i=0; while (<>) { if (/^Log Message.*$/) { $i=1; } else { if ($i==1) { print $_; } else { if (/^.*(Tag.*)$/) { print "$1\n\n"; } } } }' >| $NEWFILE
-WHO="$1"
-shift
-
-NEWMD5=`md5sum $NEWFILE | awk '{ print $1 }'`
-echo "New md5sum=$NEWMD5"
-if [ -e $OLDFILE ]; then
- OLDMD5=`md5sum $OLDFILE | awk '{ print $1 }'`
-else
- OLDMD5="N/A"
-fi
-cp $NEWFILE $OLDFILE
-echo "Old md5sum=$OLDMD5"
-if [ $NEWMD5 != $OLDMD5 ]; then
- let BUILDNO=$BUILDNO+1
- echo $BUILDNO >| $BUILDFILE
- (
- echo
- echo -n "[commit $BUILDNO] $WHO"
- date
- cat $NEWFILE
- ) >> $BUILDLOG
- mailx -s "[commit $BUILDNO] eressea-source by $WHO" $NOTIFY < $NEWFILE
- echo "New log message. Sent out notification"
-else
- echo "Identical log message. Notification skipped"
-fi
-echo $BUILDNO $@ | mailx -s "build eressea" cvs@eressea.upb.de
-rm $NEWFILE
diff --git a/scripts/cvsuser/commit-www.sh b/scripts/cvsuser/commit-www.sh
deleted file mode 100755
index 49e8d1313..000000000
--- a/scripts/cvsuser/commit-www.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-
-# notify the web user of the change
-mailx -s "update eressea" www-data@eressea.upb.de
diff --git a/scripts/cvsuser/procmailrc b/scripts/cvsuser/procmailrc
deleted file mode 100644
index 5ce21714c..000000000
--- a/scripts/cvsuser/procmailrc
+++ /dev/null
@@ -1,12 +0,0 @@
-PATH=$HOME/bin:/usr/bin:/public/bin:/bin:/usr/local/bin:/usr/sbin
-ORGMAIL=/var/spool/mail/cvs
-DEFAULT=/var/spool/mail/cvs
-MAILDIR=$HOME/Mail
-LOGFILE=$MAILDIR/procmail-log
-LOCKFILE=$HOME/.lockmail
-VERBOSE=on
-LOGABSTRACT=all
-
-:0:$MAILDIR/.build.lock
-* ^Subject: build \/.*
-| formail -I "" | $HOME/bin/build.sh $MATCH
diff --git a/scripts/cvsuser/senddiff.pl b/scripts/cvsuser/senddiff.pl
deleted file mode 100755
index 7380b9425..000000000
--- a/scripts/cvsuser/senddiff.pl
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/usr/bin/perl
-
-require Mail::Send;
-
-if(scalar(@ARGV) == 0) {
- exit();
-}
-
-$msg = new Mail::Send;
-$msg->to('eressea-diff@eressea.upb.de');
-
-# system('cvs update');
-
-$no = shift(@ARGV);
-$dir = shift(@ARGV);
-($project, $dir) = split(/\//, $dir, 2);
-
-$msg->set('Subject', "[commit $no] diff $project/$dir");
-$mail = $msg->open();
-
-print $mail "updated files in $project/$dir\n";
-chdir('/home/cvs/checkout/eressea/$project/$dir');
-
-foreach $arg (@ARGV) {
- ($file, $oldver, $newver) = split(/,/, $arg);
- print $mail "COMMAND: cvs diff -u -r $oldver -r $newver $file\n\n";
- print $mail `cd /home/cvs/checkout/eressea/$project/$dir ; cvs diff -u -r $oldver -r $newver $file`;
-}
-
-$mail->close();
diff --git a/scripts/readme.txt b/scripts/readme.txt
deleted file mode 100644
index dbc31de48..000000000
--- a/scripts/readme.txt
+++ /dev/null
@@ -1,36 +0,0 @@
-** Status und Statusänderungen
-
-* USERS.STATUS
-
-NEW: Initialer Status, warten auf Bestätigung der Anmeldung.
-Übergänge:
--> TUTORIAL, wenn Anmeldung von Benutzer bestätigt wurde.
--> INVALID, BANNED (nur manuell)
-
-TUTORIAL: Emailadresse des Spielers ist korrekt, seine Anmeldung wurde
-bestätigt, und er muss ein Tutorial bestehen.
-Übergänge:
--> ACTIVE, wenn er ein Tutorial abgeschlossen hat
--> INVALID, BANNED (nur manuell)
-
-ACTIVE: Spieler hat das Tutorial erfüllt, und kann sich für Partien anmelden
-Übergänge:
--> INVALID, BANNED (nur manuell)
-
-INVALID: Spieler hat ungültige Daten übermittelt
-
-BANNED: Spieler ist aus dem Spiel ausgeschlossen worden.
-
-
-* SUBSCRIPTIONS.STATUS
-
-WAITING: Warten auf Bestätigung
--> EXPIRED
--> CONFIRMED
-
-CONFIRMED: Bestätigung eingetroffen
--> WAITING
--> ACTIVE
-
-ACTIVE: Spiel ist gestartet
--> DEAD
diff --git a/scripts/register/account-merge.py b/scripts/register/account-merge.py
deleted file mode 100755
index 61229a6ff..000000000
--- a/scripts/register/account-merge.py
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/usr/bin/env python
-
-# merge two accounts. not used.
-# needs to be checked before used.
-# does not update the TRANSFERS table
-
-import MySQLdb
-import sys
-
-dbname=sys.argv[1]
-userid=int(sys.argv[2])
-oldid=int(sys.argv[3])
-
-db=MySQLdb.connect(db=dbname)
-cursor=db.cursor()
-
-i=cursor.execute("select distinct email from users where id="+str(oldid)+" or id="+str(userid))
-
-if i==0:
- print "Could not find specified usernames"
- sys.exit()
-
-if i>1:
- print "EMail addresses do not match"
- i=cursor.execute("select id, email from users where id="+str(oldid)+" or id="+str(userid))
- while i>0:
- i=i-1
- id, email = cursor.fetchone()
- print " "+str(int(id))+" "+email
- sys.exit()
-
-i=cursor.execute("select id, email, balance from users where id="+str(oldid)+" or id="+str(userid))
-if i!=2:
- print "Could not find both customer ids"
- while i>0:
- i=i-1
- id, email, balance = cursor.fetchone()
- print " "+str(int(id))+" "+email
- sys.exit()
-
-bal=0.0
-while i>0:
- i=i-1
- id, email, balance = cursor.fetchone()
- bal=bal+balance
-
-cursor.execute("update users set balance="+str(bal)+" where id="+str(userid))
-cursor.execute("delete from users where id="+str(oldid))
-cursor.execute("update transactions set user="+str(userid)+" where user="+str(oldid))
-cursor.execute("update subscriptions set user="+str(userid)+" where user="+str(oldid))
-print "Customer records have been merged"
diff --git a/scripts/register/balance.py b/scripts/register/balance.py
deleted file mode 100755
index ef89b8f8b..000000000
--- a/scripts/register/balance.py
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/usr/bin/env python
-
-import MySQLdb
-import sys
-import smtplib
-
-From='accounts@vinyambar.de'
-dbname=sys.argv[1]
-
-server=smtplib.SMTP('localhost')
-db=MySQLdb.connect(db=dbname)
-cursor=db.cursor()
-
-i=cursor.execute('SELECT email, balance, firstname, lastname FROM users WHERE balance>0.0')
-
-while i>0:
- email, balance, firstname, lastname = cursor.fetchone()
- print 'Balance for '+firstname+' '+lastname+' is '+str(balance)
- i=i-1
diff --git a/scripts/register/ban.py b/scripts/register/ban.py
deleted file mode 100755
index 598bdb1c5..000000000
--- a/scripts/register/ban.py
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/usr/bin/env python
-
-import MySQLdb
-import sys
-
-dbname=sys.argv[1]
-db=MySQLdb.connect(db=dbname)
-
-cursor=db.cursor()
-bans = cursor.execute("select user, users.email, users.status, userips.ip from bannedips, users, userips where users.status!='BANNED' and users.id=userips.user and userips.ip=bannedips.ip")
-bc = db.cursor()
-while bans:
- bans=bans-1
- user, email, status, ip = cursor.fetchone()
- if status!='ACTIVE':
- bc.execute("update users set status='BANNED' where id="+str(int(user)))
- else:
- print email + " is active, and playing from banned ip "+ip
diff --git a/scripts/register/billinginfo.py b/scripts/register/billinginfo.py
deleted file mode 100755
index 4f2fa6b9a..000000000
--- a/scripts/register/billinginfo.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/env python
-
-import MySQLdb
-import re
-import sys
-import smtplib
-
-
-dbname=sys.argv[1]
-template=sys.argv[2]
-game=sys.argv[3]
-
-server=smtplib.SMTP('localhost')
-db=MySQLdb.connect(db=dbname)
-From="accounts@vinyambar.de"
-
-cursor=db.cursor()
-query=("select u.id, u.email, u.firstname "+
- "from users u, games, subscriptions, transactions t "+
- "where u.id=subscriptions.user and subscriptions.game=games.id and "+
- "u.status='CONFIRMED' and games.name='"+game+"' GROUP BY u.id HAVING SUM(t.balance)=0")
-
-users=cursor.execute(query)
-print "Sending confirmation to "+str(int(users))+" users"
-while users!=0:
- users=users-1
- entry=cursor.fetchone()
- custid=str(int(entry[0]))
- email=entry[1]
- firstname=entry[2]
-
- infile=open(template,"r")
- line = infile.read()
-
- line = re.sub('', custid, line)
- line = re.sub('', firstname, line)
- line = re.sub("", game, line)
-
- Msg = ("From: "+From+"\nTo: "+email+"\n"+
- "Subject: Vinyambar Kontoinformationen.\n\n"+
- line)
-
- try:
- server.sendmail(From, email, Msg)
- update=db.cursor()
- update.execute("UPDATE users set status='PENDING' WHERE id="+custid)
- print "Sent billing information to "+email
-
- except:
- print "Could not inform "+To
- print "Reason was: '"+Reason+"'"
- print "Exception is:", sys.exc_type, ":", sys.exc_value
-
- infile.close()
diff --git a/scripts/register/confirm.py b/scripts/register/confirm.py
deleted file mode 100755
index bd7786cb3..000000000
--- a/scripts/register/confirm.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/env python
-
-# this script picks all NEW users from the database, (subscribed through
-# the web interface), and sends them their customer-id and password
-# if the mail was sent cuccessfully, it sets the user to the 'WAITING'
-# state, meaning that we wait for his confirmation.
-
-import sys
-import MySQLdb
-import smtplib
-
-dbname=sys.argv[1]
-db = MySQLdb.connect(db=dbname)
-
-From="accounts@vinyambar.de"
-server=smtplib.SMTP('localhost')
-
-cursor=db.cursor()
-records=cursor.execute("SELECT u.id, u.password, u.email "+
- "from users u "+
- "where u.status='NEW'")
-
-while records>0:
- records = records - 1
- customerid, passwd, email = cursor.fetchone()
-
- Msg = ("From: "+From+"\nTo: "+email+"\nSubject: Vinyambar Anmeldung angenommen.\n\n"+
- "Deine Anmeldung für Vinyambar wurde akzeptiert.\n"
- "\n"+
- "Kundennummer: " + str(int(customerid)) + "\n"+
- "Passwort: " + passwd + "\n" +
- "\n" +
- "Bitte bewahre diese Mail sorgfältig auf, da Du deine Kundennummer und das\n"+
- "Passwort für das Spiel benötigst. Solltest Du noch Fragen zu Deiner \n"+
- "Anmeldung haben, wende Dich bitte an accounts@vinyambar.de.\n" +
- "\n"+
- "Die Kundennummer gib bitte bei der Überweisung der Spielgebühren an. \n" +
- "Unsere Kontoinformationen lauten:\n" +
- " Katja Zedel\n"+
- " Kontonummer 1251 886 106 \n"+
- " BLZ 500 502 01 (Frankfurter Sparkasse)\n" +
- "\n"+
- "Zugang zu deinem Konto erhältst Du mit dem Passowrt auf der Webseite\n"+
- " http://www.vinyambar.de/accounts.shtml\n"+
- "\n"+
- "Das Vinyambar-Team")
- now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
- try:
- server.sendmail(From, email, Msg)
- print "[%s] USER %d - UPDATE: status='WAITING' " % (now, customerid)
- update=db.cursor()
- update.execute("UPDATE users set status='WAITING' WHERE id="+
- str(int(customerid)))
- except:
- print "[%s] USER %d - ERROR: could not send to %s: %s " % (now, customerid, email, sys.exc_indo())
- sys.exit()
diff --git a/scripts/register/dbcreate.sql b/scripts/register/dbcreate.sql
deleted file mode 100644
index 2a9ace30e..000000000
--- a/scripts/register/dbcreate.sql
+++ /dev/null
@@ -1,351 +0,0 @@
-# MySQL dump 8.13
-#
-# Host: localhost Database: vinyambar
-#--------------------------------------------------------
-# Server version 3.23.36-log
-
-#
-# Table structure for table 'countries'
-#
-
-DROP table countries;
-CREATE TABLE countries (
- id int(11) NOT NULL default '0',
- name varchar(32) default NULL,
- PRIMARY KEY (id)
-) TYPE=MyISAM;
-
-#
-# Dumping data for table 'countries'
-#
-
-INSERT INTO countries VALUES (1,'United States');
-INSERT INTO countries VALUES (10,'Anguilla');
-INSERT INTO countries VALUES (100,'Israel');
-INSERT INTO countries VALUES (101,'Italy');
-INSERT INTO countries VALUES (102,'Jamaica');
-INSERT INTO countries VALUES (103,'Jan Mayen');
-INSERT INTO countries VALUES (104,'Japan');
-INSERT INTO countries VALUES (105,'Jersey');
-INSERT INTO countries VALUES (106,'Jordan');
-INSERT INTO countries VALUES (107,'Kazakhstan');
-INSERT INTO countries VALUES (108,'Kenya Coast Republic');
-INSERT INTO countries VALUES (109,'Kiribati');
-INSERT INTO countries VALUES (11,'Antigua and Barbuda');
-INSERT INTO countries VALUES (111,'Korea, South');
-INSERT INTO countries VALUES (112,'Kuwait');
-INSERT INTO countries VALUES (113,'Kyrgyzstan');
-INSERT INTO countries VALUES (114,'Laos');
-INSERT INTO countries VALUES (115,'Latvia');
-INSERT INTO countries VALUES (116,'Lebanon');
-INSERT INTO countries VALUES (117,'Lesotho');
-INSERT INTO countries VALUES (118,'Liberia');
-INSERT INTO countries VALUES (12,'Argentina');
-INSERT INTO countries VALUES (120,'Liechtenstein');
-INSERT INTO countries VALUES (121,'Lithuania');
-INSERT INTO countries VALUES (122,'Luxembourg');
-INSERT INTO countries VALUES (123,'Macau');
-INSERT INTO countries VALUES (124,'Macedonia');
-INSERT INTO countries VALUES (125,'Madagascar');
-INSERT INTO countries VALUES (126,'Malawi');
-INSERT INTO countries VALUES (127,'Malaysia');
-INSERT INTO countries VALUES (128,'Maldives');
-INSERT INTO countries VALUES (129,'Mali');
-INSERT INTO countries VALUES (13,'Armenia');
-INSERT INTO countries VALUES (130,'Malta');
-INSERT INTO countries VALUES (131,'Marshall Islands');
-INSERT INTO countries VALUES (132,'Martinique');
-INSERT INTO countries VALUES (133,'Mauritania');
-INSERT INTO countries VALUES (134,'Mauritius');
-INSERT INTO countries VALUES (135,'Mayotte');
-INSERT INTO countries VALUES (136,'Mexico');
-INSERT INTO countries VALUES (137,'Moldova');
-INSERT INTO countries VALUES (138,'Monaco');
-INSERT INTO countries VALUES (139,'Mongolia');
-INSERT INTO countries VALUES (14,'Aruba');
-INSERT INTO countries VALUES (140,'Montserrat');
-INSERT INTO countries VALUES (141,'Morocco');
-INSERT INTO countries VALUES (142,'Mozambique');
-INSERT INTO countries VALUES (143,'Namibia');
-INSERT INTO countries VALUES (144,'Nauru');
-INSERT INTO countries VALUES (145,'Nepal');
-INSERT INTO countries VALUES (146,'Netherlands');
-INSERT INTO countries VALUES (147,'Netherlands Antilles');
-INSERT INTO countries VALUES (148,'New Caledonia');
-INSERT INTO countries VALUES (149,'New Zealand');
-INSERT INTO countries VALUES (15,'Australia');
-INSERT INTO countries VALUES (150,'Nicaragua');
-INSERT INTO countries VALUES (151,'Niger');
-INSERT INTO countries VALUES (152,'Nigeria');
-INSERT INTO countries VALUES (153,'Niue');
-INSERT INTO countries VALUES (154,'Norway');
-INSERT INTO countries VALUES (155,'Oman');
-INSERT INTO countries VALUES (156,'Pakistan');
-INSERT INTO countries VALUES (157,'Palau');
-INSERT INTO countries VALUES (158,'Panama');
-INSERT INTO countries VALUES (159,'Papua New Guinea');
-INSERT INTO countries VALUES (16,'Austria');
-INSERT INTO countries VALUES (160,'Paraguay');
-INSERT INTO countries VALUES (161,'Peru');
-INSERT INTO countries VALUES (162,'Philippines');
-INSERT INTO countries VALUES (163,'Poland');
-INSERT INTO countries VALUES (164,'Portugal');
-INSERT INTO countries VALUES (165,'Puerto Rico');
-INSERT INTO countries VALUES (166,'Qatar');
-INSERT INTO countries VALUES (167,'Romania');
-INSERT INTO countries VALUES (168,'Russian Federation');
-INSERT INTO countries VALUES (169,'Rwanda');
-INSERT INTO countries VALUES (17,'Azerbaijan Republic');
-INSERT INTO countries VALUES (170,'Saint Helena');
-INSERT INTO countries VALUES (171,'Saint Kitts-Nevis');
-INSERT INTO countries VALUES (172,'Saint Lucia');
-INSERT INTO countries VALUES (173,'Saint Pierre and Miquelon');
-INSERT INTO countries VALUES (174,'Saint Vincent and the Grenadines');
-INSERT INTO countries VALUES (175,'San Marino');
-INSERT INTO countries VALUES (176,'Saudi Arabia');
-INSERT INTO countries VALUES (177,'Senegal');
-INSERT INTO countries VALUES (178,'Seychelles');
-INSERT INTO countries VALUES (179,'Sierra Leone');
-INSERT INTO countries VALUES (18,'Bahamas');
-INSERT INTO countries VALUES (180,'Singapore');
-INSERT INTO countries VALUES (181,'Slovakia');
-INSERT INTO countries VALUES (182,'Slovenia');
-INSERT INTO countries VALUES (183,'Solomon Islands');
-INSERT INTO countries VALUES (184,'Somalia');
-INSERT INTO countries VALUES (185,'South Africa');
-INSERT INTO countries VALUES (186,'Spain');
-INSERT INTO countries VALUES (187,'Sri Lanka');
-INSERT INTO countries VALUES (188,'Sudan');
-INSERT INTO countries VALUES (189,'Suriname');
-INSERT INTO countries VALUES (19,'Bahrain');
-INSERT INTO countries VALUES (190,'Svalbard');
-INSERT INTO countries VALUES (191,'Swaziland');
-INSERT INTO countries VALUES (192,'Sweden');
-INSERT INTO countries VALUES (193,'Switzerland');
-INSERT INTO countries VALUES (194,'Syria');
-INSERT INTO countries VALUES (195,'Tahiti');
-INSERT INTO countries VALUES (196,'Taiwan');
-INSERT INTO countries VALUES (197,'Tajikistan');
-INSERT INTO countries VALUES (198,'Tanzania');
-INSERT INTO countries VALUES (199,'Thailand');
-INSERT INTO countries VALUES (2,'Canada');
-INSERT INTO countries VALUES (20,'Bangladesh');
-INSERT INTO countries VALUES (200,'Togo');
-INSERT INTO countries VALUES (201,'Tonga');
-INSERT INTO countries VALUES (202,'Trinidad and Tobago');
-INSERT INTO countries VALUES (203,'Tunisia');
-INSERT INTO countries VALUES (204,'Turkey');
-INSERT INTO countries VALUES (205,'Turkmenistan');
-INSERT INTO countries VALUES (206,'Turks and Caicos Islands');
-INSERT INTO countries VALUES (207,'Tuvalu');
-INSERT INTO countries VALUES (208,'Uganda');
-INSERT INTO countries VALUES (209,'Ukraine');
-INSERT INTO countries VALUES (21,'Barbados');
-INSERT INTO countries VALUES (210,'United Arab Emirates');
-INSERT INTO countries VALUES (211,'Uruguay');
-INSERT INTO countries VALUES (212,'Uzbekistan');
-INSERT INTO countries VALUES (213,'Vanuatu');
-INSERT INTO countries VALUES (214,'Vatican City State');
-INSERT INTO countries VALUES (215,'Venezuela');
-INSERT INTO countries VALUES (216,'Vietnam');
-INSERT INTO countries VALUES (217,'Virgin Islands (U.S.)');
-INSERT INTO countries VALUES (218,'Wallis and Futuna');
-INSERT INTO countries VALUES (219,'Western Sahara');
-INSERT INTO countries VALUES (22,'Belarus');
-INSERT INTO countries VALUES (220,'Western Samoa');
-INSERT INTO countries VALUES (221,'Yemen');
-INSERT INTO countries VALUES (222,'Yugoslavia');
-INSERT INTO countries VALUES (223,'Zambia');
-INSERT INTO countries VALUES (224,'Zimbabwe');
-INSERT INTO countries VALUES (225,'APO/FPO');
-INSERT INTO countries VALUES (226,'Micronesia');
-INSERT INTO countries VALUES (23,'Belgium');
-INSERT INTO countries VALUES (24,'Belize');
-INSERT INTO countries VALUES (25,'Benin');
-INSERT INTO countries VALUES (26,'Bermuda');
-INSERT INTO countries VALUES (27,'Bhutan');
-INSERT INTO countries VALUES (28,'Bolivia');
-INSERT INTO countries VALUES (29,'Bosnia and Herzegovina');
-INSERT INTO countries VALUES (3,'United Kingdom');
-INSERT INTO countries VALUES (30,'Botswana');
-INSERT INTO countries VALUES (31,'Brazil');
-INSERT INTO countries VALUES (32,'British Virgin Islands');
-INSERT INTO countries VALUES (33,'Brunei Darussalam');
-INSERT INTO countries VALUES (34,'Bulgaria');
-INSERT INTO countries VALUES (35,'Burkina Faso');
-INSERT INTO countries VALUES (36,'Burma');
-INSERT INTO countries VALUES (37,'Burundi');
-INSERT INTO countries VALUES (38,'Cambodia');
-INSERT INTO countries VALUES (39,'Cameroon');
-INSERT INTO countries VALUES (4,'Afghanistan');
-INSERT INTO countries VALUES (40,'Cape Verde Islands');
-INSERT INTO countries VALUES (41,'Cayman Islands');
-INSERT INTO countries VALUES (42,'Central African Republic');
-INSERT INTO countries VALUES (43,'Chad');
-INSERT INTO countries VALUES (44,'Chile');
-INSERT INTO countries VALUES (45,'China');
-INSERT INTO countries VALUES (46,'Colombia');
-INSERT INTO countries VALUES (47,'Comoros');
-INSERT INTO countries VALUES (48,'Congo, Democratic Republic of th');
-INSERT INTO countries VALUES (49,'Congo, Republic of the');
-INSERT INTO countries VALUES (5,'Albania');
-INSERT INTO countries VALUES (50,'Cook Islands');
-INSERT INTO countries VALUES (51,'Costa Rica');
-INSERT INTO countries VALUES (52,'Cote d Ivoire (Ivory Coast)');
-INSERT INTO countries VALUES (53,'Croatia, Republic of');
-INSERT INTO countries VALUES (55,'Cyprus');
-INSERT INTO countries VALUES (56,'Czech Republic');
-INSERT INTO countries VALUES (57,'Denmark');
-INSERT INTO countries VALUES (58,'Djibouti');
-INSERT INTO countries VALUES (59,'Dominica');
-INSERT INTO countries VALUES (6,'Algeria');
-INSERT INTO countries VALUES (60,'Dominican Republic');
-INSERT INTO countries VALUES (61,'Ecuador');
-INSERT INTO countries VALUES (62,'Egypt');
-INSERT INTO countries VALUES (63,'El Salvador');
-INSERT INTO countries VALUES (64,'Equatorial Guinea');
-INSERT INTO countries VALUES (65,'Eritrea');
-INSERT INTO countries VALUES (66,'Estonia');
-INSERT INTO countries VALUES (67,'Ethiopia');
-INSERT INTO countries VALUES (68,'Falkland Islands (Islas Malvinas');
-INSERT INTO countries VALUES (69,'Fiji');
-INSERT INTO countries VALUES (7,'American Samoa');
-INSERT INTO countries VALUES (70,'Finland');
-INSERT INTO countries VALUES (71,'France');
-INSERT INTO countries VALUES (72,'French Guiana');
-INSERT INTO countries VALUES (73,'French Polynesia');
-INSERT INTO countries VALUES (74,'Gabon Republic');
-INSERT INTO countries VALUES (75,'Gambia');
-INSERT INTO countries VALUES (76,'Georgia');
-INSERT INTO countries VALUES (77,'Germany');
-INSERT INTO countries VALUES (78,'Ghana');
-INSERT INTO countries VALUES (79,'Gibraltar');
-INSERT INTO countries VALUES (8,'Andorra');
-INSERT INTO countries VALUES (80,'Greece');
-INSERT INTO countries VALUES (81,'Greenland');
-INSERT INTO countries VALUES (82,'Grenada');
-INSERT INTO countries VALUES (83,'Guadeloupe');
-INSERT INTO countries VALUES (84,'Guam');
-INSERT INTO countries VALUES (85,'Guatemala');
-INSERT INTO countries VALUES (86,'Guernsey');
-INSERT INTO countries VALUES (87,'Guinea');
-INSERT INTO countries VALUES (88,'Guinea-Bissau');
-INSERT INTO countries VALUES (89,'Guyana');
-INSERT INTO countries VALUES (9,'Angola');
-INSERT INTO countries VALUES (90,'Haiti');
-INSERT INTO countries VALUES (91,'Honduras');
-INSERT INTO countries VALUES (92,'Hong Kong');
-INSERT INTO countries VALUES (93,'Hungary');
-INSERT INTO countries VALUES (94,'Iceland');
-INSERT INTO countries VALUES (95,'India');
-INSERT INTO countries VALUES (96,'Indonesia');
-INSERT INTO countries VALUES (99,'Ireland');
-
-#
-# Table structure for table 'factions'
-#
-
-DROP table factions;
-CREATE TABLE factions (
- id varchar(6) NOT NULL default '',
- game int(11) NOT NULL default '0',
- email varchar(64) default NULL,
- banner text,
- vacation varchar(64) default NULL,
- password varchar(64) default NULL,
- name varchar(64) default NULL,
- user int(11) NOT NULL default '0',
- vacation_start date default NULL,
- race varchar(16) default NULL,
- locale varchar(10) default NULL,
- lastorders int(11) default NULL,
- PRIMARY KEY (id,game)
-) TYPE=MyISAM;
-
-#
-# Dumping data for table 'factions'
-#
-
-
-#
-# Table structure for table 'games'
-#
-
-drop table games;
-CREATE TABLE games (
- id int(11) NOT NULL auto_increment,
- name varchar(32) NOT NULL default '',
- info text,
- PRIMARY KEY (id)
-) TYPE=MyISAM;
-
-#
-# Dumping data for table 'games'
-#
-
-INSERT INTO games VALUES (1,'Vinyambar I','Vinyambar nach alten Regeln');
-INSERT INTO games VALUES (2,'Vinyambar II','Vinyambar nach neuen Regeln');
-
-#
-# Table structure for table 'races'
-#
-
-drop table races;
-CREATE TABLE races (
- locale varchar(10) NOT NULL default '',
- race varchar(10) NOT NULL default '',
- name varchar(20) default NULL
-) TYPE=MyISAM;
-
-#
-# Dumping data for table 'races'
-#
-
-INSERT INTO races VALUES ('de','GOBLIN','Goblins');
-INSERT INTO races VALUES ('de','DWARF','Zwerge');
-INSERT INTO races VALUES ('de','ELF','Elfen');
-INSERT INTO races VALUES ('de','HALFLING','Halblinge');
-INSERT INTO races VALUES ('de','INSECT','Insekten');
-INSERT INTO races VALUES ('de','AQUARIAN','Meermenschen');
-INSERT INTO races VALUES ('de','HUMAN','Menschen');
-INSERT INTO races VALUES ('de','CAT','Katzen');
-INSERT INTO races VALUES ('de','TROLL','Trolle');
-INSERT INTO races VALUES ('de','ORC','Orks');
-INSERT INTO races VALUES ('de','DEMON','Dämonen');
-
-#
-# Table structure for table 'subscriptions'
-#
-
-drop table subscriptions;
-CREATE TABLE subscriptions (
- game int(11) NOT NULL default '0',
- user int(11) NOT NULL default '0',
- credits int(11) NOT NULL default '0',
- race varchar(10) default NULL,
- id int(10) NOT NULL auto_increment,
- status varchar(10) NOT NULL default 'NEW',
- updated timestamp(14) NOT NULL,
- PRIMARY KEY (id)
-) TYPE=MyISAM;
-
-
-#
-# Table structure for table 'users'
-#
-
-drop table users;
-CREATE TABLE users (
- id int(11) NOT NULL auto_increment,
- email varchar(64) default NULL,
- info text,
- address varchar(28) default NULL,
- city varchar(28) default NULL,
- country int(11) NOT NULL default '0',
- phone varchar(32) default NULL,
- firstname varchar(32) default NULL,
- lastname varchar(32) default NULL,
- password varchar(16) NOT NULL default '',
- updated timestamp(14) NOT NULL,
- PRIMARY KEY (id)
-) TYPE=MyISAM;
diff --git a/scripts/register/duplicates.py b/scripts/register/duplicates.py
deleted file mode 100755
index ab20309f8..000000000
--- a/scripts/register/duplicates.py
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/usr/bin/env python
-
-# duplicates.py
-# this script will find users that registered from the same IP,
-# where at least one of them is currenly ACTIVE.
-
-import MySQLdb
-import sys
-
-dbname=sys.argv[1]
-db = MySQLdb.connect(db=dbname)
-cursor = db.cursor()
-dupes = cursor.execute("select count(*) sum, ip from users,userips where users.id=userips.user and status!='EXPIRED' group by ip having sum>1")
-
-while dupes:
- dupes=dupes-1
- sum, ip = cursor.fetchone()
- c = db.cursor()
- c.execute("select count(*) from users, userips where users.id=userips.user and status='CONFIRMED' and ip='"+ip+"'")
- (active,) = c.fetchone()
- if active:
- users = c.execute("select id, email, firstname, lastname, status from users, userips where userips.user=users.id and ip='"+ip+"'")
- if users:
- print ip
- while users:
- users=users-1
- uid, email, firstname, lastname, status = c.fetchone()
- print "\t"+str(int(uid)) +"("+status+")\t"+firstname+" "+lastname+" <"+email+">"
- print "\n"
-
diff --git a/scripts/register/errors.py b/scripts/register/errors.py
deleted file mode 100755
index 42d5838a2..000000000
--- a/scripts/register/errors.py
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/usr/bin/env python
-
-import smtplib
-import time
-import sys
-import os
-import re
-import locking
-from locking import lock, unlock
-
-From="accounts@vinyambar.de"
-
-# lock the input file:
-lock(sys.argv[1]+'.err',180)
-
-# move input file then unlock it:
-if os.access(sys.argv[1]+'.err', os.F_OK)==0:
- unlock(sys.argv[1]+'.err')
- sys.exit();
-
-try:
- os.rename(sys.argv[1]+'.err', sys.argv[1]+'.tmp')
-finally:
- unlock(sys.argv[1]+'.err')
-
-infile=open(sys.argv[1]+".tmp", "r")
-server=smtplib.SMTP('localhost')
-#server.set_debuglevel(1)
-
-matchline=re.compile(
- r"""([^\s]+)\s*([^\n\r]+)*""",
- re.IGNORECASE | re.DOTALL | re.VERBOSE)
-
-for line in infile.readlines():
- match=matchline.match(line)
- if match!=None:
- To = match.group(1)
- Reason = match.group(2)
- print "ERROR: "+To+": "+Reason
- Msg = ("From: "+From+"\nTo: "+To+"\nSubject: Vinyambar Anmeldung fehlgeschlagen.\n\n"
- +"Deine Anmeldung konnte aus folgendem Grund nicht akzeptiert werden:\n "+Reason+"\n")
- try:
- server.sendmail(From, To, Msg)
- except:
- print "Could not send Error to "+To
- print "Reason was: '"+Reason+"'"
- print "Exception is:", sys.exc_type, ":", sys.exc_value
-
-os.unlink(sys.argv[1]+".tmp")
-infile.close()
-server.quit()
diff --git a/scripts/register/getfactions.py b/scripts/register/getfactions.py
deleted file mode 100755
index ffd6e005f..000000000
--- a/scripts/register/getfactions.py
+++ /dev/null
@@ -1,35 +0,0 @@
-#!/usr/bin/env python
-
-import MySQLdb
-import sys
-import string
-from whrandom import choice
-
-dbname=sys.argv[1]
-maxnum=int(sys.argv[2])
-game_id=0 # eressea is game 0, tutorial is 1
-
-def genpasswd():
- newpasswd=""
- chars = string.letters + string.digits
- for i in range(8):
- newpasswd = newpasswd + choice(chars)
- return newpasswd
-
-query = "select distinct u.email, s.id, s.password, r.name, u.locale, s.bonus from users u, races r, subscriptions s left join userips i on u.id=i.user left join bannedips b on i.ip=b.ip where s.user=u.id and b.ip is NULL and s.status='CONFIRMED' and r.race=s.race and s.game="+str(game_id)+" and r.locale='de' order by s.id"
-db=MySQLdb.connect(db=dbname)
-cursor = db.cursor()
-c = db.cursor()
-num=cursor.execute(query)
-if num>maxnum:
- num=maxnum
-while num:
- num=num-1
- email, sid, password, race, locale, bonus = cursor.fetchone()
- if bonus==None:
- bonus=0
- if password==None:
- password=genpasswd()
- c.execute("UPDATE subscriptions set password='"+password+"' where id="+str(int(sid)))
-
- print email+" "+race+" "+locale+" "+str(int(bonus))+" "+password
diff --git a/scripts/register/locking.py b/scripts/register/locking.py
deleted file mode 100755
index daf6c4124..000000000
--- a/scripts/register/locking.py
+++ /dev/null
@@ -1,34 +0,0 @@
-#!/usr/bin/env python
-
-import time
-import os
-import stat
-
-def trylock(file):
- try:
- os.symlink(file, file+'.lock')
- except OSError:
- return 1
- return 0
-
-def lock(file, timeout=60):
- locked=1
- while locked:
- try:
- locked=0
- os.symlink(file, file+'.lock')
- except:
- update=os.stat(file+'.lock')[stat.ST_MTIME]
- now=time.time()
- if (now > update + timeout):
- locked=0
- print "removing stale lockfile "+file+".lock"
- os.unlink(file+'.lock')
- else:
- locked=1
- print "Waiting for lock on "+file+".lock"
- time.sleep(20)
-
-def unlock(file):
- os.unlink(file+'.lock')
-
diff --git a/scripts/register/massmail.py b/scripts/register/massmail.py
deleted file mode 100755
index a2c39e77e..000000000
--- a/scripts/register/massmail.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/env python
-
-import MySQLdb
-import re
-import sys
-import smtplib
-
-
-dbname=sys.argv[1]
-template=sys.argv[2]
-sql=sys.argv[3]
-
-server=smtplib.SMTP('localhost')
-db=MySQLdb.connect(db=dbname)
-From="accounts@vinyambar.de"
-
-cursor=db.cursor()
-query=("select distinct users.id, users.email, users.firstname "+
- "from users, games, subscriptions "+
- "where users.id=subscriptions.user and subscriptions.game=games.id and "+
- sql)
-
-users=cursor.execute(query)
-print "Sending confirmation to "+str(int(users))+" users"
-while users!=0:
- users=users-1
- entry=cursor.fetchone()
- custid=str(int(entry[0]))
- email=entry[1]
- firstname=entry[2]
-
- infile=open(template,"r")
- line = infile.read()
-
- line = re.sub('', custid, line)
- line = re.sub('', firstname, line)
-# line = re.sub("", game, line)
-
- Msg = ("From: "+From+"\nTo: "+email+"\n"+
- line)
-
- try:
- server.sendmail(From, email, Msg)
- update=db.cursor()
- update.execute("UPDATE users set status='PENDING' WHERE id="+custid)
- print "Sent billing information to "+email
-
- except:
- print "Could not inform "+To
- print "Reason was: '"+Reason+"'"
- print "Exception is:", sys.exc_type, ":", sys.exc_value
-
- infile.close()
diff --git a/scripts/register/noowner.sql b/scripts/register/noowner.sql
deleted file mode 100644
index 662ad4e6c..000000000
--- a/scripts/register/noowner.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-select s.id ID, s.faction Partei, s.race Rasse, s.status Status, g.name Spiel
- from subscriptions s, games g
- where s.user=0 and g.id=s.game;
diff --git a/scripts/register/payment.py b/scripts/register/payment.py
deleted file mode 100755
index 771b2a875..000000000
--- a/scripts/register/payment.py
+++ /dev/null
@@ -1,157 +0,0 @@
-#!/usr/bin/env python
-
-import MySQLdb
-import sys
-import smtplib
-
-From='accounts@vinyambar.de'
-#!/usr/bin/env python
-
-import re
-import MySQLdb
-import sys
-
-def pay(db, userid, email, cash, date, reason='PAYMENT'):
- cursor=db.cursor()
- locale="de"
- cursor.execute("UPDATE users SET status='PAYING' WHERE id="+str(userid));
-
- cursor.execute('INSERT transactions (user, balance, description, date) VALUES ('+str(userid)+', '+str(cash)+', \''+reason+'\', \''+date+'\')')
- cursor.execute('SELECT LAST_INSERT_ID() FROM transactions WHERE user='+str(userid));
- lastid = int(cursor.fetchone()[0])
- result = cursor.execute('SELECT text FROM descriptions WHERE locale=\''+locale+'\' AND handle=\''+reason+'\'')
- if result!=0:
- reason = cursor.fetchone()[0]
-
- i=cursor.execute('SELECT sum(balance) from transactions WHERE user='+str(userid))
- balance=cursor.fetchone()[0]
- if balance==None:
- balance=0.0
- Msg = ("From: Vinyambar Buchhaltung <"+From+">\nTo: "+email+"\nSubject: Vinyambar Zahlungseingang.\n\n"+
- "Kundennummer: "+str(userid)+"\n"+
- "Eingangsdatum: "+date+"\n"+
- "Transaktionsnummer: "+str(lastid)+"\n"+
- "Alter Kontostand: "+str(balance)+" EUR\n"+
- "Zahlungseingang: "+str(cash)+" EUR\n"+
- "Neuer Kontostand: "+str(balance+cash)+" EUR\n"+
- "Verwendungszweck: "+reason+"\n"+
- "\n"+
- "Deine Zahlung ist eingegangen und wurde auf dein Spielerkonto verbucht.\n")
-
- try:
- server=smtplib.SMTP('localhost')
- server.sendmail(From, email, Msg)
- except:
- print "Could not send confirmation to "+email
- print "Exception is:", sys.exc_type, ":", sys.exc_value
- return
-
-def charge(ids, balance, kto, blz, date):
- if len(ids):
- custids = []
- db=MySQLdb.connect(db=dbname)
- cursor = db.cursor()
- for custid in ids:
- k = cursor.execute('SELECT firstname, lastname FROM users WHERE id='+str(custid))
- if k:
- custids.append(custid)
- if len(custids)==1:
- k = cursor.execute('SELECT balance from transactions where USER='+str(custid)+" and description='PAYMENT' and date='"+date+"'")
- if k:
- print "user already had a transaction today, not adding it for safety reasons"
- else:
- cursor.execute('SELECT email FROM users WHERE users.id='+str(custid))
- email = cursor.fetchone()[0]
- pay(db, custid, email, balance, date)
- return 0
- else:
- print "zero or more than one possible customerid found:", custids
- return -1
-
-def eumel(dbname):
- balance=None
- kto=None
- blz=None
- date=None
- zweck=[]
- ids = []
- rv=0
- for line in sys.stdin.readlines():
- match=re.match('Buchung/Wert.* / ([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9]).*H (.*),(.*) EUR', line)
- if match!=None:
- if (balance!=None):
- r = charge(ids, balance, kto, blz, date)
- if r!=0:
- print "FAILED", balance, kto, blz, date, zweck
- rv=r
- balance=None
- kto=None
- blz=None
- date=None
- ids = []
- date=match.groups()[0]+'-'+match.groups()[1]+'-'+match.groups()[2]
- balance=float(match.groups()[3]+'.'+match.groups()[4])
- continue
- match=re.match(' KTO/BLZ\s*([0-9]*) / ([0-9]*)', line)
- if match!=None:
- kto, blz = match.groups()
- continue
- match=re.match(' VZweck [0-9] *(.*)', line)
- if match!=None:
- zweck.append(line)
- line=match.groups()[0]
- while len(line):
- match = re.match('(.*[^ ]) +(.+)', line)
- if (match!=None):
- line, value = match.groups()
- else:
- value = line
- line=''
- try:
- custid = int(value)
- ids.append(custid)
- except ValueError:
- continue
- if (balance):
- r = charge(ids, balance, kto, blz, date)
- if r!=0:
- print "FAILED", balance, kto, blz, date, zweck
- rv=r
- return rv
-
-def manual(dbname):
- userid=sys.argv[2]
-
- db=MySQLdb.connect(db=dbname)
- cursor=db.cursor()
-
- i=cursor.execute('SELECT email, firstname, lastname FROM users, transactions WHERE users.id='+str(userid))
- if i==0:
- print "Unknown user "+str(userid)
- sys.exit()
-
- email, firstname, lastname = cursor.fetchone()
- i=cursor.execute('SELECT sum(balance) from transactions WHERE user='+str(userid))
- balance=cursor.fetchone()[0]
- if balance==None:
- balance=0.0
-
- print 'Balance for '+firstname+' '+lastname+' is '+str(balance)+' EUR'
-
- if len(sys.argv)>4:
- cash=float(sys.argv[3])
- date=sys.argv[4]
- reason='PAYMENT'
- if len(sys.argv)>5:
- reason=sys.argv[5]
-
- pay(db, int(userid), email, cash, date, reason)
- print 'New balance is '+str(balance+cash)+' EUR'
- return
-
-dbname=sys.argv[1]
-if sys.argv[2]=='--eumel':
- r = eumel(dbname)
- sys.exit(r)
-else:
- manual(dbname)
diff --git a/scripts/register/pending.sql b/scripts/register/pending.sql
deleted file mode 100644
index 0f76cb7ae..000000000
--- a/scripts/register/pending.sql
+++ /dev/null
@@ -1 +0,0 @@
-and users.balance=0 and users.status='PENDING'
diff --git a/scripts/register/races.sql b/scripts/register/races.sql
deleted file mode 100644
index 75a7c6bc1..000000000
--- a/scripts/register/races.sql
+++ /dev/null
@@ -1,10 +0,0 @@
-select races.name Rasse, count(*) Anmeldungen
- from races, subscriptions, users
- where races.race=subscriptions.race and subscriptions.user=users.id
- group by races.race;
-
-select games.name Spiel, count(*) Anmeldungen
- from games, subscriptions, users
- where subscriptions.game=games.id and subscriptions.user=users.id
- group by game;
-
diff --git a/scripts/register/register.py b/scripts/register/register.py
deleted file mode 100755
index e26ca4a11..000000000
--- a/scripts/register/register.py
+++ /dev/null
@@ -1,140 +0,0 @@
-#!/usr/bin/python
-## This script is called when an email from the user arrives
-## in reply to the registration form's confirmation email.
-## It's the first time the user is added to the database.
-
-import MySQLdb
-import sys
-import re
-import string
-from whrandom import choice
-
-import locking
-from locking import lock, unlock
-
-dbname=sys.argv[2]
-db=MySQLdb.connect(db=dbname)
-
-lock(sys.argv[1]+".err")
-errors=open(sys.argv[1]+".err", 'a')
-
-def validrace(race):
- validraces=('GOBLIN', 'DWARF', 'ELF', 'HALFLING', 'INSECT', 'AQUARIAN', 'HUMAN', 'CAT', 'TROLL', 'ORC', 'DEMON')
- name = string.upper(str(race))
- if name in validraces:
- return name
- return None
-
-def genpasswd():
- newpasswd=""
- chars = string.letters + string.digits
- for i in range(8):
- newpasswd = newpasswd + choice(chars)
- return newpasswd
-
-def error(email, message):
- errors.write(email + " "+ message+"\n");
-
-matchfrom=re.compile(
- r"""From ([^\s]*)""",
- re.IGNORECASE | re.DOTALL | re.VERBOSE)
-
-matchfirstname=re.compile(
- r""".*vorname:\s*([^\n\r]*)""",
- re.IGNORECASE | re.DOTALL | re.VERBOSE)
-firstname=None
-
-matchlastname=re.compile(
- r""".*nachname:\s*([^\n\r]*)\s*""",
- re.IGNORECASE | re.DOTALL | re.VERBOSE)
-lastname=None
-
-matchemail=re.compile(
- r""".*email:\s*([^\n\r]*)\s*""",
- re.IGNORECASE | re.DOTALL | re.VERBOSE)
-email=None
-
-matchaddress=re.compile(
- r""".*adresse:\s*([^\n\r]*)\s*""",
- re.IGNORECASE | re.DOTALL | re.VERBOSE)
-address=None
-
-matchcity=re.compile(
- r""".*ort:\s*([^\n\r]*)\s*""",
- re.IGNORECASE | re.DOTALL | re.VERBOSE)
-city=None
-
-matchcountry=re.compile(
- r""".*land:\s*([^\n\r]*)""",
- re.IGNORECASE | re.DOTALL | re.VERBOSE)
-country=None
-
-matchphone=re.compile(
- r""".*telefon:\s*([^\n\r]*)\s*""",
- re.IGNORECASE | re.DOTALL | re.VERBOSE)
-phone=None
-
-for line in sys.stdin.readlines():
- match=matchfrom.match(line)
- if (match!=None):
- email=match.group(1)
- continue
-
- match=matchfirstname.match(line)
- if (match!=None):
- firstname=match.group(1)
- continue
- match=matchlastname.match(line)
- if (match!=None):
- lastname=match.group(1)
- continue
- match=matchemail.match(line)
- if (match!=None):
- email=match.group(1)
- continue
- match=matchaddress.match(line)
- if (match!=None):
- address=match.group(1)
- continue
- match=matchcity.match(line)
- if (match!=None):
- city=match.group(1)
- continue
- match=matchcountry.match(line)
- if (match!=None):
- country=match.group(1)
- continue
- match=matchphone.match(line)
- if (match!=None):
- phone=match.group(1)
- continue
-
-if email==None:
- error("enno@eressea.upb.de",
- "Es wurde keine Emailadresse angegeben: "+firstname+" "+lastname)
-elif (firstname==None):
- error(email, "Es wurde kein Vorname angegeben")
-elif (lastname==None):
- error(email, "Es wurde kein Nachname angegeben")
-elif (address==None):
- error(email, "Es wurde keine Adresse angegeben")
-elif (city==None):
- error(email, "Es wurde kein Wohnort angegeben")
-elif (country==None):
- error(email, "Es wurde kein Land angegeben")
-else:
- if (phone==None):
- phone = "NULL"
-
- cursor=db.cursor()
- cursor.execute("INSERT INTO users (firstname, lastname, email, address, city, phone, country, password) "+
- "VALUES ('"+firstname+"', '"+lastname+"', '"+email+"', '"+address+"', '"+city+"', '"+phone+"', "+country+", '"+genpasswd()+"')")
-
- cursor.execute("SELECT LAST_INSERT_ID() from dual")
- userid=str(int(cursor.fetchone()[0]))
-
- cursor.execute("INSERT INTO subscriptions (user, game, status) "+
- "VALUES ("+str(userid)+", 3, 'WAITING')")
-
-errors.close()
-unlock(sys.argv[1]+".err")
diff --git a/scripts/register/sendmail.py b/scripts/register/sendmail.py
deleted file mode 100755
index f4027fc12..000000000
--- a/scripts/register/sendmail.py
+++ /dev/null
@@ -1,52 +0,0 @@
-#!/usr/bin/env python
-
-import MySQLdb
-import re
-import sys
-import smtplib
-
-
-dbname=sys.argv[1]
-template=sys.argv[2]
-state=sys.argv[3]
-tostate=sys.argv[3]
-
-server=smtplib.SMTP('localhost')
-db=MySQLdb.connect(db=dbname)
-From="accounts@vinyambar.de"
-
-cursor=db.cursor()
-query=("select users.id, users.email, users.firstname "+
- "from users, games, subscriptions "+
- "where users.id=subscriptions.user and subscriptions.game=games.id and "+
- "users.balance=0 and users.status='"+state+"'")
-
-users=cursor.execute(query)
-print "Sending confirmation to "+str(int(users))+" users"
-while users!=0:
- users=users-1
- custid, email, firstname =cursor.fetchone()
-
- infile=open(template,"r")
- line = infile.read()
-
- line = re.sub('', custid, line)
- line = re.sub('', firstname, line)
- line = re.sub("", game, line)
-
- Msg = ("From: "+From+"\nTo: "+email+"\n"+
- "Subject: Vinyambar Kontoinformationen.\n\n"+
- line)
-
- try:
- server.sendmail(From, email, Msg)
- update=db.cursor()
- update.execute("UPDATE users set status='"+tostate+"' WHERE id="+custid)
- print "Sent '"+template+"' information to "+email
-
- except:
- print "Could not inform "+To
- print "Reason was: '"+Reason+"'"
- print "Exception is:", sys.exc_type, ":", sys.exc_value
-
- infile.close()
diff --git a/scripts/register/status.sh b/scripts/register/status.sh
deleted file mode 100755
index 29d4bf41c..000000000
--- a/scripts/register/status.sh
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/bin/sh
-
-# produces a lot of status information about vinyambar.
-
-if [ $# -gt 0 ]; then
- db="$1"
-else
- db="vinyambar"
-fi
-echo "Vinyambar I"
-echo
-mysql --table $db -e "source subscriptions-1.sql"
-echo
-echo
-
-echo "Vinyambar II"
-echo
-mysql --table $db -e "source subscriptions-2.sql"
-echo
-echo
-
-echo "Rassenverteilung"
-echo
-mysql --table $db -e "source races.sql"
-echo
-echo
-
-echo "Ausgemusterte Parteien"
-echo
-mysql --table $db -e "source noowner.sql"
-echo
-echo
-
-echo "Überweisung erforderlich"
-echo
-mysql --table $db -e "source unpaid.sql"
-echo
-echo
-
-echo "Parteienverteilung"
-echo
-mysql --table $db -e "source summary.sql"
-echo
-echo
diff --git a/scripts/register/subscriptions-1.sql b/scripts/register/subscriptions-1.sql
deleted file mode 100644
index 224dd398e..000000000
--- a/scripts/register/subscriptions-1.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-select users.id, left(concat(firstname,' ',lastname, ' <',email,'>'),43) Name, subscriptions.faction Partei, races.name Rasse
- from users, games, subscriptions, races
- where subscriptions.user=users.id
- and games.id=subscriptions.game
- and subscriptions.race=races.race
- and games.id=1 and subscriptions.status='ACTIVE'
- order by subscriptions.id;
diff --git a/scripts/register/subscriptions-2.sql b/scripts/register/subscriptions-2.sql
deleted file mode 100644
index 1df60311b..000000000
--- a/scripts/register/subscriptions-2.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-select users.id, left(concat(firstname,' ',lastname, ' <',email,'>'),43) Name, subscriptions.faction Partei, races.name Rasse
- from users, games, subscriptions, races
- where subscriptions.user=users.id
- and games.id=subscriptions.game
- and subscriptions.race=races.race
- and games.id=2 and subscriptions.status='ACTIVE'
- order by subscriptions.id;
diff --git a/scripts/register/summary.sql b/scripts/register/summary.sql
deleted file mode 100644
index c8c6cfc58..000000000
--- a/scripts/register/summary.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-select count(users.status) Anzahl, subscriptions.status Status, games.name Spiel
- from users, games, subscriptions
- where games.id = subscriptions.game
- and users.id = subscriptions.user
- group by games.name, subscriptions.status
- order by subscriptions.game;
diff --git a/scripts/register/test.py b/scripts/register/test.py
deleted file mode 100755
index 6c2470860..000000000
--- a/scripts/register/test.py
+++ /dev/null
@@ -1,14 +0,0 @@
-import MySQLdb;
-db=MySQLdb.connect(db='vinyambar');
-c=db.cursor()
-users=c.execute('select id from users')
-while users>0:
- users=users-1
- c2=db.cursor()
- user=c.fetchone()[0]
- a=c2.execute('select id from transactions where user='+str(int(user)))
- if a>0:
- c2.execute("update users set status='PAYING' where id="+str(int(user)))
- else:
- c2.execute("update users set status='CONFIRMED' where id="+str(int(user)))
-
diff --git a/scripts/register/unpaid.sql b/scripts/register/unpaid.sql
deleted file mode 100644
index e7c80b5d2..000000000
--- a/scripts/register/unpaid.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-select distinct u.id ID, concat(s.game, '/', s.faction) Partei, left(concat(firstname,' ',lastname, ' <',email,'>'),43) Name, sum(t.balance) Kontostand
- from users u, transactions t, subscriptions s
- where u.id=t.user and u.id=s.user
- and s.status='ACTIVE'
- GROUP BY s.faction
- HAVING Kontostand<5;
diff --git a/scripts/register/users.sql b/scripts/register/users.sql
deleted file mode 100644
index 2f6ad36d9..000000000
--- a/scripts/register/users.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-select users.id, users.email, users.firstname, users.lastname, users.email, games.name, races.name
- from users, games, subscriptions, races
- where subscriptions.user=users.id
- and games.id=subscriptions.game
- and subscriptions.race=races.race
- order by games.id;
diff --git a/scripts/register/vinyambar.py b/scripts/register/vinyambar.py
deleted file mode 100755
index 930bb11d8..000000000
--- a/scripts/register/vinyambar.py
+++ /dev/null
@@ -1,128 +0,0 @@
-#!/usr/bin/env python
-import sys
-import curses
-import MySQLdb
-
-Footer = "Vinyambar Informationssystem"
-locale = "de"
-dbname = sys.argv[1]
-db = MySQLdb.connect(db=dbname)
-customers = {}
-custid = 0
-stdscr = curses.initscr()
-height, width = stdscr.getmaxyx()
-custinfo = stdscr.subwin(10, width, 0, 0)
-custdetail = stdscr.subwin(10, width, 10, 0)
-
-def refresh_customers():
- cursor=db.cursor()
- count=cursor.execute('SELECT id, firstname, lastname FROM users')
- while count>0:
- count=count-1
- cid, firstname, lastname = cursor.fetchone()
- customers[cid] = (firstname, lastname)
-
-def show_detail():
- line = 1
- custdetail.erase()
- custdetail.border()
- custdetail.addstr(0, 2, "[ Kontoinformationen ]", curses.A_BOLD)
- cursor=db.cursor()
- count = cursor.execute('SELECT games.name, subscriptions.status, races.name FROM games, subscriptions, races WHERE subscriptions.user='+str(custid)+' and subscriptions.race=races.race and races.locale="'+locale+'" and subscriptions.game=games.id')
- while count>0:
- count = count-1
- game, status, race = cursor.fetchone()
- custdetail.addstr(line, 2, game+' - '+race+' - '+status)
- line=line+1
- count = cursor.execute('SELECT balance, description, date FROM transactions WHERE user='+str(custid))
- line=line+1
- while count>0:
- count = count-1
- balance, description, date = cursor.fetchone()
- custdetail.addstr(line, 2, str(date)[0:10]+' - '+description+' - '+str(balance)+' EUR')
- line=line+1
- custdetail.refresh()
-
-def show_customer():
- cursor=db.cursor()
- custinfo.erase()
- custinfo.border()
- custinfo.addstr(0, 2, "[ Kundendaten ]", curses.A_BOLD)
- custinfo.addstr(1, 2, 'Kundennummer: '+str(custid))
- show_detail()
- count = cursor.execute('SELECT firstname, lastname, email, address, city, countries.name, phone, info, password, status FROM users, countries WHERE countries.id=users.country AND users.id='+str(custid))
- if (count!=0):
- firstname, lastname, email, addr, city, ccode, phone, info, passwd, status = cursor.fetchone()
- custinfo.addstr(2, 2, 'Name: '+firstname+' '+lastname)
- custinfo.addstr(3, 2, 'Address: '+addr)
- custinfo.addstr(4, 2, ' '+city+', '+ccode)
- custinfo.addstr(5, 2, 'Phone: '+phone)
- custinfo.addstr(6, 2, 'Password: '+passwd)
- if info!=None: custinfo.addstr(8, 2, str(info))
- custinfo.refresh()
-
-def search():
- global Footer, custid
- stdscr.addstr(height-1, 0, '/')
- stdscr.clrtoeol()
- curses.echo()
- s = stdscr.getstr()
- curses.noecho()
- refresh_customers()
- try:
- custid = int(s)
- except:
- curses.beep()
- Footer='Customer #'+s+' was not found'
-
- if customers.has_key(custid):
- show_customer()
- else:
- curses.beep()
- Footer='Customer #'+s+' was not found'
-
-
-def next_customer():
- global custid
- custid=custid+1
- show_customer()
-
-def prev_customer():
- global custid
- if custid>0:
- custid=custid-1
- show_customer()
-
-def main():
- global Footer
- branch = { 'q' : None, '/' : search, '+' : next_customer, '-' : prev_customer }
- while 1:
- stdscr.addstr(height-1, 0, Footer)
- stdscr.clrtoeol()
- stdscr.refresh()
- key=stdscr.getch()
- Footer=':'
- if (key<256) & (key>=0):
- c = chr(key)
- if branch.has_key(c):
- fun=branch[c]
- if (fun==None):
- break
- else:
- fun()
- else:
- Footer='Unknown keycode '+curses.keyname(key)
- curses.beep()
-
-stdscr.keypad(1)
-curses.noecho()
-curses.cbreak()
-
-try:
- show_customer()
- main()
-finally:
- stdscr.keypad(0)
- curses.echo()
- curses.nocbreak()
- curses.endwin()
diff --git a/scripts/register/vinyambar.sql b/scripts/register/vinyambar.sql
deleted file mode 100644
index f18eec2ba..000000000
--- a/scripts/register/vinyambar.sql
+++ /dev/null
@@ -1,663 +0,0 @@
-# MySQL dump 8.13
-#
-# Host: localhost Database: vinyambar
-#--------------------------------------------------------
-# Server version 3.23.36-log
-
-#
-# Table structure for table 'countries'
-#
-
-CREATE TABLE countries (
- id int(11) NOT NULL default '0',
- name varchar(32) default NULL,
- PRIMARY KEY (id)
-) TYPE=MyISAM;
-
-#
-# Dumping data for table 'countries'
-#
-
-INSERT INTO countries VALUES (1,'United States');
-INSERT INTO countries VALUES (10,'Anguilla');
-INSERT INTO countries VALUES (100,'Israel');
-INSERT INTO countries VALUES (101,'Italy');
-INSERT INTO countries VALUES (102,'Jamaica');
-INSERT INTO countries VALUES (103,'Jan Mayen');
-INSERT INTO countries VALUES (104,'Japan');
-INSERT INTO countries VALUES (105,'Jersey');
-INSERT INTO countries VALUES (106,'Jordan');
-INSERT INTO countries VALUES (107,'Kazakhstan');
-INSERT INTO countries VALUES (108,'Kenya Coast Republic');
-INSERT INTO countries VALUES (109,'Kiribati');
-INSERT INTO countries VALUES (11,'Antigua and Barbuda');
-INSERT INTO countries VALUES (111,'Korea, South');
-INSERT INTO countries VALUES (112,'Kuwait');
-INSERT INTO countries VALUES (113,'Kyrgyzstan');
-INSERT INTO countries VALUES (114,'Laos');
-INSERT INTO countries VALUES (115,'Latvia');
-INSERT INTO countries VALUES (116,'Lebanon');
-INSERT INTO countries VALUES (117,'Lesotho');
-INSERT INTO countries VALUES (118,'Liberia');
-INSERT INTO countries VALUES (12,'Argentina');
-INSERT INTO countries VALUES (120,'Liechtenstein');
-INSERT INTO countries VALUES (121,'Lithuania');
-INSERT INTO countries VALUES (122,'Luxembourg');
-INSERT INTO countries VALUES (123,'Macau');
-INSERT INTO countries VALUES (124,'Macedonia');
-INSERT INTO countries VALUES (125,'Madagascar');
-INSERT INTO countries VALUES (126,'Malawi');
-INSERT INTO countries VALUES (127,'Malaysia');
-INSERT INTO countries VALUES (128,'Maldives');
-INSERT INTO countries VALUES (129,'Mali');
-INSERT INTO countries VALUES (13,'Armenia');
-INSERT INTO countries VALUES (130,'Malta');
-INSERT INTO countries VALUES (131,'Marshall Islands');
-INSERT INTO countries VALUES (132,'Martinique');
-INSERT INTO countries VALUES (133,'Mauritania');
-INSERT INTO countries VALUES (134,'Mauritius');
-INSERT INTO countries VALUES (135,'Mayotte');
-INSERT INTO countries VALUES (136,'Mexico');
-INSERT INTO countries VALUES (137,'Moldova');
-INSERT INTO countries VALUES (138,'Monaco');
-INSERT INTO countries VALUES (139,'Mongolia');
-INSERT INTO countries VALUES (14,'Aruba');
-INSERT INTO countries VALUES (140,'Montserrat');
-INSERT INTO countries VALUES (141,'Morocco');
-INSERT INTO countries VALUES (142,'Mozambique');
-INSERT INTO countries VALUES (143,'Namibia');
-INSERT INTO countries VALUES (144,'Nauru');
-INSERT INTO countries VALUES (145,'Nepal');
-INSERT INTO countries VALUES (146,'Netherlands');
-INSERT INTO countries VALUES (147,'Netherlands Antilles');
-INSERT INTO countries VALUES (148,'New Caledonia');
-INSERT INTO countries VALUES (149,'New Zealand');
-INSERT INTO countries VALUES (15,'Australia');
-INSERT INTO countries VALUES (150,'Nicaragua');
-INSERT INTO countries VALUES (151,'Niger');
-INSERT INTO countries VALUES (152,'Nigeria');
-INSERT INTO countries VALUES (153,'Niue');
-INSERT INTO countries VALUES (154,'Norway');
-INSERT INTO countries VALUES (155,'Oman');
-INSERT INTO countries VALUES (156,'Pakistan');
-INSERT INTO countries VALUES (157,'Palau');
-INSERT INTO countries VALUES (158,'Panama');
-INSERT INTO countries VALUES (159,'Papua New Guinea');
-INSERT INTO countries VALUES (16,'Austria');
-INSERT INTO countries VALUES (160,'Paraguay');
-INSERT INTO countries VALUES (161,'Peru');
-INSERT INTO countries VALUES (162,'Philippines');
-INSERT INTO countries VALUES (163,'Poland');
-INSERT INTO countries VALUES (164,'Portugal');
-INSERT INTO countries VALUES (165,'Puerto Rico');
-INSERT INTO countries VALUES (166,'Qatar');
-INSERT INTO countries VALUES (167,'Romania');
-INSERT INTO countries VALUES (168,'Russian Federation');
-INSERT INTO countries VALUES (169,'Rwanda');
-INSERT INTO countries VALUES (17,'Azerbaijan Republic');
-INSERT INTO countries VALUES (170,'Saint Helena');
-INSERT INTO countries VALUES (171,'Saint Kitts-Nevis');
-INSERT INTO countries VALUES (172,'Saint Lucia');
-INSERT INTO countries VALUES (173,'Saint Pierre and Miquelon');
-INSERT INTO countries VALUES (174,'Saint Vincent and the Grenadines');
-INSERT INTO countries VALUES (175,'San Marino');
-INSERT INTO countries VALUES (176,'Saudi Arabia');
-INSERT INTO countries VALUES (177,'Senegal');
-INSERT INTO countries VALUES (178,'Seychelles');
-INSERT INTO countries VALUES (179,'Sierra Leone');
-INSERT INTO countries VALUES (18,'Bahamas');
-INSERT INTO countries VALUES (180,'Singapore');
-INSERT INTO countries VALUES (181,'Slovakia');
-INSERT INTO countries VALUES (182,'Slovenia');
-INSERT INTO countries VALUES (183,'Solomon Islands');
-INSERT INTO countries VALUES (184,'Somalia');
-INSERT INTO countries VALUES (185,'South Africa');
-INSERT INTO countries VALUES (186,'Spain');
-INSERT INTO countries VALUES (187,'Sri Lanka');
-INSERT INTO countries VALUES (188,'Sudan');
-INSERT INTO countries VALUES (189,'Suriname');
-INSERT INTO countries VALUES (19,'Bahrain');
-INSERT INTO countries VALUES (190,'Svalbard');
-INSERT INTO countries VALUES (191,'Swaziland');
-INSERT INTO countries VALUES (192,'Sweden');
-INSERT INTO countries VALUES (193,'Switzerland');
-INSERT INTO countries VALUES (194,'Syria');
-INSERT INTO countries VALUES (195,'Tahiti');
-INSERT INTO countries VALUES (196,'Taiwan');
-INSERT INTO countries VALUES (197,'Tajikistan');
-INSERT INTO countries VALUES (198,'Tanzania');
-INSERT INTO countries VALUES (199,'Thailand');
-INSERT INTO countries VALUES (2,'Canada');
-INSERT INTO countries VALUES (20,'Bangladesh');
-INSERT INTO countries VALUES (200,'Togo');
-INSERT INTO countries VALUES (201,'Tonga');
-INSERT INTO countries VALUES (202,'Trinidad and Tobago');
-INSERT INTO countries VALUES (203,'Tunisia');
-INSERT INTO countries VALUES (204,'Turkey');
-INSERT INTO countries VALUES (205,'Turkmenistan');
-INSERT INTO countries VALUES (206,'Turks and Caicos Islands');
-INSERT INTO countries VALUES (207,'Tuvalu');
-INSERT INTO countries VALUES (208,'Uganda');
-INSERT INTO countries VALUES (209,'Ukraine');
-INSERT INTO countries VALUES (21,'Barbados');
-INSERT INTO countries VALUES (210,'United Arab Emirates');
-INSERT INTO countries VALUES (211,'Uruguay');
-INSERT INTO countries VALUES (212,'Uzbekistan');
-INSERT INTO countries VALUES (213,'Vanuatu');
-INSERT INTO countries VALUES (214,'Vatican City State');
-INSERT INTO countries VALUES (215,'Venezuela');
-INSERT INTO countries VALUES (216,'Vietnam');
-INSERT INTO countries VALUES (217,'Virgin Islands (U.S.)');
-INSERT INTO countries VALUES (218,'Wallis and Futuna');
-INSERT INTO countries VALUES (219,'Western Sahara');
-INSERT INTO countries VALUES (22,'Belarus');
-INSERT INTO countries VALUES (220,'Western Samoa');
-INSERT INTO countries VALUES (221,'Yemen');
-INSERT INTO countries VALUES (222,'Yugoslavia');
-INSERT INTO countries VALUES (223,'Zambia');
-INSERT INTO countries VALUES (224,'Zimbabwe');
-INSERT INTO countries VALUES (225,'APO/FPO');
-INSERT INTO countries VALUES (226,'Micronesia');
-INSERT INTO countries VALUES (23,'Belgium');
-INSERT INTO countries VALUES (24,'Belize');
-INSERT INTO countries VALUES (25,'Benin');
-INSERT INTO countries VALUES (26,'Bermuda');
-INSERT INTO countries VALUES (27,'Bhutan');
-INSERT INTO countries VALUES (28,'Bolivia');
-INSERT INTO countries VALUES (29,'Bosnia and Herzegovina');
-INSERT INTO countries VALUES (3,'United Kingdom');
-INSERT INTO countries VALUES (30,'Botswana');
-INSERT INTO countries VALUES (31,'Brazil');
-INSERT INTO countries VALUES (32,'British Virgin Islands');
-INSERT INTO countries VALUES (33,'Brunei Darussalam');
-INSERT INTO countries VALUES (34,'Bulgaria');
-INSERT INTO countries VALUES (35,'Burkina Faso');
-INSERT INTO countries VALUES (36,'Burma');
-INSERT INTO countries VALUES (37,'Burundi');
-INSERT INTO countries VALUES (38,'Cambodia');
-INSERT INTO countries VALUES (39,'Cameroon');
-INSERT INTO countries VALUES (4,'Afghanistan');
-INSERT INTO countries VALUES (40,'Cape Verde Islands');
-INSERT INTO countries VALUES (41,'Cayman Islands');
-INSERT INTO countries VALUES (42,'Central African Republic');
-INSERT INTO countries VALUES (43,'Chad');
-INSERT INTO countries VALUES (44,'Chile');
-INSERT INTO countries VALUES (45,'China');
-INSERT INTO countries VALUES (46,'Colombia');
-INSERT INTO countries VALUES (47,'Comoros');
-INSERT INTO countries VALUES (48,'Congo, Democratic Republic of th');
-INSERT INTO countries VALUES (49,'Congo, Republic of the');
-INSERT INTO countries VALUES (5,'Albania');
-INSERT INTO countries VALUES (50,'Cook Islands');
-INSERT INTO countries VALUES (51,'Costa Rica');
-INSERT INTO countries VALUES (52,'Cote d Ivoire (Ivory Coast)');
-INSERT INTO countries VALUES (53,'Croatia, Republic of');
-INSERT INTO countries VALUES (55,'Cyprus');
-INSERT INTO countries VALUES (56,'Czech Republic');
-INSERT INTO countries VALUES (57,'Denmark');
-INSERT INTO countries VALUES (58,'Djibouti');
-INSERT INTO countries VALUES (59,'Dominica');
-INSERT INTO countries VALUES (6,'Algeria');
-INSERT INTO countries VALUES (60,'Dominican Republic');
-INSERT INTO countries VALUES (61,'Ecuador');
-INSERT INTO countries VALUES (62,'Egypt');
-INSERT INTO countries VALUES (63,'El Salvador');
-INSERT INTO countries VALUES (64,'Equatorial Guinea');
-INSERT INTO countries VALUES (65,'Eritrea');
-INSERT INTO countries VALUES (66,'Estonia');
-INSERT INTO countries VALUES (67,'Ethiopia');
-INSERT INTO countries VALUES (68,'Falkland Islands (Islas Malvinas');
-INSERT INTO countries VALUES (69,'Fiji');
-INSERT INTO countries VALUES (7,'American Samoa');
-INSERT INTO countries VALUES (70,'Finland');
-INSERT INTO countries VALUES (71,'France');
-INSERT INTO countries VALUES (72,'French Guiana');
-INSERT INTO countries VALUES (73,'French Polynesia');
-INSERT INTO countries VALUES (74,'Gabon Republic');
-INSERT INTO countries VALUES (75,'Gambia');
-INSERT INTO countries VALUES (76,'Georgia');
-INSERT INTO countries VALUES (77,'Germany');
-INSERT INTO countries VALUES (78,'Ghana');
-INSERT INTO countries VALUES (79,'Gibraltar');
-INSERT INTO countries VALUES (8,'Andorra');
-INSERT INTO countries VALUES (80,'Greece');
-INSERT INTO countries VALUES (81,'Greenland');
-INSERT INTO countries VALUES (82,'Grenada');
-INSERT INTO countries VALUES (83,'Guadeloupe');
-INSERT INTO countries VALUES (84,'Guam');
-INSERT INTO countries VALUES (85,'Guatemala');
-INSERT INTO countries VALUES (86,'Guernsey');
-INSERT INTO countries VALUES (87,'Guinea');
-INSERT INTO countries VALUES (88,'Guinea-Bissau');
-INSERT INTO countries VALUES (89,'Guyana');
-INSERT INTO countries VALUES (9,'Angola');
-INSERT INTO countries VALUES (90,'Haiti');
-INSERT INTO countries VALUES (91,'Honduras');
-INSERT INTO countries VALUES (92,'Hong Kong');
-INSERT INTO countries VALUES (93,'Hungary');
-INSERT INTO countries VALUES (94,'Iceland');
-INSERT INTO countries VALUES (95,'India');
-INSERT INTO countries VALUES (96,'Indonesia');
-INSERT INTO countries VALUES (99,'Ireland');
-
-#
-# Table structure for table 'dual'
-#
-
-CREATE TABLE dual (
- dual char(1) default NULL
-) TYPE=MyISAM;
-
-#
-# Dumping data for table 'dual'
-#
-
-INSERT INTO dual VALUES ('0');
-
-#
-# Table structure for table 'factions'
-#
-
-CREATE TABLE factions (
- id varchar(6) NOT NULL default '',
- game int(11) NOT NULL default '0',
- email varchar(64) default NULL,
- banner text,
- vacation varchar(64) default NULL,
- password varchar(64) default NULL,
- name varchar(64) default NULL,
- user int(11) NOT NULL default '0',
- vacation_start date default NULL,
- race varchar(16) default NULL,
- locale varchar(10) default NULL,
- lastorders int(11) default NULL,
- PRIMARY KEY (id,game)
-) TYPE=MyISAM;
-
-#
-# Dumping data for table 'factions'
-#
-
-
-#
-# Table structure for table 'games'
-#
-
-CREATE TABLE games (
- id int(11) NOT NULL auto_increment,
- name varchar(32) NOT NULL default '',
- info text,
- PRIMARY KEY (id)
-) TYPE=MyISAM;
-
-#
-# Dumping data for table 'games'
-#
-
-INSERT INTO games VALUES (1,'Vinyambar I','Vinyambar nach alten Regeln');
-INSERT INTO games VALUES (2,'Vinyambar II','Vinyambar nach neuen Regeln');
-INSERT INTO games VALUES (3,'Warteliste','Interessenten für neue Regeln');
-
-#
-# Table structure for table 'races'
-#
-
-CREATE TABLE races (
- locale varchar(10) NOT NULL default '',
- race varchar(10) NOT NULL default '',
- name varchar(20) default NULL
-) TYPE=MyISAM;
-
-#
-# Dumping data for table 'races'
-#
-
-INSERT INTO races VALUES ('de','GOBLIN','Goblins');
-INSERT INTO races VALUES ('de','DWARF','Zwerge');
-INSERT INTO races VALUES ('de','ELF','Elfen');
-INSERT INTO races VALUES ('de','HALFLING','Halblinge');
-INSERT INTO races VALUES ('de','INSECT','Insekten');
-INSERT INTO races VALUES ('de','AQUARIAN','Meermenschen');
-INSERT INTO races VALUES ('de','HUMAN','Menschen');
-INSERT INTO races VALUES ('de','CAT','Katzen');
-INSERT INTO races VALUES ('de','TROLL','Trolle');
-INSERT INTO races VALUES ('de','ORC','Orks');
-INSERT INTO races VALUES ('de','DEMON','Dämonen');
-
-#
-# Table structure for table 'subscriptions'
-#
-
-CREATE TABLE subscriptions (
- game int(11) NOT NULL default '0',
- user int(11) NOT NULL default '0',
- race varchar(10) default NULL,
- id int(10) NOT NULL auto_increment,
- status varchar(10) NOT NULL default 'NEW',
- updated timestamp(14) NOT NULL,
- credits int(11) NOT NULL default '0',
- PRIMARY KEY (id)
-) TYPE=MyISAM;
-
-#
-# Dumping data for table 'subscriptions'
-#
-
-INSERT INTO subscriptions VALUES (1,4,'ELF',4,'CONFIRMED',20011106230004,0);
-INSERT INTO subscriptions VALUES (1,2,'HUMAN',2,'CONFIRMED',20011106224055,0);
-INSERT INTO subscriptions VALUES (1,3,'DWARF',3,'CONFIRMED',20011106224055,0);
-INSERT INTO subscriptions VALUES (1,5,'HALFLING',5,'CONFIRMED',20011106230004,0);
-INSERT INTO subscriptions VALUES (1,6,'DWARF',6,'CONFIRMED',20011106231004,0);
-INSERT INTO subscriptions VALUES (1,7,'ELF',7,'CONFIRMED',20011106231504,0);
-INSERT INTO subscriptions VALUES (1,8,'TROLL',8,'CONFIRMED',20011106232003,0);
-INSERT INTO subscriptions VALUES (1,9,'DWARF',9,'CONFIRMED',20011106233004,0);
-INSERT INTO subscriptions VALUES (1,10,'ELF',10,'CONFIRMED',20011106233005,0);
-INSERT INTO subscriptions VALUES (1,11,'DWARF',11,'CONFIRMED',20011106233005,0);
-INSERT INTO subscriptions VALUES (2,12,'GOBLIN',12,'CONFIRMED',20011106233505,0);
-INSERT INTO subscriptions VALUES (1,68,'DWARF',78,'CONFIRMED',20011108215504,0);
-INSERT INTO subscriptions VALUES (2,67,'TROLL',77,'CONFIRMED',20011108201004,0);
-INSERT INTO subscriptions VALUES (1,14,'CAT',15,'CONFIRMED',20011107000503,0);
-INSERT INTO subscriptions VALUES (1,15,'ELF',16,'CONFIRMED',20011107002509,0);
-INSERT INTO subscriptions VALUES (2,15,'HALFLING',17,'CONFIRMED',20011107013618,0);
-INSERT INTO subscriptions VALUES (2,18,'AQUARIAN',18,'CONFIRMED',20011107085504,0);
-INSERT INTO subscriptions VALUES (1,19,'DEMON',19,'CONFIRMED',20011107085504,0);
-INSERT INTO subscriptions VALUES (2,19,'AQUARIAN',20,'CONFIRMED',20011107085504,0);
-INSERT INTO subscriptions VALUES (2,20,'ELF',21,'CONFIRMED',20011107085504,0);
-INSERT INTO subscriptions VALUES (2,21,'CAT',22,'CONFIRMED',20011111220350,0);
-INSERT INTO subscriptions VALUES (1,22,'HALFLING',23,'CONFIRMED',20011107095504,0);
-INSERT INTO subscriptions VALUES (2,23,'DEMON',24,'CONFIRMED',20011107105009,0);
-INSERT INTO subscriptions VALUES (2,24,'AQUARIAN',25,'CONFIRMED',20011107105504,0);
-INSERT INTO subscriptions VALUES (2,25,'DWARF',26,'CONFIRMED',20011107110503,0);
-INSERT INTO subscriptions VALUES (2,26,'AQUARIAN',27,'CONFIRMED',20011107114004,0);
-INSERT INTO subscriptions VALUES (1,27,'ELF',28,'CONFIRMED',20011107120503,0);
-INSERT INTO subscriptions VALUES (2,27,'CAT',29,'CONFIRMED',20011107120503,0);
-INSERT INTO subscriptions VALUES (1,28,'HUMAN',30,'CONFIRMED',20011107121506,0);
-INSERT INTO subscriptions VALUES (1,29,'AQUARIAN',31,'CONFIRMED',20011107122004,0);
-INSERT INTO subscriptions VALUES (2,29,'AQUARIAN',32,'CONFIRMED',20011107122004,0);
-INSERT INTO subscriptions VALUES (2,30,'HALFLING',33,'CONFIRMED',20011107123504,0);
-INSERT INTO subscriptions VALUES (1,31,'TROLL',34,'CONFIRMED',20011107135004,0);
-INSERT INTO subscriptions VALUES (2,32,'TROLL',35,'CONFIRMED',20011107143508,0);
-INSERT INTO subscriptions VALUES (2,33,'DEMON',36,'CONFIRMED',20011107152006,0);
-INSERT INTO subscriptions VALUES (2,34,'ELF',37,'CONFIRMED',20011107154504,0);
-INSERT INTO subscriptions VALUES (2,35,'DWARF',38,'CONFIRMED',20011107154504,0);
-INSERT INTO subscriptions VALUES (2,36,'AQUARIAN',39,'CONFIRMED',20011107160504,0);
-INSERT INTO subscriptions VALUES (2,37,'GOBLIN',40,'CONFIRMED',20011107161008,0);
-INSERT INTO subscriptions VALUES (2,38,'CAT',41,'CONFIRMED',20011107163023,0);
-INSERT INTO subscriptions VALUES (2,39,'HUMAN',42,'CONFIRMED',20011107164505,0);
-INSERT INTO subscriptions VALUES (2,40,'ORC',43,'CONFIRMED',20011107171004,0);
-INSERT INTO subscriptions VALUES (2,41,'DWARF',44,'CONFIRMED',20011107173004,0);
-INSERT INTO subscriptions VALUES (2,42,'DEMON',45,'CONFIRMED',20011107184004,0);
-INSERT INTO subscriptions VALUES (2,43,'INSECT',46,'CONFIRMED',20011107190504,0);
-INSERT INTO subscriptions VALUES (2,44,'AQUARIAN',47,'CONFIRMED',20011107200004,0);
-INSERT INTO subscriptions VALUES (1,45,'DWARF',48,'CONFIRMED',20011107201504,0);
-INSERT INTO subscriptions VALUES (2,45,'AQUARIAN',49,'CONFIRMED',20011107201504,0);
-INSERT INTO subscriptions VALUES (2,46,'INSECT',50,'CONFIRMED',20011107202504,0);
-INSERT INTO subscriptions VALUES (2,47,'CAT',51,'CONFIRMED',20011107203004,0);
-INSERT INTO subscriptions VALUES (1,48,'TROLL',52,'CONFIRMED',20011107203508,0);
-INSERT INTO subscriptions VALUES (2,48,'DWARF',53,'CONFIRMED',20011107203509,0);
-INSERT INTO subscriptions VALUES (1,49,'ELF',54,'CONFIRMED',20011107213503,0);
-INSERT INTO subscriptions VALUES (2,50,'HUMAN',55,'CONFIRMED',20011107222003,0);
-INSERT INTO subscriptions VALUES (2,51,'AQUARIAN',56,'CONFIRMED',20011107223504,0);
-INSERT INTO subscriptions VALUES (1,52,'TROLL',57,'CONFIRMED',20011107223504,0);
-INSERT INTO subscriptions VALUES (2,52,'HUMAN',58,'CONFIRMED',20011107223504,0);
-INSERT INTO subscriptions VALUES (1,53,'HUMAN',59,'CONFIRMED',20011107223504,0);
-INSERT INTO subscriptions VALUES (2,53,'HUMAN',60,'CONFIRMED',20011107223505,0);
-INSERT INTO subscriptions VALUES (1,54,'DWARF',61,'CONFIRMED',20011107234505,0);
-INSERT INTO subscriptions VALUES (1,55,'HUMAN',62,'CONFIRMED',20011108001003,0);
-INSERT INTO subscriptions VALUES (2,56,'TROLL',63,'CONFIRMED',20011108023507,0);
-INSERT INTO subscriptions VALUES (1,57,'AQUARIAN',64,'CONFIRMED',20011108095504,0);
-INSERT INTO subscriptions VALUES (2,58,'HUMAN',65,'CONFIRMED',20011108124503,0);
-INSERT INTO subscriptions VALUES (2,59,'DWARF',66,'CONFIRMED',20011108153006,0);
-INSERT INTO subscriptions VALUES (2,60,'DWARF',67,'CONFIRMED',20011108154504,0);
-INSERT INTO subscriptions VALUES (2,61,'INSECT',68,'CONFIRMED',20011108165505,0);
-INSERT INTO subscriptions VALUES (1,62,'HALFLING',69,'CONFIRMED',20011108183504,0);
-INSERT INTO subscriptions VALUES (2,62,'ELF',70,'CONFIRMED',20011108183504,0);
-INSERT INTO subscriptions VALUES (1,63,'DEMON',71,'CONFIRMED',20011108183504,0);
-INSERT INTO subscriptions VALUES (2,63,'ELF',72,'CONFIRMED',20011108183504,0);
-INSERT INTO subscriptions VALUES (1,64,'INSECT',73,'CONFIRMED',20011108185004,0);
-INSERT INTO subscriptions VALUES (2,65,'DWARF',74,'CONFIRMED',20011108192503,0);
-INSERT INTO subscriptions VALUES (1,66,'DWARF',75,'CONFIRMED',20011108195504,0);
-INSERT INTO subscriptions VALUES (2,66,'ELF',76,'CONFIRMED',20011108195505,0);
-INSERT INTO subscriptions VALUES (2,69,'INSECT',79,'CONFIRMED',20011108220003,0);
-INSERT INTO subscriptions VALUES (2,70,'HALFLING',80,'CONFIRMED',20011108222503,0);
-INSERT INTO subscriptions VALUES (1,71,'DWARF',81,'CONFIRMED',20011108224013,0);
-INSERT INTO subscriptions VALUES (1,72,'GOBLIN',82,'CONFIRMED',20011108224503,0);
-INSERT INTO subscriptions VALUES (2,72,'DWARF',83,'CONFIRMED',20011108224503,0);
-INSERT INTO subscriptions VALUES (1,73,'TROLL',84,'CONFIRMED',20011108225004,0);
-INSERT INTO subscriptions VALUES (1,74,'HUMAN',85,'CONFIRMED',20011109070003,0);
-INSERT INTO subscriptions VALUES (2,74,'HUMAN',86,'CONFIRMED',20011109070004,0);
-INSERT INTO subscriptions VALUES (2,75,'DWARF',87,'CONFIRMED',20011109094004,0);
-INSERT INTO subscriptions VALUES (2,76,'ELF',88,'CONFIRMED',20011109094504,0);
-INSERT INTO subscriptions VALUES (1,77,'ELF',89,'CONFIRMED',20011109094504,0);
-INSERT INTO subscriptions VALUES (2,78,'DWARF',90,'CONFIRMED',20011109103504,0);
-INSERT INTO subscriptions VALUES (2,79,'ORC',91,'CONFIRMED',20011109105004,0);
-INSERT INTO subscriptions VALUES (2,80,'DEMON',92,'CONFIRMED',20011109121504,0);
-INSERT INTO subscriptions VALUES (2,81,'INSECT',93,'CONFIRMED',20011109131003,0);
-INSERT INTO subscriptions VALUES (2,82,'DEMON',94,'CONFIRMED',20011109144004,0);
-INSERT INTO subscriptions VALUES (2,83,'CAT',95,'CONFIRMED',20011109145004,0);
-INSERT INTO subscriptions VALUES (2,84,'AQUARIAN',96,'CONFIRMED',20011109190003,0);
-INSERT INTO subscriptions VALUES (2,85,'GOBLIN',97,'CONFIRMED',20011109210506,0);
-INSERT INTO subscriptions VALUES (1,86,'GOBLIN',98,'CONFIRMED',20011109215004,0);
-INSERT INTO subscriptions VALUES (2,87,'ELF',99,'CONFIRMED',20011110115504,0);
-INSERT INTO subscriptions VALUES (2,88,'AQUARIAN',100,'CONFIRMED',20011110121004,0);
-INSERT INTO subscriptions VALUES (2,89,'TROLL',101,'CONFIRMED',20011110130504,0);
-INSERT INTO subscriptions VALUES (1,90,'DWARF',102,'CONFIRMED',20011110142021,0);
-INSERT INTO subscriptions VALUES (2,90,'DWARF',103,'CONFIRMED',20011110142021,0);
-INSERT INTO subscriptions VALUES (2,91,'AQUARIAN',104,'CONFIRMED',20011110142504,0);
-INSERT INTO subscriptions VALUES (1,93,'GOBLIN',106,'CONFIRMED',20011110152005,0);
-INSERT INTO subscriptions VALUES (1,94,'HALFLING',107,'CONFIRMED',20011110152005,0);
-INSERT INTO subscriptions VALUES (2,95,'HALFLING',108,'CONFIRMED',20011110155005,0);
-INSERT INTO subscriptions VALUES (2,96,'ELF',109,'CONFIRMED',20011110160003,0);
-INSERT INTO subscriptions VALUES (1,97,'DEMON',110,'CONFIRMED',20011110180504,0);
-INSERT INTO subscriptions VALUES (2,97,'HALFLING',111,'CONFIRMED',20011110180504,0);
-INSERT INTO subscriptions VALUES (1,98,'ORC',112,'CONFIRMED',20011110190508,0);
-INSERT INTO subscriptions VALUES (2,99,'AQUARIAN',113,'CONFIRMED',20011110201003,0);
-INSERT INTO subscriptions VALUES (1,100,'ELF',114,'CONFIRMED',20011110202005,0);
-INSERT INTO subscriptions VALUES (2,101,'HUMAN',115,'CONFIRMED',20011110204505,0);
-INSERT INTO subscriptions VALUES (2,102,'DEMON',116,'CONFIRMED',20011111111504,0);
-INSERT INTO subscriptions VALUES (2,103,'DWARF',117,'CONFIRMED',20011111113004,0);
-INSERT INTO subscriptions VALUES (1,104,'ELF',118,'CONFIRMED',20011111140003,0);
-INSERT INTO subscriptions VALUES (1,105,'TROLL',119,'CONFIRMED',20011111141504,0);
-INSERT INTO subscriptions VALUES (2,106,'DEMON',120,'CONFIRMED',20011111144505,0);
-INSERT INTO subscriptions VALUES (2,107,'ELF',121,'CONFIRMED',20011111161507,0);
-INSERT INTO subscriptions VALUES (2,108,'AQUARIAN',122,'CONFIRMED',20011111162004,0);
-INSERT INTO subscriptions VALUES (2,109,'INSECT',123,'CONFIRMED',20011111163004,0);
-INSERT INTO subscriptions VALUES (1,110,'INSECT',124,'CONFIRMED',20011111164510,0);
-INSERT INTO subscriptions VALUES (1,111,'HALFLING',125,'CONFIRMED',20011111185004,0);
-INSERT INTO subscriptions VALUES (2,111,'DEMON',126,'CONFIRMED',20011111185005,0);
-INSERT INTO subscriptions VALUES (2,112,'AQUARIAN',127,'CONFIRMED',20011111195004,0);
-INSERT INTO subscriptions VALUES (1,114,'ELF',129,'CONFIRMED',20011111202506,0);
-INSERT INTO subscriptions VALUES (2,115,'DWARF',130,'CONFIRMED',20011111214505,0);
-INSERT INTO subscriptions VALUES (1,116,'TROLL',131,'CONFIRMED',20011111225505,0);
-INSERT INTO subscriptions VALUES (2,116,'HALFLING',132,'CONFIRMED',20011111225506,0);
-INSERT INTO subscriptions VALUES (2,117,'DEMON',133,'CONFIRMED',20011112063020,0);
-INSERT INTO subscriptions VALUES (2,118,'TROLL',134,'CONFIRMED',20011112082005,0);
-INSERT INTO subscriptions VALUES (2,119,'HUMAN',135,'CONFIRMED',20011112101504,0);
-INSERT INTO subscriptions VALUES (2,120,'HUMAN',136,'CONFIRMED',20011112103004,0);
-INSERT INTO subscriptions VALUES (1,121,'AQUARIAN',137,'CONFIRMED',20011112103004,0);
-INSERT INTO subscriptions VALUES (2,121,'GOBLIN',138,'CONFIRMED',20011114122718,0);
-INSERT INTO subscriptions VALUES (2,122,'DWARF',139,'CONFIRMED',20011112103004,0);
-INSERT INTO subscriptions VALUES (1,123,'DEMON',140,'CONFIRMED',20011112121504,0);
-INSERT INTO subscriptions VALUES (2,124,'AQUARIAN',141,'CONFIRMED',20011112141504,0);
-INSERT INTO subscriptions VALUES (2,125,'INSECT',142,'CONFIRMED',20011112143003,0);
-INSERT INTO subscriptions VALUES (1,126,'INSECT',143,'CONFIRMED',20011112155004,0);
-INSERT INTO subscriptions VALUES (1,127,'HUMAN',144,'CONFIRMED',20011112170004,0);
-INSERT INTO subscriptions VALUES (2,128,'GOBLIN',145,'CONFIRMED',20011112172503,0);
-INSERT INTO subscriptions VALUES (2,129,'INSECT',146,'CONFIRMED',20011112184504,0);
-INSERT INTO subscriptions VALUES (1,130,'HALFLING',147,'CONFIRMED',20011112204505,0);
-INSERT INTO subscriptions VALUES (2,130,'ELF',148,'CONFIRMED',20011112204505,0);
-INSERT INTO subscriptions VALUES (2,131,'TROLL',149,'CONFIRMED',20011112225503,0);
-INSERT INTO subscriptions VALUES (1,132,'ELF',150,'CONFIRMED',20011113010003,0);
-INSERT INTO subscriptions VALUES (1,133,'ELF',151,'CONFIRMED',20011113013503,0);
-INSERT INTO subscriptions VALUES (2,134,'CAT',152,'CONFIRMED',20011113085504,0);
-INSERT INTO subscriptions VALUES (2,135,'ELF',153,'CONFIRMED',20011113145505,0);
-INSERT INTO subscriptions VALUES (1,136,'ELF',154,'CONFIRMED',20011113151504,0);
-INSERT INTO subscriptions VALUES (2,137,'GOBLIN',155,'CONFIRMED',20011113230507,0);
-INSERT INTO subscriptions VALUES (2,138,'DWARF',156,'CONFIRMED',20011114002504,0);
-INSERT INTO subscriptions VALUES (2,139,'GOBLIN',157,'CONFIRMED',20011114110503,0);
-INSERT INTO subscriptions VALUES (2,140,'DEMON',158,'CONFIRMED',20011114112004,0);
-INSERT INTO subscriptions VALUES (3,141,'DWARF',159,'WAITING',20011114162334,0);
-INSERT INTO subscriptions VALUES (1,142,'INSECT',160,'CONFIRMED',20011116222017,0);
-INSERT INTO subscriptions VALUES (3,143,'HALFLING',161,'WAITING',20011118204013,0);
-
-#
-# Table structure for table 'users'
-#
-
-CREATE TABLE users (
- id int(11) NOT NULL auto_increment,
- email varchar(64) default NULL,
- info text,
- address varchar(28) default NULL,
- city varchar(28) default NULL,
- country int(11) NOT NULL default '0',
- phone varchar(32) default NULL,
- firstname varchar(32) default NULL,
- lastname varchar(32) default NULL,
- password varchar(16) NOT NULL default '',
- updated timestamp(14) NOT NULL,
- PRIMARY KEY (id)
-) TYPE=MyISAM;
-
-#
-# Dumping data for table 'users'
-#
-
-INSERT INTO users VALUES (4,'stemu@netcologne.de',NULL,'Mendener Str. 9','51105 Kvln',77,'','Stephan','M|ller','MsR675tf',20011106225756);
-INSERT INTO users VALUES (2,'christianemmler@t-online.de',NULL,'Delmestrasse 55','27777 Ganderkesee',77,'04222-7951073','Christian','Emmler','awfUaLOw',20011106223256);
-INSERT INTO users VALUES (3,'R.Pusbatzkies@gmx.de',NULL,'Heideweg 6','03119 Welzow',77,'035751 12823','Rene','Pusbatzkies','4X2eRrsb',20011106224026);
-INSERT INTO users VALUES (5,'meirose@studst.fh-muenster.de',NULL,'Lange Strasse 11','27777 Ganderkesee',77,'','Nils','Meirose','gPG1Simr',20011106233417);
-INSERT INTO users VALUES (6,'alkas@t-online.de',NULL,'Emil-Barth-Str.99','Düsseldorf',77,'','Thomas','Volkmann','cwD7oD6H',20011106230847);
-INSERT INTO users VALUES (7,'rosenhaeger@planet-interkom.de',NULL,'Mühlenbrink 18','Detmold',77,'05231-628338','Dirk','Rosenhäger','OwSKnl97',20011106231428);
-INSERT INTO users VALUES (8,'sibbi@freenet.de',NULL,'Jägersberg 12','24103 Kiel',77,'0431552372','Christopher','Sievers','SachwIuS',20011106231808);
-INSERT INTO users VALUES (9,'michael-steil@t-online.de',NULL,'Im Langgarten 14 A','66687 Wadern',77,'06874/182022','Michael','Steil','r3OHgxAp',20011106232959);
-INSERT INTO users VALUES (10,'DMuenstermann@t-online.de',NULL,'Lärchenstr. 4','45892 Gelsenkirchen',77,'0209 799440','Denise','Münstermann','zcMn5FvU',20011106233000);
-INSERT INTO users VALUES (11,'dvaergynlaender@gmx.de',NULL,'Lärchenstr. 4','45892 Gelsenkirchen',77,'0209 799440','Dirk','Marquardt','ylW7nwOm',20011106233000);
-INSERT INTO users VALUES (12,'D.Axmacher@t-online.de',NULL,'Streuffstr. 46','Emmerich',77,'02828/92003','Daniel','Axmacher','wqpuZzMx',20011106233008);
-INSERT INTO users VALUES (67,'bigkas@newsfactory.net',NULL,'Lechfeldstr. 23b','86316 Friedberg',77,'0821 229 29 12 (ges)','Klaus','Borchert','li1v7r2m',20011108200859);
-INSERT INTO users VALUES (14,'cennaire@gmx.de',NULL,'Im Langgarten 14 A','66687 wadern',77,'','Sabine','Steil','MF6mH6ni',20011107000431);
-INSERT INTO users VALUES (15,'Aerisprojekt@web.de',NULL,'Sundgauer Str. 105R','Berlin',77,'','Immanuel','Völker','ugTXl7Pn',20011107002356);
-INSERT INTO users VALUES (20,'Schrat@t-online.de',NULL,'Wolfinstr. 10','77830 Bühlertal',77,'07223/991569','Jens','Schrader','o7uFqyKF',20011107085420);
-INSERT INTO users VALUES (19,'saressa@celtic-visions.net',NULL,'Geismar Landstr. 9','Göttingen',77,'0551 / 49569266','Thomas','Schmeja','SiocxqZh',20011107085410);
-INSERT INTO users VALUES (18,'Muescha@epost.de',NULL,'Saßnitzer Str. 4','Dresden',77,'','Michael','Sommer','0378RCOT',20011107085255);
-INSERT INTO users VALUES (21,'red@gmx.de',NULL,'Selchower Strasse 28','12049 Berlin',77,'','Mareike','Paluk','IcC3kQ7P',20011107093654);
-INSERT INTO users VALUES (22,'mirco-jabs@gmx.de',NULL,'Am Bollheister 54','47055 Duisburg',77,'','Mirco','Jabs','yREUOJd6',20011107095421);
-INSERT INTO users VALUES (23,'egonaut@web.de',NULL,'Cammannstraße 4','38118 Braunschweig',77,'','Karsten','Schulz','ZSLPdqYW',20011107104844);
-INSERT INTO users VALUES (24,'Santa_Cruz_@web.de',NULL,'Willy-Andreas-Allee 7','76131 Karlsruhe',77,'0178 - 4577630','Andreas','Kreuzer','xaC1vz69',20011107105426);
-INSERT INTO users VALUES (25,'vic@tzi.de',NULL,'Hahnenstr. 21','28309 Bremen',77,'','Victor','Wundersee','Mv7l3PAz',20011107110426);
-INSERT INTO users VALUES (26,'marcelkessels@web.de',NULL,'Bismarckstr. 51','41747 Viersen',77,'02162-574670','Marcel','Kessels','9XRr1bVY',20011107113517);
-INSERT INTO users VALUES (27,'elfpunkt@yahoo.de',NULL,'Kirchheimer Str. 18','69214 Eppelheim',77,'','Dietmar','Fischer','ifEeJPKV',20011107120408);
-INSERT INTO users VALUES (28,'ChiefMUC@gmx.net',NULL,'Josef-Frankl-Strasse 11B','80995 München',77,'','Oliver','Pappalardo','sQNeuVmz',20011107121008);
-INSERT INTO users VALUES (29,'rolf.schmidt@nefkom.net',NULL,'Krugstr 22','90419 Nürnberg',77,'0049 172 8249600','Rolf','Schmidt','pYhJ45ya',20011107121817);
-INSERT INTO users VALUES (30,'Gron-T.kar@gmx.de',NULL,'Hultroper Dorfstraße 19','59510 Lippetal-Hultrop',77,'02527/8362','Dominik','Gösken','6yMUcZE1',20011107123201);
-INSERT INTO users VALUES (31,'roland.engels@web.de',NULL,'17 Lutton Place','Edinburgh EH8 9PD',3,'0044-131-6681134','Roland','Engels','bJLkxYpZ',20011107134618);
-INSERT INTO users VALUES (32,'sahne@tzi.de',NULL,'Hinter dem Gartel 47','OHZ',77,'04791/899006','Daniel','Kühn','JVDBiaGt',20011107143430);
-INSERT INTO users VALUES (33,'michael@kamenz.de',NULL,'Kirchweg 4','01920 Wendischbaselitz',77,'+49 3578 305068','Michael','Möller','jIqBsV1p',20011107151554);
-INSERT INTO users VALUES (34,'wuestenkrieg@gmx.de',NULL,'Hauptstraße 9','02627 Breitendorf',77,'','Falk','Schneider','WJa1IAPy',20011107154137);
-INSERT INTO users VALUES (35,'Sven.Pietschmann@t-online.de',NULL,'Löbauer Str. 64','Beiersdorf',77,'','Sven','Pietschmann','YnryGAD7',20011107154155);
-INSERT INTO users VALUES (36,'520097125011-0001@t-online.de',NULL,'Nollinger Str. 42','79618 Rheinfelden',77,'0173/5215656','Uwe','Müller','AFPd86ap',20011107160339);
-INSERT INTO users VALUES (37,'Schifferb@web.de',NULL,'Pappelstr. 71b','28199 Bremen',77,'0173-5779873','Bernd','Schiffer','uTkG6ild',20011107160859);
-INSERT INTO users VALUES (38,'marten.kollakowski@t-online.de',NULL,'Carl-von-Ossietzky-Str. 3','29126 oldenburg',77,'0441/7779763','Marten','Kollakowski','ZYR9jY5e',20011107162558);
-INSERT INTO users VALUES (39,'Markus.Klawitter@web.de',NULL,'Hoeltyweg 15','49082 Osnabrueck',77,'','Markus','Klawitter','YlB8yB6R',20011107164020);
-INSERT INTO users VALUES (40,'cordesmartin@gmx.de',NULL,'Feldstrasse 79 a','Bremen',77,'0421 77412','Martin','Cordes','6tV8oqQf',20011107170659);
-INSERT INTO users VALUES (41,'marco.vitali@gmx.ch',NULL,'Buechstrasse 18','5445 Eggenwil',193,'++41-(0)56-6316989','Marco','Vitali','T8HSsnWd',20011107172612);
-INSERT INTO users VALUES (42,'moritzsalinger@web.de',NULL,'Obentrautstraße 64','10963 Berlin',77,'0173 97 95 701','Moritz','Salinger','GrfL4jon',20011107183554);
-INSERT INTO users VALUES (43,'christian@decomain.de',NULL,'Spiegelsbergenweg 104A','Halberstadt',77,'+49 179 2155992','Christian','Decomain','s1Fx40y3',20011107190221);
-INSERT INTO users VALUES (44,'ramona@schrepler.de',NULL,'Fritz-Frey-Str. 11','69121 Heidelberg',77,'06221-418010','Ramona','Schrepler','Lacn2Pyv',20011107195559);
-INSERT INTO users VALUES (45,'ARose@nwn.de',NULL,'Walsroder Str.4','28215 Bremen',77,'','Arne','Rose','PrIw8UyY',20011107201347);
-INSERT INTO users VALUES (46,'hbruhns@ix.urz.uni-heidelberg.de',NULL,'Fritz-Frey-Str. 11','69121 Heidelberg',77,'06221 418012','Hjalmar','Bruhns','zwpY7peL',20011107202024);
-INSERT INTO users VALUES (47,'osprung@gmx.de',NULL,'Meißener Str.9','44139 Dortmund',77,'','Oliver','Sprung','xiXDEu9Y',20011107202741);
-INSERT INTO users VALUES (48,'Fam.Spengler@t-online.de',NULL,'Irlenbornerstr. 14','53783 Eitorf',77,'02243 82178','Stephan','Spengler','okdq89vi',20011107203029);
-INSERT INTO users VALUES (49,'gerhard.hecht@deutschlandweb.de',NULL,'Lerchenweg 16','86492 Egling a.d.Paar',77,'08206 / 903178','Gerhard','Hecht','s4ilkbQb',20011107213252);
-INSERT INTO users VALUES (50,'Ralf.Hachmeister@t-online.de',NULL,'Georg-Viktor-Strasse 32','31812 Bad Pyrmont',77,'05281 960074','Ralf','Hachmeister','Rv5dJqqz',20011107221535);
-INSERT INTO users VALUES (51,'gwaylare@gmx.net',NULL,'Leinestr. 2','Göttingen',77,'','Christoph','Albrecht','4Gp89cDU',20011107223151);
-INSERT INTO users VALUES (52,'chennings@talknet.de',NULL,'Kämmerei 40','27749 Delmenhorst',77,'04221121222','Carsten','Hennings','HrPcHFQF',20011107223240);
-INSERT INTO users VALUES (53,'thorsten.bahr@onlinehome.de',NULL,'Harthauser Straße 76','83043 Bad Aibling',77,'','Thorsten','Bahr','NYD9v561',20011107223249);
-INSERT INTO users VALUES (54,'daniel@boiger.com',NULL,'Rechbergstraße 1','73240 Wendlingen',77,'','Daniel','Boiger','sj3ZmEZ6',20011107234225);
-INSERT INTO users VALUES (55,'alerich2@gmx.net',NULL,'Geschwister-Scholl 6','91058 Erlangen',77,'09131/129670','Ulrich','Hofrichter','xntFLV17',20011108000555);
-INSERT INTO users VALUES (56,'Seppel@prof-seppel.de',NULL,'Bayernallee 7','52066 Aachen',77,'','Sebastian','Oliva','fTDKrAhA',20011108023008);
-INSERT INTO users VALUES (57,'helge.hennings@klinik.uni-regensburg.de',NULL,'Placidusstr. 8','93053 Regensburg',77,'0941/7081875','Helge','Hennings','0saimmtE',20011108095242);
-INSERT INTO users VALUES (58,'andre.lerch@gmx.net',NULL,'Salgaer Str. 4','02694 Malschwitz',77,'','Andre','Lerch','npfnFzsF',20011108124045);
-INSERT INTO users VALUES (59,'Volk-von-Condor@web.de',NULL,'Nadistr. 20','80809 München',77,'08151/4442450 oder 089/3573261','Ralf','Jung','o7tYHQtu',20011114122937);
-INSERT INTO users VALUES (60,'raffa@tzi.de',NULL,'Bachstr. 81','28199 Bremen',77,'0421/393981','Raphael','Sturm','WfzzoBNb',20011108154052);
-INSERT INTO users VALUES (61,'moekon@snafu.de',NULL,'JansaStr. 9','12045 Berlin',77,'030 / 62 72 76 84','Thomas','Konnerth','ufKYGIAu',20011108165022);
-INSERT INTO users VALUES (62,'Morgon@Morgon.de',NULL,'Riegelstr. 58','63762 Großostheim',77,'06026/995153','Sebastian','Weigt','ehzZi6iz',20011108183027);
-INSERT INTO users VALUES (63,'Rupalairpel@gmx.de',NULL,'Thüringer Straße 12','63811 Stockstadt',77,'','Andreas','Müller','rS9gevGv',20011108183035);
-INSERT INTO users VALUES (64,'Oglbi@gmx.de',NULL,'Moritzstr.45','55130 Mainz',77,'','Alexander','Schoehl','6kv1s57y',20011108184527);
-INSERT INTO users VALUES (65,'Xolgrim@gmx.de',NULL,'Hugo-Haelschner-Str.2','53129 Bonn',77,'0228/234588','Thomas','Straßberger','r1qBy4Ot',20011108192159);
-INSERT INTO users VALUES (66,'paladin@bluemail.ch',NULL,'Alpenblickweg 17','3034 Uettligen',193,'','Matthias','Regli','KEbsf2EZ',20011108195229);
-INSERT INTO users VALUES (68,'gzech@t-online.de',NULL,'brendelweg 42','27755 Delmenhorst',77,'0422124921','Guido','Zech','FchaKiVy',20011108215045);
-INSERT INTO users VALUES (69,'stephan-heinrich@gmx.net',NULL,'Schnickenfeld 45a','25497 Prisdorf',77,'04101 782875','Stephan','Heinrich','CaYdwCs9',20011108215639);
-INSERT INTO users VALUES (70,'r.m.glade@talknet.de',NULL,'Finsterwalderstraße 39','01239 Dresden',77,'0172/9147817','Matthias','Glade','a6PSYqFH',20011108222348);
-INSERT INTO users VALUES (71,'vinyambar@waldgoettin.de',NULL,'Wehrweg 2','Kelkheim',77,'','Silvia','Tobies','VOgKOw9A',20011108223528);
-INSERT INTO users VALUES (72,'peter.kraus@web.de',NULL,'Heideweg 94','50196 Kerpen',77,'0227369610','Peter','Kraus','nSK0W8q4',20011108224148);
-INSERT INTO users VALUES (73,'cavendish@planet-interkom.de',NULL,'am gelskamp 16a','32758 detmold',77,'','michael','fisahn','2Z36XPjP',20011108224858);
-INSERT INTO users VALUES (74,'ralphknoll@web.de',NULL,'Neutann 1','88364 Wolfegg',77,'','Ralph','Knoll','lC1dRs9P',20011109065601);
-INSERT INTO users VALUES (75,'klaus@lottmann.de',NULL,'Neuenhainerstrasse 10','60326 Frankfurt',77,'01718596589','Klaus','Lottmann','EfW9d4rM',20011109093531);
-INSERT INTO users VALUES (76,'pampala@gmx.de',NULL,'Grenadierweg 15','26129 Oldenburg',77,'0441/2179804','Pan','Pollack','e9aCJ47w',20011109094120);
-INSERT INTO users VALUES (77,'p.biebow@web.de',NULL,'Friedrichstr. 72','68519 Viernheim',77,'0160 3241994','Peter','Biebow','6TIhSjM2',20011109094157);
-INSERT INTO users VALUES (78,'Wilhelm.Dolle@brainmedia.de',NULL,'Cappeler Strasse 21','35039 Marburg',77,'','Wilhelm','Dolle','fufuxstL',20011109103349);
-INSERT INTO users VALUES (79,'grrummpf@web.de',NULL,'Friedrichstr. 6','53757 Hangelar',77,'','Sebastian','Korte','xhBi2P64',20011109104641);
-INSERT INTO users VALUES (80,'genua@snafu.de',NULL,'Winsstr. 22','10405 Berlin',77,'+49 172 3219138','Steffen','Schermaul','DxC9C8JW',20011109121424);
-INSERT INTO users VALUES (81,'vinyambar@zigulle.de',NULL,'Sonnenstr. 232','44137 Dortmund',77,'','Daniel','Frickemeier','3GkZMurN',20011109130637);
-INSERT INTO users VALUES (82,'alexander.metzner@informatik.uni-oldenburg.de',NULL,'Ahornweg 4','26919 Brake',77,'','Alexander','Metzner','F9GVOC2A',20011109143916);
-INSERT INTO users VALUES (83,'Christian.Wachtendorf@Informatik.Uni-Oldenburg.DE',NULL,'Heiligengeistwall 10','26122 Oldenburg',77,'','Christian','Wachtendorf','Qs9xbr5P',20011109144906);
-INSERT INTO users VALUES (84,'mallig@gmx.net',NULL,'Im Laimacker 32','79249 Merzhausen',77,'','Nicolai','Mallig','CFCsxTiL',20011109185952);
-INSERT INTO users VALUES (85,'Carsten.Kaschube@web.de',NULL,'Sigmaringer Str. 52','72622 Nürtingen',77,'','Carsten','Kaschube','3IOR4tQx',20011109210108);
-INSERT INTO users VALUES (86,'thomas-peter.klug@debitel.net',NULL,'Alter heerweg 35','53123 Bonn',77,'','Thomas-Peter','Klug','LYSt6qXS',20011109214720);
-INSERT INTO users VALUES (87,'ahillenb@ix.urz.uni-heidelberg.de',NULL,'Albert-Überle-Str. 10','69120 Heidelberg',77,'06221 408995','Andreas','Hillenbach','LME6LSjq',20011110115209);
-INSERT INTO users VALUES (88,'Xarkor@gmx.net',NULL,'Howaldtstr. 18','24118 Kiel',77,'0431-6409852','Michael','Jabs','jh5buGu3',20011110120628);
-INSERT INTO users VALUES (89,'feibisch@estec.net',NULL,'Lutherstr. 84','07743 Jena',77,'03641/470096','Frank','Eibisch','KH1u5FEA',20011110130129);
-INSERT INTO users VALUES (90,'ottstadt@sevcon.de',NULL,'Hermann-Löns-Weg 11','22848 Norderstedt',77,'040-512086-12','Willy','Ottstadt','NdYUBNQs',20011110141811);
-INSERT INTO users VALUES (91,'Noilaht@web.de',NULL,'Ifteweg 6','58454 Witten',77,'','Thorsten','Engelbrecht','Hyyycvmt',20011110142138);
-INSERT INTO users VALUES (93,'arthurrefinius@web.de',NULL,'Stolberger Str. 68','Aachen',77,'','Arthur','Refinius','MX2xIKNZ',20011110151659);
-INSERT INTO users VALUES (94,'mina_murry@web.de',NULL,'Stolberger Str. 68','Aachen',77,'','Yvonne','Meis','lx5JAobE',20011110151718);
-INSERT INTO users VALUES (95,'Frank-Michael.Zimmer@T-Online.de',NULL,'Ulmenweg 11','25451 Quickborn',77,'04106 / 66297','Frank-Michael','Zimmer','2RvsbXJB',20011110154508);
-INSERT INTO users VALUES (96,'Holger.Gentemann@t-online.de',NULL,'Arminiusstr. 12','22525 Hamburg',77,'0408500103','Holger','Gentemann','2cWGhMhC',20011110155953);
-INSERT INTO users VALUES (97,'enno@eressea.upb.de',NULL,'Huk Aveny 5b','0287 Oslo',154,'','Enno','Rehling','stkxSiHQ',20011110180250);
-INSERT INTO users VALUES (98,'MJimBeam@aol.com',NULL,'Dresdener Ring 1','Hochheim',77,'','Michael','Simon','UzESKxUm',20011110190227);
-INSERT INTO users VALUES (99,'centime@in-trier.de',NULL,'Henneystr.11','54293 Trier',77,'','Carsten','Pfennig','yC43Eob3',20011110200752);
-INSERT INTO users VALUES (100,'stefan@siev.de',NULL,'Emil-von-Behring Str. 21','35041 Marburg',77,'','Stefan','Sievers','gWiiCQCZ',20011110201606);
-INSERT INTO users VALUES (101,'matthias.frost@cityweb.de',NULL,'Zweibachweg 7','45279 Essen',77,'01605035882','Matthias','Frost','QQ9wHAAu',20011110204447);
-INSERT INTO users VALUES (102,'gandalf@informatik.uni-bremen.de',NULL,'Dresdener Str. 1a','28844 Weyhe (bei Bremen)',77,'04203/810797','Cedrik','Duval','WDrEQTW2',20011111111333);
-INSERT INTO users VALUES (103,'aramesvs@t-online.de',NULL,'Hauptstraße 48','Herzberg',77,'05521 2809','Frank','Nolte','4Ydo3fTT',20011111112533);
-INSERT INTO users VALUES (104,'micha@lst.de',NULL,'Naegelsbacherstr. 49c','91052 Erlangen',77,'+49 9131 7192-325','Micha','Istine','kNgy9al3',20011111135542);
-INSERT INTO users VALUES (105,'nilshorstmann@web.de',NULL,'Schwalbenstr. 4','28816 Stuhr',77,'','Nils','Horstmann','1ppXJrWV',20011111141125);
-INSERT INTO users VALUES (106,'Feacor@web.de',NULL,'Nestorstr. 15','10709 Berlin',77,'','Daniel','Kohl','h48VSRLD',20011111144452);
-INSERT INTO users VALUES (107,'boris_schroeder@web.de',NULL,'Kriegerstr. 42','30161 Hannover',77,'05111693916','Boris','Schröder','d3LORqkj',20011111161143);
-INSERT INTO users VALUES (108,'ectorhga@linux.zrz.tu-berlin.de',NULL,'Nestorstr. 15','Berlin',77,'','Alexander','Sahm','vjdfhtOQ',20011111161623);
-INSERT INTO users VALUES (109,'520020001929-0001@T-Online.de',NULL,'Ascher Str. 22','63477 Maintal',77,'','Nick','Sauter','u8rzSQAq',20011111162902);
-INSERT INTO users VALUES (110,'joha_puck@web.de',NULL,'Kastanienstraße 13','24114 Kiel',77,'0431/6686648','Markus Johannes','Puck','ajWhzD34',20011111164353);
-INSERT INTO users VALUES (111,'meini@einsteinfreun.de',NULL,'Auf der Schulenburg 22','33378 Rheda',77,'','Sebastian','Meinhardt','NkFXheZM',20011111184904);
-INSERT INTO users VALUES (112,'Evewan@web.de',NULL,'Belßstraße 81','Berlin',77,'','Thomas','Leue','uxUiWIxE',20011111194928);
-INSERT INTO users VALUES (114,'paul.fuehring@gmx.net',NULL,'Müllerstr. 30','13353 Berlin',77,'','Paul','Führing','OK2sRkAr',20011111202214);
-INSERT INTO users VALUES (115,'Dragoon2913@t-online.de',NULL,'Winkelstr. 16','Herzberg',77,'','Mark','Szemeitat','FmYwtR0G',20011111214036);
-INSERT INTO users VALUES (116,'MMalte@directbox.com',NULL,'Hohenloherstr 39 A','70435 Stuttgart',77,'0173/5938300','Malte','Möller','mKrRMgqo',20011111225156);
-INSERT INTO users VALUES (117,'andreas.hallmann@gecits-eu.com',NULL,'Gröpelinger Heerstr. 301','28239 Bremen',77,'0421-6166311','Andreas','Hallmann','dPjRKZs2',20011112062521);
-INSERT INTO users VALUES (118,'vinyambar@zerofoks.net',NULL,'Taubenstraße 18','28203 Bremen',77,'0421 7940905','Ferdinand','Steiger','9zxMjWDp',20011112081725);
-INSERT INTO users VALUES (119,'gunty@talknet.de',NULL,'Nithackstr. 4','D-10585 Berlin',77,'(030) 347 02 758','Günther','Martinez Dreyer','vLN79XDJ',20011112101441);
-INSERT INTO users VALUES (120,'Karsten.Meier@stim.de',NULL,'Südekumzeile 7a','13591 Berlin',77,'','Karsten','Meier','tdP0FoVr',20011112102722);
-INSERT INTO users VALUES (121,'michael.tuscher@web.de',NULL,'Bussmannsfeld 109','44805 Bochum',77,'','Michael','Tuscher','eBJnJmsR',20011112102904);
-INSERT INTO users VALUES (122,'daniel@boiger.com',NULL,'Rechbergstr. 1','Wendlingen',77,'','Daniel','Boiger','znUOJmZ0',20011112102923);
-INSERT INTO users VALUES (123,'jb559755@rcs.urz.tu-dresden.de',NULL,'Gubener Str. 36','01237 Dresden',77,'0172/3515486','Jens','Bergmann','zxOoiau9',20011112121046);
-INSERT INTO users VALUES (124,'phelan@phelan-net.de',NULL,'Klaushager Weg 17','13467 Berlin',77,'','Rainer','Schüler','uDtnGTSE',20011112141432);
-INSERT INTO users VALUES (125,'Roger.Frehoff@t-online.de',NULL,'Bergheimer Weg 25','Gerlingen',77,'','Roger','Frehoff','FVv0gEJL',20011112142906);
-INSERT INTO users VALUES (126,'Alexander.Miseler@SilverStyle.de',NULL,'Weidenweg 47','10249 Berlin',77,'','Alexander','Miseler','OC6kYMIS',20011112154757);
-INSERT INTO users VALUES (127,'falen@freenet.de',NULL,'Hattingerstr.241','44795 Bochum',77,'','Torsten','Felske','CqrtmkIt',20011112165628);
-INSERT INTO users VALUES (128,'jb559755@rcs.urz.tu-dresden.de',NULL,'Gubener Str. 36','01237 Dresden',77,'0172/3515486','Jens','Bergmann','UINiqkC1',20011112172156);
-INSERT INTO users VALUES (129,'St.Ziegler@gmx.de',NULL,'Hirschgraben 24','Aachen',77,'','Stefan','Ziegler','nxQSXfF6',20011112184027);
-INSERT INTO users VALUES (130,'tach.uli@t-online.de',NULL,'Limbeckstr.1b','44894 Bochum',77,'0234/261526','Ulrich','Meise','pPFz3COy',20011112204010);
-INSERT INTO users VALUES (131,'cyrion_@web.de',NULL,'Bachstr. 81','28199 Bremen',77,'','Christian','Büthe','vwmvxxrH',20011112225303);
-INSERT INTO users VALUES (132,'torsten@steigner.de',NULL,'Alleestraße 4','66882 Huetschenhausen',77,'','Torsten','Steigner','eZxwKddw',20011113005654);
-INSERT INTO users VALUES (133,'esclarmunde@gmx.de',NULL,'Kastanienstr.13','24114 Kiel',77,'0431/6794667','Jörn','Gräbert','meXNQnPx',20011113013016);
-INSERT INTO users VALUES (134,'harryrat@gmx.de',NULL,'Kastanienweg 13','52074 Aachen',77,'0241-81806','Harald','Radke','Pbzjwagv',20011113085313);
-INSERT INTO users VALUES (135,'stefan@hoeffling.de',NULL,'Franziskanerstr. 1','56154 Boppard',77,'06742/82512','Stefan','Hoeffling','HLtorF5o',20011113145256);
-INSERT INTO users VALUES (136,'esclarmunde@gmx.de',NULL,'Kastanienstr.13','24114 Kiel',77,'0431/6794667','Jörn','Gräbert','0HmvpMSi',20011113151218);
-INSERT INTO users VALUES (137,'Frank.Adler@gmx.net',NULL,'Gertrudisweg 5','Euskirchen',77,'','Frank','Adler','6fWjD6Ib',20011113230300);
-INSERT INTO users VALUES (138,'jens.otte@gmxpro.de',NULL,'Am Suedhang 5','Glinde',77,'+494075665561','Jens','Otte','m7omFMzP',20011114002043);
-INSERT INTO users VALUES (139,'martin@hershoff.de',NULL,'Abtsbrede 47','33098 Paderborn',77,'','Martin','Hershoff','UTJXiCMw',20011114110237);
-INSERT INTO users VALUES (140,'n.werhahn@t-online.de',NULL,'kohlenweg 10','Baden Baden',76534,'01796972416','nils','werhahn','ZfBmZlMe',20011114111939);
-INSERT INTO users VALUES (141,'elvis@eressea-pbem.de',NULL,'Rockaway','Memphis',77,'','Elvis','The King','Z7VXtjiX',20011114162334);
-INSERT INTO users VALUES (142,'zdomotor@axelero.hu',NULL,'Liszt Ferenc 3','H-2045 Törökbálint',93,'0036 23 336 385','Zoltán','Dömötör','p57pnZGf',20011116221701);
-INSERT INTO users VALUES (143,'faber@kawo1.rwth-aachen.de',NULL,'Kastanienweg 4 / 2225','52074 Aachen',77,'0241/9810789','Michael','Ziegler','aDP4eoC0',20011118204013);
-
diff --git a/scripts/register/wait-reset.py b/scripts/register/wait-reset.py
deleted file mode 100755
index ebef9a734..000000000
--- a/scripts/register/wait-reset.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/env python
-
-#
-# reset the waiting list after ZAT.
-# before running this script, be sure to apply the patchfile generated by the eressea-server to
-# mark users with new accounts as ACTIVE.
-# * Will mark WAITING users as EXPIRED, removig them from the waitng list.
-# * Will mark CONFIRMED users as WAITING, and send them another mail.
-
-import MySQLdb
-import string
-import re
-import sys
-import os
-import smtplib
-
-dbname=sys.argv[1]
-date=sys.argv[2]
-From='accounts@eressea-pbem.de'
-smtpserver='localhost'
-server=smtplib.SMTP(smtpserver)
-patchdir='/home/eressea/eressea-rsync'
-game_id=0
-
-db=MySQLdb.connect(db=dbname)
-cursor=db.cursor()
-cursor.execute("select name, patch from games where id="+str(game_id))
-game, patch = cursor.fetchone()
-
-MailTemplate="templates/register.mail."+string.lower(game)
-
-def Patch():
- global patch
-
- print "Auswertung für " + game + " Patch Level " + str(int(patch))
- while os.access(patchdir+'/patch-'+str(int(patch+1))+'.sql', os.F_OK):
- patch=patch+1
- print " Patching to level "+str(patch)
- os.system('mysql ' + dbname + ' < ' + patchdir+'/patch-'+str(int(patch))+'.sql')
- cursor.execute('update games set patch='+str(int(patch))+' where id='+str(game_id))
- return
-
-def Send(email, custid, firstname, password, position, locale):
- TemplateHandle = open(MailTemplate+"."+locale, "r") # open in read only mode
- # read the entire file as a string
- TemplateInput = TemplateHandle.read()
- TemplateHandle.close() # close the file
-
- SubResult = re.subn("", firstname, TemplateInput)
- SubResult = re.subn("", game, SubResult[0])
- SubResult = re.subn("", password, SubResult[0])
- SubResult = re.subn("", str(int(position)), SubResult[0])
- SubResult = re.subn("", str(int(custid)), SubResult[0])
-
- Msg="From: "+From+"\nTo: "+email+"\nSubject: Eressea Anmeldung\n\n"
- Msg=Msg+SubResult[0]
- server.sendmail(From, email, Msg)
- return
-
-Patch()
-# remove all illegal and banned users:
-users = cursor.execute("SELECT s.id from users u, subscriptions s where u.id=s.user and u.status in ('BANNED', 'ILLEGAL')")
-update=db.cursor()
-while users:
- users=users-1
- sid = cursor.fetchone()[0]
- update.execute("UPDATE subscriptions set status='EXPIRED' WHERE id="+str(int(sid)))
-
-# espire all users without confirmation. reset waiting list.
-cursor.execute("update subscriptions set status='EXPIRED' where TO_DAYS(updated)2:
- dryrun=1
-price=1.25
-warnahead=4
-cancelafter=1
-db=MySQLdb.connect(db=dbname)
-cursor=db.cursor()
-server=smtplib.SMTP('localhost')
-print "connected to SMTP"
-users = cursor.execute("select users.email, users.id, count(subscriptions.game) from users, subscriptions, games where users.id=subscriptions.user and subscriptions.game=games.id and users.id!=0 and games.status='RUNNING' GROUP BY users.id")
-while users > 0:
- users=users-1
- email, uid, games = cursor.fetchone()
- if games==0:
- continue
- c2 = db.cursor()
- t = c2.execute("select sum(balance) from transactions where user="+str(int(uid)))
- if t==0:
- balance=0.0
- else:
- balance = c2.fetchone()[0]
- Msg=None
- if balance <= games*warnahead*price:
- Msg = ("From: Vinyambar Buchhaltung <"+From+">\nTo: "+email+"\n")
- if balance < -games*cancelafter*price:
- Msg=Msg+"Subject: Vinyambar Abmeldung Kunde "+str(int(uid))+".\n\n"
- Msg = Msg+("Nachdem Dein Konto bei uns im Minus ist, haben wir deine\n"+
- "Anmeldung bei Vinyambar gekündigt, und die Partei(en) der Parteibörse\n"+
- "zugeführt.\n")
- print "CANCEL: "+email+", uid="+str(int(uid))+", balance="+str(balance)+", games="+str(int(games))
- if dryrun==0:
- c2.execute("UPDATE subscriptions set status='CANCELLED' where user="+str(int(uid)))
- else:
- print "WARNING: "+email+", uid="+str(int(uid))+", balance="+str(balance)+", games="+str(int(games))
- Msg = Msg+"Subject: WARNUNG - Vinyambar Kontostand Kunde "+str(int(uid))+"\n\n"
- Msg = Msg+("Dein Vinyambar Kontostand reicht nicht mehr aus, um die kommenden "+str(warnahead)+"\n"+
- "Wochen zu bezahlen. Bitte mache baldmöglichst eine neue Überweisung\n"
- "auf das Vinyambar-Konto.\n\n"+
- "Kundennummer: "+str(uid)+"\n"+
- "Kontostand: "+str(balance)+" EUR\n"+
- "\n"+
- "Unser Konto: Katja Zedel\n"+
- "Kontonummer 1251 886 106\n"+
- "BLZ 500 502 01 (Frankfurter Sparkasse)\n")
-
- if (Msg!=None) and dryrun==0:
- try:
- server.sendmail(From, email, Msg)
- except:
- print "Could not send confirmation to "+email
- print "Exception is:", sys.exc_type, ":", sys.exc_value
-
diff --git a/scripts/register/zat.py b/scripts/register/zat.py
deleted file mode 100755
index 0b38b1c24..000000000
--- a/scripts/register/zat.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/env python
-import MySQLdb
-import sys
-import os
-
-dbname=sys.argv[1]
-gid=int(sys.argv[2])
-date=sys.argv[3]
-price=1.25
-db=MySQLdb.connect(db=dbname)
-patchdir='/home/eressea/vinyambar-rsync/vin'+str(gid)+'/data'
-
-cursor=db.cursor()
-
-def SetUser(cursor, num, newuser):
- update = db.cursor()
- while num:
- num = num-1
- uid, faction = cursor.fetchone()
- update.execute("insert into transfers (faction, game, src,dst) values ('"+faction+"', "+str(gid)+", "+str(int(uid))+", 0)")
- update.execute("update subscriptions set user="+str(newuser)+" where game="+str(gid)+" and faction='"+faction+"'")
-
-
-k = cursor.execute('select name, patch from games where id='+str(gid))
-if k==0:
- print "Unbekanntes Spiel"
-
-name, patch = cursor.fetchone()
-
-os.system("mysqldump vinyambar > backup-vinyambar-"+str(int(patch))+".sql")
-
-k = cursor.execute("SELECT max(lastturn) from subscriptions")
-lastturn = int(cursor.fetchone()[0])
-
-print "Auswertung für " + name + " Patch Level " + str(int(patch)) + ", Runde "+str(lastturn)
-while os.access(patchdir+'/patch-'+str(int(patch+1))+'.sql', os.F_OK):
- patch=patch+1
- print " Patching to level "+str(patch)
- os.system('mysql ' + dbname + ' < ' + patchdir+'/patch-'+str(int(patch))+'.sql')
- cursor.execute('update games set patch='+str(int(patch))+' where id='+str(gid))
-
-k = cursor.execute("select user, faction from subscriptions where game="+str(gid)+" and status='TRANSFERED' and user!=0 and updated<'"+date+"'")
-print "Removing "+str(int(k))+" transfered subscriptions."
-SetUser(cursor, int(k), 0)
-
-k = cursor.execute("select user, faction from subscriptions where game="+str(gid)+" and status='CANCELLED' and user!=0 and updated<'"+date+"'")
-print "Removing "+str(int(k))+" cancelled subscriptions."
-SetUser(cursor, int(k), 0)
-
-k = cursor.execute("select user, faction from subscriptions where game="+str(gid)+" and user!=0 and status='DEAD'")
-print "Removing "+str(int(k))+" dead subscriptions."
-
-k = cursor.execute("UPDATE subscriptions SET status='CANCELLED' where game="+str(gid)+" and status='ACTIVE' and lastturn+3<="+str(lastturn))
-if k:
- print "Cancelling subscriptions with 3+ NMRs."
-
-cursor.execute("SELECT count(*) from transactions where date='"+date+"' and description='ZAT-"+str(gid)+"'")
-k = cursor.fetchone()[0]
-if k==0:
- k = cursor.execute("SELECT users.id FROM users, subscriptions WHERE users.id=subscriptions.user and subscriptions.status='ACTIVE' and subscriptions.game="+str(gid))
- print "Billing "+str(int(k))+" users."
- while k!=0:
- k=k-1
- user = int(cursor.fetchone()[0])
- update=db.cursor()
- update.execute("INSERT INTO transactions (user,date,balance,description) VALUES ("+str(user)+", '"+date+"', -"+str(price)+", 'ZAT-"+str(gid)+"')")
-else:
- print "ERROR: ZAT for game "+str(gid)+" has already been done."
diff --git a/scripts/templates/eressea.html b/scripts/templates/eressea.html
deleted file mode 100644
index 7dd87d963..000000000
--- a/scripts/templates/eressea.html
+++ /dev/null
@@ -1,53 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-Eressea PBEM
-
-
-
-
-
-
-
-
diff --git a/scripts/templates/register.mail.eressea.de b/scripts/templates/register.mail.eressea.de
deleted file mode 100644
index ab9c4e1d3..000000000
--- a/scripts/templates/register.mail.eressea.de
+++ /dev/null
@@ -1,22 +0,0 @@
-Hallo ,
-
-Du stehst mit deiner Anmeldung bei auf der Warteliste für neue Parteien
-derzeit an Position . Um Deine Anmeldung zu bestätigen, gehe bitte
-auf die folgende Webseite, und gib dort zur Bestätigung deine Kundennummer
-und den Bestätigungsschlüssel ein.
-
- http://eressea-pbem.de/de/confirm.html
- Kundennummer:
- Schlüssel:
-
-Um sicherzustellen, das nur interessierte Spieler in der Warteliste sind,
-muß diese Prozedur einmal wöchentlich wiederholt werden. Du bekommst daher
-wöchentlich eine Erinnerungsmail, in der Du auch deine aktuelle Position in
-der Warteliste sehen kannst.
-
-Solltest Du den Schlüssel bis Sonntag früh nicht eingegeben haben, wird
-deine Anmeldung aus der Warteliste entfernt, und Du bekommst keine weiteren
-Mails von uns.
-
-
-Das Eressea-Team
diff --git a/scripts/templates/register.mail.eressea.en b/scripts/templates/register.mail.eressea.en
deleted file mode 100644
index 41759f740..000000000
--- a/scripts/templates/register.mail.eressea.en
+++ /dev/null
@@ -1,20 +0,0 @@
-Hello ,
-
-You are now entered into the waiting list of , at position .
-To confirm your subscription, please go to the following URL and enter your
-Customer-ID and confirmation key.
-
- http://eressea-pbem.de/en/confirm.html
- Customer ID:
- Key:
-
-To make sure that only those players interested in playing remain on the
-list, you need to repeat this procedure once every week. We will send you this
-reminder by mail, in which you'll also see your updated position on the
-waiting list.
-
-If you do not enter the key before sunday morning 9:00 CET, your
-registration will be considered cancelled, and you will receive no further
-email from us.
-
-The Eressea Team
diff --git a/scripts/templates/register.mail.tutorial.de b/scripts/templates/register.mail.tutorial.de
deleted file mode 100644
index 963d7c76b..000000000
--- a/scripts/templates/register.mail.tutorial.de
+++ /dev/null
@@ -1,21 +0,0 @@
-Hallo ,
-
-Als bisher nicht registrierter Eressea-Spieler haben wir Dich zu einer 5
-Runden dauernden Schnupperpartie eingetragen. Dieses Tutorial gibt Dir die
-Chance, deine Anfangsstrategie auszuprobieren und festzustellen, ob Du die
-Regeln auch wirklich verstanden hast.
-
-Nachdem Du 5 Runden im Tutorial gespielt hast, werden wir deinen Account für
-das richtige Eressea-Spiel freischalten. Das hat für alle Beteiligten auch
-den Vorteil, das nur solche Spieler teilnehmen, die über Grundkenntnisse der
-Regeln verfügen, und wissen, worum es bei Eressea geht.
-
-Um Deine Anmeldung zu bestätigen, gehe bitte auf die folgende Webseite, und
-gib dort zur Bestätigung deine Kundennummer und den Bestätigungsschlüssel
-ein.
-
- http://eressea-pbem.de/de/confirm.html
- Kundennummer:
- Schlüssel:
-
-Das Eressea-Team
diff --git a/scripts/templates/register.mail.tutorial.en b/scripts/templates/register.mail.tutorial.en
deleted file mode 100644
index 4e6f84b98..000000000
--- a/scripts/templates/register.mail.tutorial.en
+++ /dev/null
@@ -1,19 +0,0 @@
-Hello ,
-
-as a new player, you have been entered into the Eressea tutorial game. By
-letting you play the tutorial first, we're giving you the chance to test
-your knowledge of the rules and exxperiment for a few turns befor the actual
-game starts - consider this a way to test your initial strategy. Better to
-make mistakes now than later, right?
-
-Once you finish 5 turns in this game (which will have a turn every 2 days),
-your Account will be upgraded, allowing you to subscribe to Eressea.
-
-To confirm this subscription, please go to the following URL and enter your
-new Customer-ID and confirmation key.
-
- http://eressea-pbem.de/en/confirm.html
- Customer ID:
- Key:
-
-The Eressea Team
diff --git a/scripts/templates/vinyambar-register.mail.de b/scripts/templates/vinyambar-register.mail.de
deleted file mode 100644
index 193947501..000000000
--- a/scripts/templates/vinyambar-register.mail.de
+++ /dev/null
@@ -1,22 +0,0 @@
-Hallo ,
-
-Deine Vinyambar-Anmeldung ist beinahe komplett. Um Deine Anmeldung zu bestätigen,
-gehe bitte auf die folgende Webseite, und gib dort zur Bestätigung deine
-Kundennummer und das Kundenpasswort ein.
-
- http://www.vinyambar.de/accounts.shtml
- Kundennummer:
- Kundenpasswort:
-
-Bitte bewahre diese Mail sorgfältig auf, da Du deine Kundennummer und das
-Passwort für das Spiel benötigst. Solltest Du noch Fragen zu Deiner
-Anmeldung haben, wende Dich bitte an accounts@vinyambar.de.
-
-Die Kundennummer gib bitte bei der Überweisung der Spielgebühren an.
-Unsere Kontoinformationen lauten:
-
- Katja Zedel
- Kontonummer 1251 886 106
- BLZ 500 502 01 (Frankfurter Sparkasse)
-
-Das Vinyambar-Team
diff --git a/scripts/templates/vinyambar-register.mail.en b/scripts/templates/vinyambar-register.mail.en
deleted file mode 100644
index 193947501..000000000
--- a/scripts/templates/vinyambar-register.mail.en
+++ /dev/null
@@ -1,22 +0,0 @@
-Hallo ,
-
-Deine Vinyambar-Anmeldung ist beinahe komplett. Um Deine Anmeldung zu bestätigen,
-gehe bitte auf die folgende Webseite, und gib dort zur Bestätigung deine
-Kundennummer und das Kundenpasswort ein.
-
- http://www.vinyambar.de/accounts.shtml
- Kundennummer:
- Kundenpasswort:
-
-Bitte bewahre diese Mail sorgfältig auf, da Du deine Kundennummer und das
-Passwort für das Spiel benötigst. Solltest Du noch Fragen zu Deiner
-Anmeldung haben, wende Dich bitte an accounts@vinyambar.de.
-
-Die Kundennummer gib bitte bei der Überweisung der Spielgebühren an.
-Unsere Kontoinformationen lauten:
-
- Katja Zedel
- Kontonummer 1251 886 106
- BLZ 500 502 01 (Frankfurter Sparkasse)
-
-Das Vinyambar-Team
diff --git a/scripts/templates/vinyambar.html b/scripts/templates/vinyambar.html
deleted file mode 100644
index 82c709c2a..000000000
--- a/scripts/templates/vinyambar.html
+++ /dev/null
@@ -1,65 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-Vinyambar PBEM
-
-
-
-
-
-
-
-
diff --git a/src/Jamrules b/src/Jamrules
deleted file mode 100644
index 6efb07d89..000000000
--- a/src/Jamrules
+++ /dev/null
@@ -1,205 +0,0 @@
-C++ = g++ ;
-CC = gcc ;
-LINK = gcc ;
-
-MSPACES = 1 ;
-
-# BINDINGS can only be TOLUA (we dropped both NONE and LUABIND at some point)
-if ! $(BINDINGS) {
- BINDINGS = TOLUA ;
-}
-
-# BUILDTYPE can be REGULAR or UNITY
-if ! $(BUILDTYPE) {
- BUILDTYPE = UNITY ;
-}
-
-if $(BINDINGS) = TOLUA {
- CCFLAGS += -DBINDINGS_TOLUA ;
- C++FLAGS += -DBINDINGS_TOLUA ;
-}
-
-if ! $(LUA_VERSION) {
- LUA_VERSION = 5.1 ;
-}
-
-if ! $(HAVE_LUA) {
- HAVE_LUA = 1 ;
-}
-
-if ! $(CPU) {
- CPU = prescott ;
- ARCH = -march=$(CPU) -mmmx -mieee-fp ;
- ARCH += -mtune=$(CPU) ;
-}
-
-if $(DISTCC_HOSTS) {
- DISTCC = 1 ;
-}
-
-if $(DISTCC) {
- CC = distcc $(CC) ;
- C++ = distcc $(C++) ;
- Echo Compiling with distcc ;
-}
-
-if ! $(CCACHE_DIR) {
-} else {
- CC = ccache $(CC) ;
- C++ = ccache $(C++) ;
- Echo Compiling with ccache ;
-}
-
-if $(DMALLOC) {
- Echo Compiling with dmalloc ;
- CCFLAGS += -DUSE_DMALLOC ;
- C++FLAGS += -DUSE_DMALLOC ;
- LINKFLAGS += -ldmalloc ;
-}
-
-if $(COVERAGE) = 1 {
- Echo Compiling with gcov info ;
- CCFLAGS += -fprofile-arcs -ftest-coverage ;
- C++FLAGS += -fprofile-arcs -ftest-coverage ;
- LINKFLAGS += -fprofile-arcs -ftest-coverage ;
-}
-
-if $(PROFILE) = 1 {
- Echo Compiling with profiler ;
- CCFLAGS += -pg -ggdb ;
- LINKFLAGS += -pg -ggdb ;
-}
-
-CCFLAGS += -Wall -Werror -Wno-unknown-pragmas -Wstrict-prototypes
- -Wpointer-arith -Wno-char-subscripts ;
-
-CCFLAGS on foo += -Wwrite-strings
- -Wundef
- -Wstrict-prototypes
- -Werror-implicit-function-declaration
- -Wno-char-subscripts
- -Wpointer-arith
-# -Wshadow
-# -Wcast-qual
- -Wcast-align
-# -Wconversion
-# -Wunreachable-code
- -Werror
- ;
-
-if $(LOCAL_USR) {
- XMLHDRS = $(LOCAL_USR)/include/libxml2 ;
- C++FLAGS += -I$(LOCAL_USR)/include ;
- CFLAGS += -I$(LOCAL_USR)/include ;
- LINKLIBS += -L$(LOCAL_USR)/lib ;
-} else {
- XMLHDRS = /usr/include/libxml2 ;
-}
-
-rule iconv
-{
- if $(LINK_ICONV) {
- LINKLIBS on $(<) += -liconv ;
- }
-}
-
-rule zlib
-{
- LINKLIBS on $(<) += -lz ;
-}
-
-rule liblua
-{
- if $(LUA_VERSION) = 5.1 {
- LINKLIBS on $(<) += -llua5.1 ;
- } else {
- LINKLIBS on $(<) += -llua50 -llualib50 ;
- }
-}
-
-rule libxml2
-{
- LINKLIBS on $(<) += -lxml2 ;
-}
-
-rule libtolua
-{
- LINKLIBS on $(<) += -ltolua ;
-}
-
-rule libcurses
-{
- LINKLIBS on $(<) += -lncurses ;
-}
-
-rule libmcheck
-{
- if $(DEBUG) = 1 {
- LINKLIBS on $(<) += -lmcheck ;
- }
-}
-
-rule UsingLua
-{
- if $(LUA_VERSION) = 5.1 {
- SubDirHdrs /usr/include/lua5.1 ;
- } else {
- SubDirHdrs /usr/include/lua50 ;
- }
-}
-
-rule TargetDirectory
-{
- # Now set up SEARCH_SOURCE, LOCATE_TARGET, SOURCE_GRIST
- # These can be reset if needed. For example, if the source
- # directory should not hold object files, LOCATE_TARGET can
- # subsequently be redefined.
-
- local path = [ FDirName $(SUBDIR) $(TARGET_PREFIX) ] ;
- SEARCH_SOURCE = $(SUBDIR) ;
- LOCATE_SOURCE = $(ALL_LOCATE_TARGET) $(path) ;
- LOCATE_TARGET = $(ALL_LOCATE_TARGET) $(path) ;
- SOURCE_GRIST = $(path) ;
- if $(DEBUG) = 1 {
- SubDirCcFlags -ggdb ;
- SubDirC++Flags -ggdb ;
- OPTIM = -O0 -ffloat-store ;
- }
- else {
- SubDirCcFlags -DNDEBUG ;
- SubDirC++Flags -DNDEBUG ;
- OPTIM = -Os -ffloat-store ;
- }
- SubDirCcFlags $(ARCH) ;
- SubDirC++Flags $(ARCH) ;
-}
-
-if ! $(DEBUG) {
- ECHO Assuming DEBUG=1 ;
- DEBUG = 1 ;
-}
-
-if $(MSPACES) {
- CCFLAGS += -DMSPACES -DDL_DEBUG=0 ;
- C++FLAGS += -DMSPACES -DDL_DEBUG=0 ;
-}
-
-if $(WITHOUT_LUA) {
- ECHO Compiling without LUA ;
-}
-
-if $(DEBUG) = 0 {
- TARGET_PREFIX = Release ;
-}
-else {
- TARGET_PREFIX = Debug ;
-}
-if $(PROFILE) = 1 {
- TARGET_PREFIX = Profile ;
-}
-if $(COVERAGE) = 1 {
- TARGET_PREFIX = Coverage ;
-}
-
-
-
diff --git a/src/basic/basic.sln b/src/basic/basic.sln
deleted file mode 100644
index 47c0dff4f..000000000
--- a/src/basic/basic.sln
+++ /dev/null
@@ -1,53 +0,0 @@
-Microsoft Visual Studio Solution File, Format Version 9.00
-# Visual Studio 2005
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kernel", "..\src\kernel.vcproj", "{6F104C0A-DDF5-A34B-A89C-0DC278DCEF6D}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gamecode", "..\src\gamecode.vcproj", "{1E8BFF9E-3044-0742-992F-C5765B80FE65}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "util", "..\src\util.vcproj", "{F70CFB27-8A2F-E447-B452-4E1C590EDA6D}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lua-bindings", "..\src\lua-bindings.vcproj", "{75501170-51C2-E641-BA8B-EDC008184192}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "external", "..\external\external.vcproj", "{F9AE4586-8F65-486B-9666-744839E40A54}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "amalgamation-basic", "basic.vcproj", "{4A17DAEE-2261-4E2C-96F6-BA4132A09551}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tests", "..\src\tests.vcproj", "{228B8781-480F-4608-BA14-1EB82581EADE}"
-EndProject
-Global
- GlobalSection(SubversionScc) = preSolution
- Svn-Managed = True
- Manager = AnkhSVN - Subversion Support for Visual Studio
- EndGlobalSection
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Win32 = Debug|Win32
- Release|Win32 = Release|Win32
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {6F104C0A-DDF5-A34B-A89C-0DC278DCEF6D}.Debug|Win32.ActiveCfg = Debug|Win32
- {6F104C0A-DDF5-A34B-A89C-0DC278DCEF6D}.Release|Win32.ActiveCfg = Release|Win32
- {6F104C0A-DDF5-A34B-A89C-0DC278DCEF6D}.Release|Win32.Build.0 = Release|Win32
- {1E8BFF9E-3044-0742-992F-C5765B80FE65}.Debug|Win32.ActiveCfg = Debug|Win32
- {1E8BFF9E-3044-0742-992F-C5765B80FE65}.Release|Win32.ActiveCfg = Release|Win32
- {1E8BFF9E-3044-0742-992F-C5765B80FE65}.Release|Win32.Build.0 = Release|Win32
- {F70CFB27-8A2F-E447-B452-4E1C590EDA6D}.Debug|Win32.ActiveCfg = Debug|Win32
- {F70CFB27-8A2F-E447-B452-4E1C590EDA6D}.Release|Win32.ActiveCfg = Release|Win32
- {F70CFB27-8A2F-E447-B452-4E1C590EDA6D}.Release|Win32.Build.0 = Release|Win32
- {75501170-51C2-E641-BA8B-EDC008184192}.Debug|Win32.ActiveCfg = Debug|Win32
- {75501170-51C2-E641-BA8B-EDC008184192}.Release|Win32.ActiveCfg = Release|Win32
- {75501170-51C2-E641-BA8B-EDC008184192}.Release|Win32.Build.0 = Release|Win32
- {F9AE4586-8F65-486B-9666-744839E40A54}.Debug|Win32.ActiveCfg = Debug|Win32
- {F9AE4586-8F65-486B-9666-744839E40A54}.Release|Win32.ActiveCfg = Release|Win32
- {F9AE4586-8F65-486B-9666-744839E40A54}.Release|Win32.Build.0 = Release|Win32
- {4A17DAEE-2261-4E2C-96F6-BA4132A09551}.Debug|Win32.ActiveCfg = Debug|Win32
- {4A17DAEE-2261-4E2C-96F6-BA4132A09551}.Debug|Win32.Build.0 = Debug|Win32
- {4A17DAEE-2261-4E2C-96F6-BA4132A09551}.Release|Win32.ActiveCfg = Release|Win32
- {228B8781-480F-4608-BA14-1EB82581EADE}.Debug|Win32.ActiveCfg = Debug|Win32
- {228B8781-480F-4608-BA14-1EB82581EADE}.Debug|Win32.Build.0 = Debug|Win32
- {228B8781-480F-4608-BA14-1EB82581EADE}.Release|Win32.ActiveCfg = Release|Win32
- {228B8781-480F-4608-BA14-1EB82581EADE}.Release|Win32.Build.0 = Release|Win32
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
-EndGlobal
diff --git a/src/basic/basic.vcproj b/src/basic/basic.vcproj
deleted file mode 100644
index a549145cd..000000000
--- a/src/basic/basic.vcproj
+++ /dev/null
@@ -1,280 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/res/armor.xml b/src/basic/res/armor.xml
deleted file mode 100644
index f24ddcd35..000000000
--- a/src/basic/res/armor.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/res/buildings.xml b/src/basic/res/buildings.xml
deleted file mode 100644
index 3d128a12c..000000000
--- a/src/basic/res/buildings.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
diff --git a/src/basic/res/catalog-basic.xml b/src/basic/res/catalog-basic.xml
deleted file mode 100644
index 8eb4603a3..000000000
--- a/src/basic/res/catalog-basic.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
diff --git a/src/basic/res/config-basic.xml b/src/basic/res/config-basic.xml
deleted file mode 100644
index 9ff9019fd..000000000
--- a/src/basic/res/config-basic.xml
+++ /dev/null
@@ -1,102 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- eressea-server@example.com
- eressea-server@example.com
-
-
- Bitte denke daran, deine Befehle mit dem Betreff
- ERESSEA BEFEHLE an eressea-server@example.com zu senden.
- Remember to send your orders to
- eressea-server@example.com with the subject ERESSEA ORDERS.
-
-
- ERESSEA BEFEHLE
- ERESSEA ORDERS
-
-
- ARBEITEN
- WORK
-
-
-
diff --git a/src/basic/res/items.xml b/src/basic/res/items.xml
deleted file mode 100644
index e8fa7246a..000000000
--- a/src/basic/res/items.xml
+++ /dev/null
@@ -1,3 +0,0 @@
-
-
-
diff --git a/src/basic/res/races.xml b/src/basic/res/races.xml
deleted file mode 100644
index 09ce2212e..000000000
--- a/src/basic/res/races.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/res/races/aquarian.xml b/src/basic/res/races/aquarian.xml
deleted file mode 100644
index 0bd11c8c3..000000000
--- a/src/basic/res/races/aquarian.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/res/races/cat.xml b/src/basic/res/races/cat.xml
deleted file mode 100644
index d71d41b92..000000000
--- a/src/basic/res/races/cat.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/res/races/demon.xml b/src/basic/res/races/demon.xml
deleted file mode 100644
index 24f89c515..000000000
--- a/src/basic/res/races/demon.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/res/races/dwarf.xml b/src/basic/res/races/dwarf.xml
deleted file mode 100644
index a718581a7..000000000
--- a/src/basic/res/races/dwarf.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/basic/res/races/elf.xml b/src/basic/res/races/elf.xml
deleted file mode 100644
index 678422652..000000000
--- a/src/basic/res/races/elf.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/basic/res/races/goblin.xml b/src/basic/res/races/goblin.xml
deleted file mode 100644
index b68137353..000000000
--- a/src/basic/res/races/goblin.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/res/races/halfling.xml b/src/basic/res/races/halfling.xml
deleted file mode 100644
index 0e61aa55d..000000000
--- a/src/basic/res/races/halfling.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/res/races/human.xml b/src/basic/res/races/human.xml
deleted file mode 100644
index 0d689b4ac..000000000
--- a/src/basic/res/races/human.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/res/races/insect.xml b/src/basic/res/races/insect.xml
deleted file mode 100644
index d727e1ee4..000000000
--- a/src/basic/res/races/insect.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/basic/res/races/orc.xml b/src/basic/res/races/orc.xml
deleted file mode 100644
index 2caaaf8e5..000000000
--- a/src/basic/res/races/orc.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/res/races/troll.xml b/src/basic/res/races/troll.xml
deleted file mode 100644
index 3761e17ec..000000000
--- a/src/basic/res/races/troll.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/res/ships.xml b/src/basic/res/ships.xml
deleted file mode 100644
index f5577c2f4..000000000
--- a/src/basic/res/ships.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
diff --git a/src/basic/res/ships/boat.xml b/src/basic/res/ships/boat.xml
deleted file mode 100644
index c19d18529..000000000
--- a/src/basic/res/ships/boat.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/res/spells.xml b/src/basic/res/spells.xml
deleted file mode 100644
index 343cd1e92..000000000
--- a/src/basic/res/spells.xml
+++ /dev/null
@@ -1,2 +0,0 @@
-
-
diff --git a/src/basic/res/terrains.xml b/src/basic/res/terrains.xml
deleted file mode 100644
index 5fb289d3b..000000000
--- a/src/basic/res/terrains.xml
+++ /dev/null
@@ -1,57 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/res/weapons.xml b/src/basic/res/weapons.xml
deleted file mode 100644
index 0cab11ad0..000000000
--- a/src/basic/res/weapons.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/basic/scripts/basic/main.lua b/src/basic/scripts/basic/main.lua
deleted file mode 100644
index 300a58e7e..000000000
--- a/src/basic/scripts/basic/main.lua
+++ /dev/null
@@ -1,54 +0,0 @@
-require "multis"
-
-function process(orders)
- local confirmed_multis = { }
- local suspected_multis = { }
-
- if open_game(get_turn())~=0 then
- print("could not read game")
- return -1
- end
- init_summary()
-
- -- kill multi-players (external script)
- kill_multis(confirmed_multis, false)
- mark_multis(suspected_multis, false)
-
- -- run the turn:
- if read_orders(orders) ~= 0 then
- print("could not read " .. orders)
- return -1
- end
-
- plan_monsters()
-
- if nmr_check(config.maxnmrs or 80)~=0 then
- return -1
- end
-
- process_orders()
-
- -- create new monsters:
- spawn_dragons()
- spawn_undead()
- spawn_braineaters(0.25)
- spawn_ents()
-
- -- post-turn updates:
- update_xmas2006()
- update_embassies()
- update_guards()
- update_scores()
-
- local localechange = { de = { "ii" } }
- change_locales(localechange)
-
- write_files(config.locales)
-
- file = "" .. get_turn() .. ".dat"
- if write_game(file, "binary")~=0 then
- print("could not write game")
- return -1
- end
- return 0
-end
diff --git a/src/basic/scripts/basic/modules.lua b/src/basic/scripts/basic/modules.lua
deleted file mode 100644
index 4ed093dbb..000000000
--- a/src/basic/scripts/basic/modules.lua
+++ /dev/null
@@ -1 +0,0 @@
-require "basic.rules"
diff --git a/src/basic/scripts/basic/rules.lua b/src/basic/scripts/basic/rules.lua
deleted file mode 100644
index 5866a8ffc..000000000
--- a/src/basic/scripts/basic/rules.lua
+++ /dev/null
@@ -1,8 +0,0 @@
-function item_canuse(u, iname)
- local race = u.race
- if iname=="greatbow" then
- -- only elves use greatbow
- return race=="elf"
- end
- return true
-end
diff --git a/src/basic/src/main.c b/src/basic/src/main.c
deleted file mode 100644
index 1ac2be9cf..000000000
--- a/src/basic/src/main.c
+++ /dev/null
@@ -1,135 +0,0 @@
-#include
-#include
-
-#include
-#include
-#include
-#include
-#include
-
-#include
-#include
-
-static const char * luafile = "init.lua";
-static const char * entry_point = NULL;
-static int memdebug = 0;
-
-static void parse_config(const char * filename)
-{
- dictionary * d = iniparser_new(filename);
- if (d) {
- load_inifile(d);
-
- memdebug = iniparser_getint(d, "eressea:memcheck", memdebug);
- entry_point = iniparser_getstring(d, "eressea:run", entry_point);
- luafile = iniparser_getstring(d, "eressea:load", luafile);
-
- /* only one value in the [editor] section */
- force_color = iniparser_getint(d, "editor:color", force_color);
- }
- global.inifile = d;
-}
-
-static int
-usage(const char * prog, const char * arg)
-{
- if (arg) {
- fprintf(stderr, "unknown argument: %s\n\n", arg);
- }
- fprintf(stderr, "Usage: %s [options]\n"
- "-t : read this datafile, not the most current one\n"
- "-q : be quite (same as -v 0)\n"
- "-v : verbosity level\n"
- "-C : run in interactive mode\n"
- "--color : force curses to use colors even when not detected\n"
- "--help : help\n", prog);
- return -1;
-}
-
-static int
-parse_args(int argc, char **argv)
-{
- int i;
-
- for (i=1;i!=argc;++i) {
- if (argv[i][0]!='-') {
- return usage(argv[0], argv[i]);
- } else if (argv[i][1]=='-') { /* long format */
- if (strcmp(argv[i]+2, "version")==0) {
- printf("\n%s PBEM host\n"
- "Copyright (C) 1996-2005 C. Schlittchen, K. Zedel, E. Rehling, H. Peters.\n\n"
- "Compilation: " __DATE__ " at " __TIME__ "\nVersion: %f\n\n", global.gamename, version());
- }
- else if (strcmp(argv[i]+2, "color")==0) {
- /* force the editor to have colors */
- force_color = 1;
- }
- else if (strcmp(argv[i]+2, "help")==0) {
- return usage(argv[0], NULL);
- }
- else {
- return usage(argv[0], argv[i]);
- }
- } else switch(argv[i][1]) {
- case 'C':
- entry_point = NULL;
- break;
- case 'e':
- entry_point = argv[++i];
- break;
- case 't':
- turn = atoi(argv[++i]);
- break;
- case 'q':
- verbosity = 0;
- break;
- case 'v':
- verbosity = atoi(argv[++i]);
- break;
- case 'h':
- return usage(argv[0], NULL);
- default:
- return usage(argv[0], argv[i]);
- }
- }
-
- return 0;
-}
-
-
-void locale_init(void)
-{
- setlocale(LC_CTYPE, "");
- setlocale(LC_NUMERIC, "C");
- assert(towlower(0xC4)==0xE4); /* Ä => ä */
-}
-
-int main(int argc, char ** argv)
-{
- int err;
-
- log_open("eressea.log");
- locale_init();
- parse_config("eressea.ini");
-
- err = parse_args(argc, argv);
- if (err) {
- return err;
- }
-
- err = eressea_init();
- if (err) {
- log_error(("initialization failed with code %d\n", err));
- return err;
- }
-
- err = eressea_run(luafile, entry_point);
- if (err) {
- log_error(("server execution failed with code %d\n", err));
- return err;
- }
-
- eressea_done();
- log_close();
- return 0;
-}
diff --git a/src/basic/src/server.c b/src/basic/src/server.c
deleted file mode 100644
index b6d606005..000000000
--- a/src/basic/src/server.c
+++ /dev/null
@@ -1,2 +0,0 @@
-#include "stdafx.h"
-#include "main.c"
diff --git a/src/eressea/res/buildings/castle.xml b/src/eressea/res/buildings/castle.xml
deleted file mode 100644
index 296d1f716..000000000
--- a/src/eressea/res/buildings/castle.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/external/bson/bson.c b/src/external/bson/bson.c
deleted file mode 100644
index cd2b71075..000000000
--- a/src/external/bson/bson.c
+++ /dev/null
@@ -1,634 +0,0 @@
-/* bson.c */
-
-#include
-#include "bson.h"
-#include
-#include
-#include
-#include
-
-const int initialBufferSize = 128;
-
-/* only need one of these */
-static const int zero = 0;
-
-/* ----------------------------
- READING
- ------------------------------ */
-
-bson * bson_empty(bson * obj){
- static char * data = "\005\0\0\0\0";
- return bson_init(obj, data, 0);
-}
-
-void bson_copy(bson* out, const bson* in){
- if (!out) return;
- out->data = bson_malloc(bson_size(in));
- out->owned = 1;
- memcpy(out->data, in->data, bson_size(in));
-}
-
-bson * bson_from_buffer(bson * b, bson_buffer * buf){
- return bson_init(b, bson_buffer_finish(buf), 1);
-}
-
-bson * bson_init( bson * b , char * data , bson_bool_t mine ){
- b->data = data;
- b->owned = mine;
- return b;
-}
-int bson_size(const bson * b ){
- int i;
- if ( ! b || ! b->data )
- return 0;
- bson_little_endian32(&i, *(int32_t*)b->data);
- return i;
-}
-void bson_destroy( bson * b ){
- if ( b->owned && b->data )
- free( b->data );
- b->data = 0;
- b->owned = 0;
-}
-
-static char hexbyte(char hex){
- switch (hex){
- case '0': return 0x0;
- case '1': return 0x1;
- case '2': return 0x2;
- case '3': return 0x3;
- case '4': return 0x4;
- case '5': return 0x5;
- case '6': return 0x6;
- case '7': return 0x7;
- case '8': return 0x8;
- case '9': return 0x9;
- case 'a':
- case 'A': return 0xa;
- case 'b':
- case 'B': return 0xb;
- case 'c':
- case 'C': return 0xc;
- case 'd':
- case 'D': return 0xd;
- case 'e':
- case 'E': return 0xe;
- case 'f':
- case 'F': return 0xf;
- default: return 0x0; /* something smarter? */
- }
-}
-
-void bson_oid_from_string(bson_oid_t* oid, const char* str){
- int i;
- for (i=0; i<12; i++){
- oid->bytes[i] = (hexbyte(str[2*i]) << 4) | hexbyte(str[2*i + 1]);
- }
-}
-void bson_oid_to_string(const bson_oid_t* oid, char* str){
- static const char hex[16] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
- int i;
- for (i=0; i<12; i++){
- str[2*i] = hex[(oid->bytes[i] & 0xf0) >> 4];
- str[2*i + 1] = hex[ oid->bytes[i] & 0x0f ];
- }
- str[24] = '\0';
-}
-void bson_oid_gen(bson_oid_t* oid){
- static int incr = 0;
- static int fuzz = 0;
- int i = incr++; /*TODO make atomic*/
- unsigned int t = (unsigned int)time(NULL);
-
- /* TODO rand sucks. find something better */
- if (!fuzz){
- srand(t);
- fuzz = rand();
- }
-
- bson_big_endian32(&oid->ints[0], t);
- oid->ints[1] = fuzz;
- bson_big_endian32(&oid->ints[2], i);
-}
-
-time_t bson_oid_generated_time(bson_oid_t* oid){
- time_t out;
- bson_big_endian32(&out, oid->ints[0]);
- return out;
-}
-
-void bson_print( bson * b ){
- bson_print_raw( b->data , 0 );
-}
-
-void bson_print_raw( const char * data , int depth ){
- bson_iterator i;
- const char * key;
- int temp;
- char oidhex[25];
- bson_iterator_init( &i , data );
-
- while ( bson_iterator_next( &i ) ){
- bson_type t = bson_iterator_type( &i );
- if ( t == 0 )
- break;
- key = bson_iterator_key( &i );
-
- for ( temp=0; temp<=depth; temp++ )
- printf( "\t" );
- printf( "%s : %d \t " , key , t );
- switch ( t ){
- case bson_int: printf( "%d" , bson_iterator_int( &i ) ); break;
- case bson_double: printf( "%f" , bson_iterator_double( &i ) ); break;
- case bson_bool: printf( "%s" , bson_iterator_bool( &i ) ? "true" : "false" ); break;
- case bson_string: printf( "%s" , bson_iterator_string( &i ) ); break;
- case bson_null: printf( "null" ); break;
- case bson_oid: bson_oid_to_string(bson_iterator_oid(&i), oidhex); printf( "%s" , oidhex ); break;
- case bson_object:
- case bson_array:
- printf( "\n" );
- bson_print_raw( bson_iterator_value( &i ) , depth + 1 );
- break;
- default:
- fprintf( stderr , "can't print type : %d\n" , t );
- }
- printf( "\n" );
- }
-}
-
-/* ----------------------------
- ITERATOR
- ------------------------------ */
-
-void bson_iterator_init( bson_iterator * i , const char * bson ){
- i->cur = bson + 4;
- i->first = 1;
-}
-
-bson_type bson_find(bson_iterator* it, const bson* obj, const char* name){
- bson_iterator_init(it, obj->data);
- while(bson_iterator_next(it)){
- if (strcmp(name, bson_iterator_key(it)) == 0)
- break;
- }
- return bson_iterator_type(it);
-}
-
-bson_bool_t bson_iterator_more( const bson_iterator * i ){
- return *(i->cur);
-}
-
-bson_type bson_iterator_next( bson_iterator * i ){
- ptrdiff_t ds;
-
- if ( i->first ){
- i->first = 0;
- return (bson_type)(*i->cur);
- }
-
- switch ( bson_iterator_type(i) ){
- case bson_eoo: return bson_eoo; /* don't advance */
- case bson_undefined:
- case bson_null: ds = 0; break;
- case bson_bool: ds = 1; break;
- case bson_int: ds = 4; break;
- case bson_long:
- case bson_double:
- case bson_timestamp:
- case bson_date: ds = 8; break;
- case bson_oid: ds = 12; break;
- case bson_string:
- case bson_symbol:
- case bson_code: ds = 4 + bson_iterator_int_raw(i); break;
- case bson_bindata: ds = 5 + bson_iterator_int_raw(i); break;
- case bson_object:
- case bson_array:
- case bson_codewscope: ds = bson_iterator_int_raw(i); break;
- case bson_dbref: ds = 4+12 + bson_iterator_int_raw(i); break;
- case bson_regex:
- {
- const char * s = bson_iterator_value(i);
- const char * p = s;
- p += strlen(p)+1;
- p += strlen(p)+1;
- ds = p-s;
- break;
- }
-
- default:
- {
- char msg[] = "unknown type: 000000000000";
- bson_numstr(msg+14, (unsigned)(i->cur[0]));
- bson_fatal_msg(0, msg);
- return 0;
- }
- }
-
- i->cur += 1 + strlen( i->cur + 1 ) + 1 + ds;
-
- return (bson_type)(*i->cur);
-}
-
-bson_type bson_iterator_type( const bson_iterator * i ){
- return (bson_type)i->cur[0];
-}
-const char * bson_iterator_key( const bson_iterator * i ){
- return i->cur + 1;
-}
-const char * bson_iterator_value( const bson_iterator * i ){
- const char * t = i->cur + 1;
- t += strlen( t ) + 1;
- return t;
-}
-
-/* types */
-
-int bson_iterator_int_raw( const bson_iterator * i ){
- int out;
- bson_little_endian32(&out, *(int32_t*)bson_iterator_value( i ));
- return out;
-}
-double bson_iterator_double_raw( const bson_iterator * i ){
- double out;
- bson_little_endian64(&out, *(int64_t*)bson_iterator_value( i ));
- return out;
-}
-int64_t bson_iterator_long_raw( const bson_iterator * i ){
- int64_t out;
- bson_little_endian64(&out, *(int64_t*)bson_iterator_value( i ));
- return out;
-}
-
-bson_bool_t bson_iterator_bool_raw( const bson_iterator * i ){
- return bson_iterator_value( i )[0];
-}
-
-bson_oid_t * bson_iterator_oid( const bson_iterator * i ){
- return (bson_oid_t*)bson_iterator_value(i);
-}
-
-int bson_iterator_int( const bson_iterator * i ){
- switch (bson_iterator_type(i)){
- case bson_int: return bson_iterator_int_raw(i);
- case bson_long: return (int)bson_iterator_long_raw(i);
- case bson_double: return (int)bson_iterator_double_raw(i);
- default: return 0;
- }
-}
-double bson_iterator_double( const bson_iterator * i ){
- switch (bson_iterator_type(i)){
- case bson_int: return bson_iterator_int_raw(i);
- case bson_long: return (double)bson_iterator_long_raw(i);
- case bson_double: return bson_iterator_double_raw(i);
- default: return 0;
- }
-}
-int64_t bson_iterator_long( const bson_iterator * i ){
- switch (bson_iterator_type(i)){
- case bson_int: return bson_iterator_int_raw(i);
- case bson_long: return bson_iterator_long_raw(i);
- case bson_double: return (int64_t)bson_iterator_double_raw(i);
- default: return 0;
- }
-}
-
-bson_bool_t bson_iterator_bool( const bson_iterator * i ){
- switch (bson_iterator_type(i)){
- case bson_bool: return bson_iterator_bool_raw(i);
- case bson_int: return bson_iterator_int_raw(i) != 0;
- case bson_long: return bson_iterator_long_raw(i) != 0;
- case bson_double: return bson_iterator_double_raw(i) != 0;
- case bson_eoo:
- case bson_null: return 0;
- default: return 1;
- }
-}
-
-const char * bson_iterator_string( const bson_iterator * i ){
- return bson_iterator_value( i ) + 4;
-}
-int bson_iterator_string_len( const bson_iterator * i ){
- return bson_iterator_int_raw( i );
-}
-
-const char * bson_iterator_code( const bson_iterator * i ){
- switch (bson_iterator_type(i)){
- case bson_string:
- case bson_code: return bson_iterator_value(i) + 4;
- case bson_codewscope: return bson_iterator_value(i) + 8;
- default: return NULL;
- }
-}
-
-void bson_iterator_code_scope(const bson_iterator * i, bson * scope){
- if (bson_iterator_type(i) == bson_codewscope){
- int code_len;
- bson_little_endian32(&code_len, *(int32_t*)(bson_iterator_value(i)+4));
- bson_init(scope, (void*)(bson_iterator_value(i)+8+code_len), 0);
- }else{
- bson_empty(scope);
- }
-}
-
-bson_date_t bson_iterator_date(const bson_iterator * i){
- return bson_iterator_long_raw(i);
-}
-
-time_t bson_iterator_time_t(const bson_iterator * i){
- return bson_iterator_date(i) / 1000;
-}
-
-int bson_iterator_bin_len( const bson_iterator * i ){
- return bson_iterator_int_raw( i );
-}
-
-char bson_iterator_bin_type( const bson_iterator * i ){
- return bson_iterator_value(i)[4];
-}
-const char * bson_iterator_bin_data( const bson_iterator * i ){
- return bson_iterator_value( i ) + 5;
-}
-
-const char * bson_iterator_regex( const bson_iterator * i ){
- return bson_iterator_value( i );
-}
-const char * bson_iterator_regex_opts( const bson_iterator * i ){
- const char* p = bson_iterator_value( i );
- return p + strlen(p) + 1;
-
-}
-
-void bson_iterator_subobject(const bson_iterator * i, bson * sub){
- bson_init(sub, (char*)bson_iterator_value(i), 0);
-}
-void bson_iterator_subiterator(const bson_iterator * i, bson_iterator * sub){
- bson_iterator_init(sub, bson_iterator_value(i));
-}
-
-/* ----------------------------
- BUILDING
- ------------------------------ */
-
-bson_buffer * bson_buffer_init( bson_buffer * b ){
- b->buf = (char*)bson_malloc( initialBufferSize );
- b->bufSize = initialBufferSize;
- b->cur = b->buf + 4;
- b->finished = 0;
- b->stackPos = 0;
- return b;
-}
-
-void bson_append_byte( bson_buffer * b , char c ){
- b->cur[0] = c;
- b->cur++;
-}
-void bson_append( bson_buffer * b , const void * data , size_t len ){
- memcpy( b->cur , data , len );
- b->cur += len;
-}
-void bson_append32(bson_buffer * b, const void * data){
- bson_little_endian32(b->cur, *(int32_t*)data);
- b->cur += 4;
-}
-void bson_append64(bson_buffer * b, const void * data){
- bson_little_endian64(b->cur, *(int64_t*)data);
- b->cur += 8;
-}
-
-bson_buffer * bson_ensure_space( bson_buffer * b , const size_t bytesNeeded ){
- ptrdiff_t pos = b->cur - b->buf;
- char * orig = b->buf;
- size_t new_size;
-
- if (b->finished)
- bson_fatal_msg(!!b->buf, "trying to append to finished buffer");
-
- if (pos + bytesNeeded <= b->bufSize)
- return b;
-
- new_size = 3 * (b->bufSize + bytesNeeded) / 2;
- b->buf = realloc(b->buf, new_size);
- if (!b->buf)
- bson_fatal_msg(!!b->buf, "realloc() failed");
-
- b->bufSize = new_size;
- b->cur += b->buf - orig;
-
- return b;
-}
-
-char * bson_buffer_finish( bson_buffer * b ){
- ptrdiff_t i;
- if ( ! b->finished ){
- if ( ! bson_ensure_space( b , 1 ) ) return 0;
- bson_append_byte( b , 0 );
- i = b->cur - b->buf;
- bson_little_endian32(b->buf, (int32_t)i);
- b->finished = 1;
- }
- return b->buf;
-}
-
-void bson_buffer_destroy( bson_buffer * b ){
- free( b->buf );
- b->buf = 0;
- b->cur = 0;
- b->finished = 1;
-}
-
-static bson_buffer * bson_append_estart( bson_buffer * b , int type , const char * name , const size_t dataSize ){
- const int sl = (int)(strlen(name) + 1);
- if ( ! bson_ensure_space( b , 1 + sl + dataSize ) )
- return 0;
- bson_append_byte( b , (char)type );
- bson_append( b , name , sl );
- return b;
-}
-
-/* ----------------------------
- BUILDING TYPES
- ------------------------------ */
-
-bson_buffer * bson_append_int( bson_buffer * b , const char * name , const int i ){
- if ( ! bson_append_estart( b , bson_int , name , 4 ) ) return 0;
- bson_append32( b , &i );
- return b;
-}
-bson_buffer * bson_append_long( bson_buffer * b , const char * name , const int64_t i ){
- if ( ! bson_append_estart( b , bson_long , name , 8 ) ) return 0;
- bson_append64( b , &i );
- return b;
-}
-bson_buffer * bson_append_double( bson_buffer * b , const char * name , const double d ){
- if ( ! bson_append_estart( b , bson_double , name , 8 ) ) return 0;
- bson_append64( b , &d );
- return b;
-}
-bson_buffer * bson_append_bool( bson_buffer * b , const char * name , const bson_bool_t i ){
- if ( ! bson_append_estart( b , bson_bool , name , 1 ) ) return 0;
- bson_append_byte( b , i?1:0 );
- return b;
-}
-bson_buffer * bson_append_null( bson_buffer * b , const char * name ){
- if ( ! bson_append_estart( b , bson_null , name , 0 ) ) return 0;
- return b;
-}
-bson_buffer * bson_append_undefined( bson_buffer * b , const char * name ){
- if ( ! bson_append_estart( b , bson_undefined , name , 0 ) ) return 0;
- return b;
-}
-bson_buffer * bson_append_string_base( bson_buffer * b , const char * name , const char * value , bson_type type){
- int sl = (int)(strlen( value ) + 1);
- if ( ! bson_append_estart( b , type , name , 4 + sl ) ) return 0;
- bson_append32( b , &sl);
- bson_append( b , value , sl );
- return b;
-}
-bson_buffer * bson_append_string( bson_buffer * b , const char * name , const char * value ){
- return bson_append_string_base(b, name, value, bson_string);
-}
-bson_buffer * bson_append_symbol( bson_buffer * b , const char * name , const char * value ){
- return bson_append_string_base(b, name, value, bson_symbol);
-}
-bson_buffer * bson_append_code( bson_buffer * b , const char * name , const char * value ){
- return bson_append_string_base(b, name, value, bson_code);
-}
-
-bson_buffer * bson_append_code_w_scope( bson_buffer * b , const char * name , const char * code , const bson * scope){
- int sl = (int)(strlen(code) + 1);
- int size = 4 + 4 + sl + bson_size(scope);
- if (!bson_append_estart(b, bson_codewscope, name, size)) return 0;
- bson_append32(b, &size);
- bson_append32(b, &sl);
- bson_append(b, code, sl);
- bson_append(b, scope->data, bson_size(scope));
- return b;
-}
-
-bson_buffer * bson_append_binary( bson_buffer * b, const char * name, char type, const char * str, int len ){
- if ( ! bson_append_estart( b , bson_bindata , name , 4+1+len ) ) return 0;
- bson_append32(b, &len);
- bson_append_byte(b, type);
- bson_append(b, str, len);
- return b;
-}
-bson_buffer * bson_append_oid( bson_buffer * b , const char * name , const bson_oid_t * oid ){
- if ( ! bson_append_estart( b , bson_oid , name , 12 ) ) return 0;
- bson_append( b , oid , 12 );
- return b;
-}
-bson_buffer * bson_append_new_oid( bson_buffer * b , const char * name ){
- bson_oid_t oid;
- bson_oid_gen(&oid);
- return bson_append_oid(b, name, &oid);
-}
-
-bson_buffer * bson_append_regex( bson_buffer * b , const char * name , const char * pattern, const char * opts ){
- const size_t plen = strlen(pattern)+1;
- const size_t olen = strlen(opts)+1;
- if ( ! bson_append_estart( b , bson_regex , name , (int)(plen + olen) ) ) return 0;
- bson_append( b , pattern , (int)plen );
- bson_append( b , opts , (int)olen );
- return b;
-}
-
-bson_buffer * bson_append_bson( bson_buffer * b , const char * name , const bson* bson){
- if ( ! bson_append_estart( b , bson_object , name , bson_size(bson) ) ) return 0;
- bson_append( b , bson->data , bson_size(bson) );
- return b;
-}
-
-bson_buffer * bson_append_element( bson_buffer * b, const char * name_or_null, const bson_iterator* elem){
- bson_iterator next = *elem;
- int size;
-
- bson_iterator_next(&next);
- size = (int)(next.cur - elem->cur);
-
- if (name_or_null == NULL){
- bson_ensure_space(b, size);
- bson_append(b, elem->cur, size);
- }else{
- size_t data_size = size - 1 - strlen(bson_iterator_key(elem));
- bson_append_estart(b, elem->cur[0], name_or_null, data_size);
- bson_append(b, name_or_null, strlen(name_or_null));
- bson_append(b, bson_iterator_value(elem), data_size);
- }
-
- return b;
-}
-
-bson_buffer * bson_append_date( bson_buffer * b , const char * name , bson_date_t millis ){
- if ( ! bson_append_estart( b , bson_date , name , 8 ) ) return 0;
- bson_append64( b , &millis );
- return b;
-}
-
-bson_buffer * bson_append_time_t( bson_buffer * b , const char * name , time_t secs){
- return bson_append_date(b, name, (bson_date_t)secs * 1000);
-}
-
-bson_buffer * bson_append_start_object( bson_buffer * b , const char * name ){
- if ( ! bson_append_estart( b , bson_object , name , 5 ) ) return 0;
- b->stack[ b->stackPos++ ] = b->cur - b->buf;
- bson_append32( b , &zero );
- return b;
-}
-
-bson_buffer * bson_append_start_array( bson_buffer * b , const char * name ){
- if ( ! bson_append_estart( b , bson_array , name , 5 ) ) return 0;
- b->stack[ b->stackPos++ ] = b->cur - b->buf;
- bson_append32( b , &zero );
- return b;
-}
-
-bson_buffer * bson_append_finish_object( bson_buffer * b ){
- char * start;
- ptrdiff_t i;
- if ( ! bson_ensure_space( b , 1 ) ) return 0;
- bson_append_byte( b , 0 );
-
- start = b->buf + b->stack[ --b->stackPos ];
- i = b->cur - start;
- bson_little_endian32(start, (int32_t)i);
-
- return b;
-}
-
-void* bson_malloc(int size){
- void* p = malloc(size);
- bson_fatal_msg(!!p, "malloc() failed");
- return p;
-}
-
-static bson_err_handler err_handler = NULL;
-
-bson_err_handler set_bson_err_handler(bson_err_handler func){
- bson_err_handler old = err_handler;
- err_handler = func;
- return old;
-}
-
-void bson_fatal( int ok ){
- bson_fatal_msg(ok, "");
-}
-
-void bson_fatal_msg( int ok , const char* msg){
- if (ok)
- return;
-
- if (err_handler){
- err_handler(msg);
- }
-
- fprintf( stderr , "error: %s\n" , msg );
- exit(-5);
-}
-
-extern const char bson_numstrs[1000][4];
-void bson_numstr(char* str, int i){
- if(i < 1000)
- memcpy(str, bson_numstrs[i], 4);
- else
- sprintf(str,"%d", i);
-}
diff --git a/src/external/bson/bson.h b/src/external/bson/bson.h
deleted file mode 100644
index 588e11b02..000000000
--- a/src/external/bson/bson.h
+++ /dev/null
@@ -1,203 +0,0 @@
-/* bson.h */
-
-#ifndef _BSON_H_
-#define _BSON_H_
-
-#include "platform_hacks.h"
-#include
-
-MONGO_EXTERN_C_START
-
-typedef enum {
- bson_eoo=0 ,
- bson_double=1,
- bson_string=2,
- bson_object=3,
- bson_array=4,
- bson_bindata=5,
- bson_undefined=6,
- bson_oid=7,
- bson_bool=8,
- bson_date=9,
- bson_null=10,
- bson_regex=11,
- bson_dbref=12, /* deprecated */
- bson_code=13,
- bson_symbol=14,
- bson_codewscope=15,
- bson_int = 16,
- bson_timestamp = 17,
- bson_long = 18
-} bson_type;
-
-typedef int bson_bool_t;
-
-typedef struct {
- char * data;
- bson_bool_t owned;
-} bson;
-
-typedef struct {
- const char * cur;
- bson_bool_t first;
-} bson_iterator;
-
-typedef struct {
- char * buf;
- char * cur;
- size_t bufSize;
- bson_bool_t finished;
- ptrdiff_t stack[32];
- int stackPos;
-} bson_buffer;
-
-#pragma pack(1)
-typedef union{
- char bytes[12];
- int ints[3];
-} bson_oid_t;
-#pragma pack()
-
-typedef int64_t bson_date_t; /* milliseconds since epoch UTC */
-
-/* ----------------------------
- READING
- ------------------------------ */
-
-
-bson * bson_empty(bson * obj); /* returns pointer to static empty bson object */
-void bson_copy(bson* out, const bson* in); /* puts data in new buffer. NOOP if out==NULL */
-bson * bson_from_buffer(bson * b, bson_buffer * buf);
-bson * bson_init( bson * b , char * data , bson_bool_t mine );
-int bson_size(const bson * b );
-void bson_destroy( bson * b );
-
-void bson_print( bson * b );
-void bson_print_raw( const char * bson , int depth );
-
-/* advances iterator to named field */
-/* returns bson_eoo (which is false) if field not found */
-bson_type bson_find(bson_iterator* it, const bson* obj, const char* name);
-
-void bson_iterator_init( bson_iterator * i , const char * bson );
-
-/* more returns true for eoo. best to loop with bson_iterator_next(&it) */
-bson_bool_t bson_iterator_more( const bson_iterator * i );
-bson_type bson_iterator_next( bson_iterator * i );
-
-bson_type bson_iterator_type( const bson_iterator * i );
-const char * bson_iterator_key( const bson_iterator * i );
-const char * bson_iterator_value( const bson_iterator * i );
-
-/* these convert to the right type (return 0 if non-numeric) */
-double bson_iterator_double( const bson_iterator * i );
-int bson_iterator_int( const bson_iterator * i );
-int64_t bson_iterator_long( const bson_iterator * i );
-
-/* false: boolean false, 0 in any type, or null */
-/* true: anything else (even empty strings and objects) */
-bson_bool_t bson_iterator_bool( const bson_iterator * i );
-
-/* these assume you are using the right type */
-double bson_iterator_double_raw( const bson_iterator * i );
-int bson_iterator_int_raw( const bson_iterator * i );
-int64_t bson_iterator_long_raw( const bson_iterator * i );
-bson_bool_t bson_iterator_bool_raw( const bson_iterator * i );
-bson_oid_t* bson_iterator_oid( const bson_iterator * i );
-
-/* these can also be used with bson_code and bson_symbol*/
-const char * bson_iterator_string( const bson_iterator * i );
-int bson_iterator_string_len( const bson_iterator * i );
-
-/* works with bson_code, bson_codewscope, and bson_string */
-/* returns NULL for everything else */
-const char * bson_iterator_code(const bson_iterator * i);
-
-/* calls bson_empty on scope if not a bson_codewscope */
-void bson_iterator_code_scope(const bson_iterator * i, bson * scope);
-
-/* both of these only work with bson_date */
-bson_date_t bson_iterator_date(const bson_iterator * i);
-time_t bson_iterator_time_t(const bson_iterator * i);
-
-int bson_iterator_bin_len( const bson_iterator * i );
-char bson_iterator_bin_type( const bson_iterator * i );
-const char * bson_iterator_bin_data( const bson_iterator * i );
-
-const char * bson_iterator_regex( const bson_iterator * i );
-const char * bson_iterator_regex_opts( const bson_iterator * i );
-
-/* these work with bson_object and bson_array */
-void bson_iterator_subobject(const bson_iterator * i, bson * sub);
-void bson_iterator_subiterator(const bson_iterator * i, bson_iterator * sub);
-
-/* str must be at least 24 hex chars + null byte */
-void bson_oid_from_string(bson_oid_t* oid, const char* str);
-void bson_oid_to_string(const bson_oid_t* oid, char* str);
-void bson_oid_gen(bson_oid_t* oid);
-
-time_t bson_oid_generated_time(bson_oid_t* oid); /* Gives the time the OID was created */
-
-/* ----------------------------
- BUILDING
- ------------------------------ */
-
-bson_buffer * bson_buffer_init( bson_buffer * b );
-bson_buffer * bson_ensure_space( bson_buffer * b , const size_t bytesNeeded );
-
-/**
- * @return the raw data. you either should free this OR call bson_destroy not both
- */
-char * bson_buffer_finish( bson_buffer * b );
-void bson_buffer_destroy( bson_buffer * b );
-
-bson_buffer * bson_append_oid( bson_buffer * b , const char * name , const bson_oid_t* oid );
-bson_buffer * bson_append_new_oid( bson_buffer * b , const char * name );
-bson_buffer * bson_append_int( bson_buffer * b , const char * name , const int i );
-bson_buffer * bson_append_long( bson_buffer * b , const char * name , const int64_t i );
-bson_buffer * bson_append_double( bson_buffer * b , const char * name , const double d );
-bson_buffer * bson_append_string( bson_buffer * b , const char * name , const char * str );
-bson_buffer * bson_append_symbol( bson_buffer * b , const char * name , const char * str );
-bson_buffer * bson_append_code( bson_buffer * b , const char * name , const char * str );
-bson_buffer * bson_append_code_w_scope( bson_buffer * b , const char * name , const char * code , const bson * scope);
-bson_buffer * bson_append_binary( bson_buffer * b, const char * name, char type, const char * str, int len );
-bson_buffer * bson_append_bool( bson_buffer * b , const char * name , const bson_bool_t v );
-bson_buffer * bson_append_null( bson_buffer * b , const char * name );
-bson_buffer * bson_append_undefined( bson_buffer * b , const char * name );
-bson_buffer * bson_append_regex( bson_buffer * b , const char * name , const char * pattern, const char * opts );
-bson_buffer * bson_append_bson( bson_buffer * b , const char * name , const bson* bson);
-bson_buffer * bson_append_element( bson_buffer * b, const char * name_or_null, const bson_iterator* elem);
-
-/* these both append a bson_date */
-bson_buffer * bson_append_date(bson_buffer * b, const char * name, bson_date_t millis);
-bson_buffer * bson_append_time_t(bson_buffer * b, const char * name, time_t secs);
-
-bson_buffer * bson_append_start_object( bson_buffer * b , const char * name );
-bson_buffer * bson_append_start_array( bson_buffer * b , const char * name );
-bson_buffer * bson_append_finish_object( bson_buffer * b );
-
-void bson_numstr(char* str, int i);
-void bson_incnumstr(char* str);
-
-
-/* ------------------------------
- ERROR HANDLING - also used in mongo code
- ------------------------------ */
-
-void * bson_malloc(int size); /* checks return value */
-
-/* bson_err_handlers shouldn't return!!! */
-typedef void(*bson_err_handler)(const char* errmsg);
-
-/* returns old handler or NULL */
-/* default handler prints error then exits with failure*/
-bson_err_handler set_bson_err_handler(bson_err_handler func);
-
-
-
-/* does nothing is ok != 0 */
-void bson_fatal( int ok );
-void bson_fatal_msg( int ok, const char* msg );
-
-MONGO_EXTERN_C_END
-#endif
diff --git a/src/external/bson/numbers.c b/src/external/bson/numbers.c
deleted file mode 100644
index c27a501b8..000000000
--- a/src/external/bson/numbers.c
+++ /dev/null
@@ -1,112 +0,0 @@
-/* all the numbers that fit in a 4 byte string */
-const char bson_numstrs[1000][4] = {
- "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
- "10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
- "20", "21", "22", "23", "24", "25", "26", "27", "28", "29",
- "30", "31", "32", "33", "34", "35", "36", "37", "38", "39",
- "40", "41", "42", "43", "44", "45", "46", "47", "48", "49",
- "50", "51", "52", "53", "54", "55", "56", "57", "58", "59",
- "60", "61", "62", "63", "64", "65", "66", "67", "68", "69",
- "70", "71", "72", "73", "74", "75", "76", "77", "78", "79",
- "80", "81", "82", "83", "84", "85", "86", "87", "88", "89",
- "90", "91", "92", "93", "94", "95", "96", "97", "98", "99",
-
- "100", "101", "102", "103", "104", "105", "106", "107", "108", "109",
- "110", "111", "112", "113", "114", "115", "116", "117", "118", "119",
- "120", "121", "122", "123", "124", "125", "126", "127", "128", "129",
- "130", "131", "132", "133", "134", "135", "136", "137", "138", "139",
- "140", "141", "142", "143", "144", "145", "146", "147", "148", "149",
- "150", "151", "152", "153", "154", "155", "156", "157", "158", "159",
- "160", "161", "162", "163", "164", "165", "166", "167", "168", "169",
- "170", "171", "172", "173", "174", "175", "176", "177", "178", "179",
- "180", "181", "182", "183", "184", "185", "186", "187", "188", "189",
- "190", "191", "192", "193", "194", "195", "196", "197", "198", "199",
-
- "200", "201", "202", "203", "204", "205", "206", "207", "208", "209",
- "210", "211", "212", "213", "214", "215", "216", "217", "218", "219",
- "220", "221", "222", "223", "224", "225", "226", "227", "228", "229",
- "230", "231", "232", "233", "234", "235", "236", "237", "238", "239",
- "240", "241", "242", "243", "244", "245", "246", "247", "248", "249",
- "250", "251", "252", "253", "254", "255", "256", "257", "258", "259",
- "260", "261", "262", "263", "264", "265", "266", "267", "268", "269",
- "270", "271", "272", "273", "274", "275", "276", "277", "278", "279",
- "280", "281", "282", "283", "284", "285", "286", "287", "288", "289",
- "290", "291", "292", "293", "294", "295", "296", "297", "298", "299",
-
- "300", "301", "302", "303", "304", "305", "306", "307", "308", "309",
- "310", "311", "312", "313", "314", "315", "316", "317", "318", "319",
- "320", "321", "322", "323", "324", "325", "326", "327", "328", "329",
- "330", "331", "332", "333", "334", "335", "336", "337", "338", "339",
- "340", "341", "342", "343", "344", "345", "346", "347", "348", "349",
- "350", "351", "352", "353", "354", "355", "356", "357", "358", "359",
- "360", "361", "362", "363", "364", "365", "366", "367", "368", "369",
- "370", "371", "372", "373", "374", "375", "376", "377", "378", "379",
- "380", "381", "382", "383", "384", "385", "386", "387", "388", "389",
- "390", "391", "392", "393", "394", "395", "396", "397", "398", "399",
-
- "400", "401", "402", "403", "404", "405", "406", "407", "408", "409",
- "410", "411", "412", "413", "414", "415", "416", "417", "418", "419",
- "420", "421", "422", "423", "424", "425", "426", "427", "428", "429",
- "430", "431", "432", "433", "434", "435", "436", "437", "438", "439",
- "440", "441", "442", "443", "444", "445", "446", "447", "448", "449",
- "450", "451", "452", "453", "454", "455", "456", "457", "458", "459",
- "460", "461", "462", "463", "464", "465", "466", "467", "468", "469",
- "470", "471", "472", "473", "474", "475", "476", "477", "478", "479",
- "480", "481", "482", "483", "484", "485", "486", "487", "488", "489",
- "490", "491", "492", "493", "494", "495", "496", "497", "498", "499",
-
- "500", "501", "502", "503", "504", "505", "506", "507", "508", "509",
- "510", "511", "512", "513", "514", "515", "516", "517", "518", "519",
- "520", "521", "522", "523", "524", "525", "526", "527", "528", "529",
- "530", "531", "532", "533", "534", "535", "536", "537", "538", "539",
- "540", "541", "542", "543", "544", "545", "546", "547", "548", "549",
- "550", "551", "552", "553", "554", "555", "556", "557", "558", "559",
- "560", "561", "562", "563", "564", "565", "566", "567", "568", "569",
- "570", "571", "572", "573", "574", "575", "576", "577", "578", "579",
- "580", "581", "582", "583", "584", "585", "586", "587", "588", "589",
- "590", "591", "592", "593", "594", "595", "596", "597", "598", "599",
-
- "600", "601", "602", "603", "604", "605", "606", "607", "608", "609",
- "610", "611", "612", "613", "614", "615", "616", "617", "618", "619",
- "620", "621", "622", "623", "624", "625", "626", "627", "628", "629",
- "630", "631", "632", "633", "634", "635", "636", "637", "638", "639",
- "640", "641", "642", "643", "644", "645", "646", "647", "648", "649",
- "650", "651", "652", "653", "654", "655", "656", "657", "658", "659",
- "660", "661", "662", "663", "664", "665", "666", "667", "668", "669",
- "670", "671", "672", "673", "674", "675", "676", "677", "678", "679",
- "680", "681", "682", "683", "684", "685", "686", "687", "688", "689",
- "690", "691", "692", "693", "694", "695", "696", "697", "698", "699",
-
- "700", "701", "702", "703", "704", "705", "706", "707", "708", "709",
- "710", "711", "712", "713", "714", "715", "716", "717", "718", "719",
- "720", "721", "722", "723", "724", "725", "726", "727", "728", "729",
- "730", "731", "732", "733", "734", "735", "736", "737", "738", "739",
- "740", "741", "742", "743", "744", "745", "746", "747", "748", "749",
- "750", "751", "752", "753", "754", "755", "756", "757", "758", "759",
- "760", "761", "762", "763", "764", "765", "766", "767", "768", "769",
- "770", "771", "772", "773", "774", "775", "776", "777", "778", "779",
- "780", "781", "782", "783", "784", "785", "786", "787", "788", "789",
- "790", "791", "792", "793", "794", "795", "796", "797", "798", "799",
-
- "800", "801", "802", "803", "804", "805", "806", "807", "808", "809",
- "810", "811", "812", "813", "814", "815", "816", "817", "818", "819",
- "820", "821", "822", "823", "824", "825", "826", "827", "828", "829",
- "830", "831", "832", "833", "834", "835", "836", "837", "838", "839",
- "840", "841", "842", "843", "844", "845", "846", "847", "848", "849",
- "850", "851", "852", "853", "854", "855", "856", "857", "858", "859",
- "860", "861", "862", "863", "864", "865", "866", "867", "868", "869",
- "870", "871", "872", "873", "874", "875", "876", "877", "878", "879",
- "880", "881", "882", "883", "884", "885", "886", "887", "888", "889",
- "890", "891", "892", "893", "894", "895", "896", "897", "898", "899",
-
- "900", "901", "902", "903", "904", "905", "906", "907", "908", "909",
- "910", "911", "912", "913", "914", "915", "916", "917", "918", "919",
- "920", "921", "922", "923", "924", "925", "926", "927", "928", "929",
- "930", "931", "932", "933", "934", "935", "936", "937", "938", "939",
- "940", "941", "942", "943", "944", "945", "946", "947", "948", "949",
- "950", "951", "952", "953", "954", "955", "956", "957", "958", "959",
- "960", "961", "962", "963", "964", "965", "966", "967", "968", "969",
- "970", "971", "972", "973", "974", "975", "976", "977", "978", "979",
- "980", "981", "982", "983", "984", "985", "986", "987", "988", "989",
- "990", "991", "992", "993", "994", "995", "996", "997", "998", "999",
-};
diff --git a/src/external/bson/platform_hacks.h b/src/external/bson/platform_hacks.h
deleted file mode 100644
index 8f6ca5f7b..000000000
--- a/src/external/bson/platform_hacks.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/* platform_hacks.h */
-
-/* all platform-specific ifdefs should go here */
-
-#ifndef _PLATFORM_HACKS_H_
-#define _PLATFORM_HACKS_H_
-
-#ifdef __GNUC__
-#define MONGO_INLINE static __inline__
-#define MONGO_HAVE_STDINT
-#elif defined(_MSC_VER)
-#define MONGO_USE__INT64
-#define MONGO_INLINE __inline
-#else
-#define MONGO_INLINE static
-#endif
-
-#ifdef __cplusplus
-#define MONGO_EXTERN_C_START extern "C" {
-#define MONGO_EXTERN_C_END }
-#else
-#define MONGO_EXTERN_C_START
-#define MONGO_EXTERN_C_END
-#endif
-
-
-#if defined(MONGO_HAVE_STDINT) || __STDC_VERSION__ >= 199901L
-#include
-#elif defined(MONGO_HAVE_UNISTD)
-#include
-#elif defined(MONGO_USE__INT64)
-typedef __int64 int64_t;
-typedef __int32 int32_t;
-#elif defined(MONGO_USE_LONG_LONG_INT)
-typedef long long int int64_t;
-typedef int int32_t;
-#else
-#error must have a 64bit int type
-#endif
-
-MONGO_EXTERN_C_START
-
-MONGO_INLINE void bson_swap_endian64(void* outp, const void* inp){
- const char *in = (const char*)inp;
- char *out = (char*)outp;
-
- out[0] = in[7];
- out[1] = in[6];
- out[2] = in[5];
- out[3] = in[4];
- out[4] = in[3];
- out[5] = in[2];
- out[6] = in[1];
- out[7] = in[0];
-
-}
-MONGO_INLINE void bson_swap_endian32(void* outp, const void* inp){
- const char *in = (const char*)inp;
- char *out = (char*)outp;
-
- out[0] = in[3];
- out[1] = in[2];
- out[2] = in[1];
- out[3] = in[0];
-}
-
-/* big endian is only used for OID generation. little is used everywhere else */
-#ifdef MONGO_BIG_ENDIAN
-#define bson_little_endian64(out, in) ( bson_swap_endian64(out, &in) )
-#define bson_little_endian32(out, in) ( bson_swap_endian32(out, &in) )
-#define bson_big_endian64(out, in) ( memcpy(out, &in, 8) )
-#define bson_big_endian32(out, in) ( memcpy(out, &in, 4) )
-#else
-#ifdef NDEBUG
-#define bson_little_endian64(out, in) { *(int64_t*)out = in; }
-#define bson_little_endian32(out, in) { *(int32_t*)out = in; }
-#define bson_big_endian64(out, in) ( bson_swap_endian64(out, &in) )
-#define bson_big_endian32(out, in) ( bson_swap_endian32(out, &in) )
-#else
-#include
-MONGO_INLINE void bson_little_endian64(void * out, const int64_t in) { memcpy(out, &in, 8); }
-MONGO_INLINE void bson_little_endian32(void * out, const int32_t in) { memcpy(out, &in, 4); }
-MONGO_INLINE void bson_big_endian64(void * out, const int64_t in) { bson_swap_endian64(out, &in); }
-MONGO_INLINE void bson_big_endian32(void * out, const int32_t in) { bson_swap_endian32(out, &in); }
-#endif
-#endif
-
-MONGO_EXTERN_C_END
-
-#endif
diff --git a/src/external/cutest/AllTests.c b/src/external/cutest/AllTests.c
deleted file mode 100644
index 5c849ef8a..000000000
--- a/src/external/cutest/AllTests.c
+++ /dev/null
@@ -1,25 +0,0 @@
-#include
-
-#include "CuTest.h"
-
-CuSuite* CuGetSuite();
-CuSuite* CuStringGetSuite();
-
-void RunAllTests(void)
-{
- CuString *output = CuStringNew();
- CuSuite* suite = CuSuiteNew();
-
- CuSuiteAddSuite(suite, CuGetSuite());
- CuSuiteAddSuite(suite, CuStringGetSuite());
-
- CuSuiteRun(suite);
- CuSuiteSummary(suite, output);
- CuSuiteDetails(suite, output);
- printf("%s\n", output->buffer);
-}
-
-int main(void)
-{
- RunAllTests();
-}
diff --git a/src/external/cutest/CuTest.c b/src/external/cutest/CuTest.c
deleted file mode 100644
index f5268e234..000000000
--- a/src/external/cutest/CuTest.c
+++ /dev/null
@@ -1,309 +0,0 @@
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "CuTest.h"
-
-/*-------------------------------------------------------------------------*
- * CuStr
- *-------------------------------------------------------------------------*/
-
-char* CuStrAlloc(int size)
-{
- char* newStr = (char*) malloc( sizeof(char) * (size) );
- return newStr;
-}
-
-char* CuStrCopy(const char* old)
-{
- int len = (int)strlen(old);
- char* newStr = CuStrAlloc(len + 1);
- strcpy(newStr, old);
- return newStr;
-}
-
-/*-------------------------------------------------------------------------*
- * CuString
- *-------------------------------------------------------------------------*/
-
-void CuStringInit(CuString* str)
-{
- str->length = 0;
- str->size = STRING_MAX;
- str->buffer = (char*) malloc(sizeof(char) * str->size);
- str->buffer[0] = '\0';
-}
-
-CuString* CuStringNew(void)
-{
- CuString* str = (CuString*) malloc(sizeof(CuString));
- str->length = 0;
- str->size = STRING_MAX;
- str->buffer = (char*) malloc(sizeof(char) * str->size);
- str->buffer[0] = '\0';
- return str;
-}
-
-void CuStringResize(CuString* str, int newSize)
-{
- str->buffer = (char*) realloc(str->buffer, sizeof(char) * newSize);
- str->size = newSize;
-}
-
-void CuStringAppend(CuString* str, const char* text)
-{
- int length;
-
- if (text == NULL) {
- text = "NULL";
- }
-
- length = (int)strlen(text);
- if (str->length + length + 1 >= str->size)
- CuStringResize(str, str->length + length + 1 + STRING_INC);
- str->length += length;
- strcat(str->buffer, text);
-}
-
-void CuStringAppendChar(CuString* str, char ch)
-{
- char text[2];
- text[0] = ch;
- text[1] = '\0';
- CuStringAppend(str, text);
-}
-
-void CuStringAppendFormat(CuString* str, const char* format, ...)
-{
- va_list argp;
- char buf[HUGE_STRING_LEN];
- va_start(argp, format);
- vsprintf(buf, format, argp);
- va_end(argp);
- CuStringAppend(str, buf);
-}
-
-void CuStringInsert(CuString* str, const char* text, int pos)
-{
- int length = (int)strlen(text);
- if (pos > str->length)
- pos = str->length;
- if (str->length + length + 1 >= str->size)
- CuStringResize(str, str->length + length + 1 + STRING_INC);
- memmove(str->buffer + pos + length, str->buffer + pos, (str->length - pos) + 1);
- str->length += length;
- memcpy(str->buffer + pos, text, length);
-}
-
-/*-------------------------------------------------------------------------*
- * CuTest
- *-------------------------------------------------------------------------*/
-
-void CuTestInit(CuTest* t, const char* name, TestFunction function)
-{
- t->name = CuStrCopy(name);
- t->failed = 0;
- t->ran = 0;
- t->message = NULL;
- t->function = function;
- t->jumpBuf = NULL;
-}
-
-CuTest* CuTestNew(const char* name, TestFunction function)
-{
- CuTest* tc = CU_ALLOC(CuTest);
- CuTestInit(tc, name, function);
- return tc;
-}
-
-void CuTestRun(CuTest* tc)
-{
- jmp_buf buf;
- tc->jumpBuf = &buf;
- if (setjmp(buf) == 0)
- {
- tc->ran = 1;
- (tc->function)(tc);
- }
- tc->jumpBuf = 0;
-}
-
-static void CuFailInternal(CuTest* tc, const char* file, int line, CuString* string)
-{
- char buf[HUGE_STRING_LEN];
-
- sprintf(buf, "%s:%d: ", file, line);
- CuStringInsert(string, buf, 0);
-
- tc->failed = 1;
- tc->message = string->buffer;
- if (tc->jumpBuf != 0) longjmp(*(tc->jumpBuf), 0);
-}
-
-void CuFail_Line(CuTest* tc, const char* file, int line, const char* message2, const char* message)
-{
- CuString string;
-
- CuStringInit(&string);
- if (message2 != NULL)
- {
- CuStringAppend(&string, message2);
- CuStringAppend(&string, ": ");
- }
- CuStringAppend(&string, message);
- CuFailInternal(tc, file, line, &string);
-}
-
-void CuAssert_Line(CuTest* tc, const char* file, int line, const char* message, int condition)
-{
- if (condition) return;
- CuFail_Line(tc, file, line, NULL, message);
-}
-
-void CuAssertStrEquals_LineMsg(CuTest* tc, const char* file, int line, const char* message,
- const char* expected, const char* actual)
-{
- CuString string;
- if ((expected == NULL && actual == NULL) ||
- (expected != NULL && actual != NULL &&
- strcmp(expected, actual) == 0))
- {
- return;
- }
-
- CuStringInit(&string);
- if (message != NULL)
- {
- CuStringAppend(&string, message);
- CuStringAppend(&string, ": ");
- }
- CuStringAppend(&string, "expected <");
- CuStringAppend(&string, expected);
- CuStringAppend(&string, "> but was <");
- CuStringAppend(&string, actual);
- CuStringAppend(&string, ">");
- CuFailInternal(tc, file, line, &string);
-}
-
-void CuAssertIntEquals_LineMsg(CuTest* tc, const char* file, int line, const char* message,
- int expected, int actual)
-{
- char buf[STRING_MAX];
- if (expected == actual) return;
- sprintf(buf, "expected <%d> but was <%d>", expected, actual);
- CuFail_Line(tc, file, line, message, buf);
-}
-
-void CuAssertDblEquals_LineMsg(CuTest* tc, const char* file, int line, const char* message,
- double expected, double actual, double delta)
-{
- char buf[STRING_MAX];
- if (fabs(expected - actual) <= delta) return;
- sprintf(buf, "expected <%lf> but was <%lf>", expected, actual);
- CuFail_Line(tc, file, line, message, buf);
-}
-
-void CuAssertPtrEquals_LineMsg(CuTest* tc, const char* file, int line, const char* message,
- void* expected, void* actual)
-{
- char buf[STRING_MAX];
- if (expected == actual) return;
- sprintf(buf, "expected pointer <0x%p> but was <0x%p>", expected, actual);
- CuFail_Line(tc, file, line, message, buf);
-}
-
-
-/*-------------------------------------------------------------------------*
- * CuSuite
- *-------------------------------------------------------------------------*/
-
-void CuSuiteInit(CuSuite* testSuite)
-{
- testSuite->count = 0;
- testSuite->failCount = 0;
-}
-
-CuSuite* CuSuiteNew(void)
-{
- CuSuite* testSuite = CU_ALLOC(CuSuite);
- CuSuiteInit(testSuite);
- return testSuite;
-}
-
-void CuSuiteAdd(CuSuite* testSuite, CuTest *testCase)
-{
- assert(testSuite->count < MAX_TEST_CASES);
- testSuite->list[testSuite->count] = testCase;
- testSuite->count++;
-}
-
-void CuSuiteAddSuite(CuSuite* testSuite, CuSuite* testSuite2)
-{
- int i;
- for (i = 0 ; i < testSuite2->count ; ++i)
- {
- CuTest* testCase = testSuite2->list[i];
- CuSuiteAdd(testSuite, testCase);
- }
-}
-
-void CuSuiteRun(CuSuite* testSuite)
-{
- int i;
- for (i = 0 ; i < testSuite->count ; ++i)
- {
- CuTest* testCase = testSuite->list[i];
- CuTestRun(testCase);
- if (testCase->failed) { testSuite->failCount += 1; }
- }
-}
-
-void CuSuiteSummary(CuSuite* testSuite, CuString* summary)
-{
- int i;
- for (i = 0 ; i < testSuite->count ; ++i)
- {
- CuTest* testCase = testSuite->list[i];
- CuStringAppend(summary, testCase->failed ? "F" : ".");
- }
- CuStringAppend(summary, "\n\n");
-}
-
-void CuSuiteDetails(CuSuite* testSuite, CuString* details)
-{
- int i;
- int failCount = 0;
-
- if (testSuite->failCount == 0)
- {
- int passCount = testSuite->count - testSuite->failCount;
- const char* testWord = passCount == 1 ? "test" : "tests";
- CuStringAppendFormat(details, "OK (%d %s)\n", passCount, testWord);
- }
- else
- {
- if (testSuite->failCount == 1)
- CuStringAppend(details, "There was 1 failure:\n");
- else
- CuStringAppendFormat(details, "There were %d failures:\n", testSuite->failCount);
-
- for (i = 0 ; i < testSuite->count ; ++i)
- {
- CuTest* testCase = testSuite->list[i];
- if (testCase->failed)
- {
- failCount++;
- CuStringAppendFormat(details, "%d) %s: %s\n",
- failCount, testCase->name, testCase->message);
- }
- }
- CuStringAppend(details, "\n!!!FAILURES!!!\n");
-
- CuStringAppendFormat(details, "Runs: %d ", testSuite->count);
- CuStringAppendFormat(details, "Passes: %d ", testSuite->count - testSuite->failCount);
- CuStringAppendFormat(details, "Fails: %d\n", testSuite->failCount);
- }
-}
diff --git a/src/external/cutest/CuTest.h b/src/external/cutest/CuTest.h
deleted file mode 100644
index 78c414687..000000000
--- a/src/external/cutest/CuTest.h
+++ /dev/null
@@ -1,111 +0,0 @@
-#ifndef CU_TEST_H
-#define CU_TEST_H
-
-#include
-#include
-
-/* CuString */
-
-char* CuStrAlloc(int size);
-char* CuStrCopy(const char* old);
-
-#define CU_ALLOC(TYPE) ((TYPE*) malloc(sizeof(TYPE)))
-
-#define HUGE_STRING_LEN 8192
-#define STRING_MAX 256
-#define STRING_INC 256
-
-typedef struct
-{
- int length;
- int size;
- char* buffer;
-} CuString;
-
-void CuStringInit(CuString* str);
-CuString* CuStringNew(void);
-void CuStringRead(CuString* str, const char* path);
-void CuStringAppend(CuString* str, const char* text);
-void CuStringAppendChar(CuString* str, char ch);
-void CuStringAppendFormat(CuString* str, const char* format, ...);
-void CuStringInsert(CuString* str, const char* text, int pos);
-void CuStringResize(CuString* str, int newSize);
-
-/* CuTest */
-
-typedef struct CuTest CuTest;
-
-typedef void (*TestFunction)(CuTest *);
-
-struct CuTest
-{
- const char* name;
- TestFunction function;
- int failed;
- int ran;
- const char* message;
- jmp_buf *jumpBuf;
-};
-
-void CuTestInit(CuTest* t, const char* name, TestFunction function);
-CuTest* CuTestNew(const char* name, TestFunction function);
-void CuTestRun(CuTest* tc);
-
-/* Internal versions of assert functions -- use the public versions */
-void CuFail_Line(CuTest* tc, const char* file, int line, const char* message2, const char* message);
-void CuAssert_Line(CuTest* tc, const char* file, int line, const char* message, int condition);
-void CuAssertStrEquals_LineMsg(CuTest* tc,
- const char* file, int line, const char* message,
- const char* expected, const char* actual);
-void CuAssertIntEquals_LineMsg(CuTest* tc,
- const char* file, int line, const char* message,
- int expected, int actual);
-void CuAssertDblEquals_LineMsg(CuTest* tc,
- const char* file, int line, const char* message,
- double expected, double actual, double delta);
-void CuAssertPtrEquals_LineMsg(CuTest* tc,
- const char* file, int line, const char* message,
- void* expected, void* actual);
-
-/* public assert functions */
-
-#define CuFail(tc, ms) CuFail_Line( (tc), __FILE__, __LINE__, NULL, (ms))
-#define CuAssert(tc, ms, cond) CuAssert_Line((tc), __FILE__, __LINE__, (ms), (cond))
-#define CuAssertTrue(tc, cond) CuAssert_Line((tc), __FILE__, __LINE__, "assert failed", (cond))
-
-#define CuAssertStrEquals(tc,ex,ac) CuAssertStrEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac))
-#define CuAssertStrEquals_Msg(tc,ms,ex,ac) CuAssertStrEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac))
-#define CuAssertIntEquals(tc,ex,ac) CuAssertIntEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac))
-#define CuAssertIntEquals_Msg(tc,ms,ex,ac) CuAssertIntEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac))
-#define CuAssertDblEquals(tc,ex,ac,dl) CuAssertDblEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac),(dl))
-#define CuAssertDblEquals_Msg(tc,ms,ex,ac,dl) CuAssertDblEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac),(dl))
-#define CuAssertPtrEquals(tc,ex,ac) CuAssertPtrEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac))
-#define CuAssertPtrEquals_Msg(tc,ms,ex,ac) CuAssertPtrEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac))
-
-#define CuAssertPtrNotNull(tc,p) CuAssert_Line((tc),__FILE__,__LINE__,"null pointer unexpected",(p != NULL))
-#define CuAssertPtrNotNullMsg(tc,msg,p) CuAssert_Line((tc),__FILE__,__LINE__,(msg),(p != NULL))
-
-/* CuSuite */
-
-#define MAX_TEST_CASES 1024
-
-#define SUITE_ADD_TEST(SUITE,TEST) CuSuiteAdd(SUITE, CuTestNew(#TEST, TEST))
-
-typedef struct
-{
- int count;
- CuTest* list[MAX_TEST_CASES];
- int failCount;
-
-} CuSuite;
-
-
-void CuSuiteInit(CuSuite* testSuite);
-CuSuite* CuSuiteNew(void);
-void CuSuiteAdd(CuSuite* testSuite, CuTest *testCase);
-void CuSuiteAddSuite(CuSuite* testSuite, CuSuite* testSuite2);
-void CuSuiteRun(CuSuite* testSuite);
-void CuSuiteSummary(CuSuite* testSuite, CuString* summary);
-void CuSuiteDetails(CuSuite* testSuite, CuString* details);
-
-#endif /* CU_TEST_H */
diff --git a/src/external/cutest/CuTestTest.c b/src/external/cutest/CuTestTest.c
deleted file mode 100644
index 547f1195a..000000000
--- a/src/external/cutest/CuTestTest.c
+++ /dev/null
@@ -1,709 +0,0 @@
-#include
-#include
-#include
-#include
-#include
-
-#include "CuTest.h"
-
-/*-------------------------------------------------------------------------*
- * Helper functions
- *-------------------------------------------------------------------------*/
-
-#define CompareAsserts(tc, message, expected, actual) X_CompareAsserts((tc), __FILE__, __LINE__, (message), (expected), (actual))
-
-static void X_CompareAsserts(CuTest* tc, const char *file, int line, const char* message, const char* expected, const char* actual)
-{
- int mismatch;
- if (expected == NULL || actual == NULL) {
- mismatch = (expected != NULL || actual != NULL);
- } else {
- const char *front = __FILE__ ":";
- const size_t frontLen = strlen(front);
- const size_t expectedLen = strlen(expected);
-
- const char *matchStr = actual;
-
- mismatch = (strncmp(matchStr, front, frontLen) != 0);
- if (!mismatch) {
- matchStr = strchr(matchStr + frontLen, ':');
- mismatch |= (matchStr == NULL || strncmp(matchStr, ": ", 2));
- if (!mismatch) {
- matchStr += 2;
- mismatch |= (strncmp(matchStr, expected, expectedLen) != 0);
- }
- }
- }
-
- CuAssert_Line(tc, file, line, message, !mismatch);
-}
-
-/*-------------------------------------------------------------------------*
- * CuString Test
- *-------------------------------------------------------------------------*/
-
-void TestCuStringNew(CuTest* tc)
-{
- CuString* str = CuStringNew();
- CuAssertTrue(tc, 0 == str->length);
- CuAssertTrue(tc, 0 != str->size);
- CuAssertStrEquals(tc, "", str->buffer);
-}
-
-
-void TestCuStringAppend(CuTest* tc)
-{
- CuString* str = CuStringNew();
- CuStringAppend(str, "hello");
- CuAssertIntEquals(tc, 5, str->length);
- CuAssertStrEquals(tc, "hello", str->buffer);
- CuStringAppend(str, " world");
- CuAssertIntEquals(tc, 11, str->length);
- CuAssertStrEquals(tc, "hello world", str->buffer);
-}
-
-
-void TestCuStringAppendNULL(CuTest* tc)
-{
- CuString* str = CuStringNew();
- CuStringAppend(str, NULL);
- CuAssertIntEquals(tc, 4, str->length);
- CuAssertStrEquals(tc, "NULL", str->buffer);
-}
-
-
-void TestCuStringAppendChar(CuTest* tc)
-{
- CuString* str = CuStringNew();
- CuStringAppendChar(str, 'a');
- CuStringAppendChar(str, 'b');
- CuStringAppendChar(str, 'c');
- CuStringAppendChar(str, 'd');
- CuAssertIntEquals(tc, 4, str->length);
- CuAssertStrEquals(tc, "abcd", str->buffer);
-}
-
-
-void TestCuStringInserts(CuTest* tc)
-{
- CuString* str = CuStringNew();
- CuStringAppend(str, "world");
- CuAssertIntEquals(tc, 5, str->length);
- CuAssertStrEquals(tc, "world", str->buffer);
- CuStringInsert(str, "hell", 0);
- CuAssertIntEquals(tc, 9, str->length);
- CuAssertStrEquals(tc, "hellworld", str->buffer);
- CuStringInsert(str, "o ", 4);
- CuAssertIntEquals(tc, 11, str->length);
- CuAssertStrEquals(tc, "hello world", str->buffer);
- CuStringInsert(str, "!", 11);
- CuAssertIntEquals(tc, 12, str->length);
- CuAssertStrEquals(tc, "hello world!", str->buffer);
-}
-
-
-void TestCuStringResizes(CuTest* tc)
-{
- CuString* str = CuStringNew();
- int i;
- for(i = 0 ; i < STRING_MAX ; ++i)
- {
- CuStringAppend(str, "aa");
- }
- CuAssertTrue(tc, STRING_MAX * 2 == str->length);
- CuAssertTrue(tc, STRING_MAX * 2 <= str->size);
-}
-
-CuSuite* CuStringGetSuite(void)
-{
- CuSuite* suite = CuSuiteNew();
-
- SUITE_ADD_TEST(suite, TestCuStringNew);
- SUITE_ADD_TEST(suite, TestCuStringAppend);
- SUITE_ADD_TEST(suite, TestCuStringAppendNULL);
- SUITE_ADD_TEST(suite, TestCuStringAppendChar);
- SUITE_ADD_TEST(suite, TestCuStringInserts);
- SUITE_ADD_TEST(suite, TestCuStringResizes);
-
- return suite;
-}
-
-/*-------------------------------------------------------------------------*
- * CuTest Test
- *-------------------------------------------------------------------------*/
-
-void TestPasses(CuTest* tc)
-{
- CuAssert(tc, "test should pass", 1 == 0 + 1);
-}
-
-void zTestFails(CuTest* tc)
-{
- CuAssert(tc, "test should fail", 1 == 1 + 1);
-}
-
-
-void TestCuTestNew(CuTest* tc)
-{
- CuTest* tc2 = CuTestNew("MyTest", TestPasses);
- CuAssertStrEquals(tc, "MyTest", tc2->name);
- CuAssertTrue(tc, !tc2->failed);
- CuAssertTrue(tc, tc2->message == NULL);
- CuAssertTrue(tc, tc2->function == TestPasses);
- CuAssertTrue(tc, tc2->ran == 0);
- CuAssertTrue(tc, tc2->jumpBuf == NULL);
-}
-
-
-void TestCuTestInit(CuTest *tc)
-{
- CuTest tc2;
- CuTestInit(&tc2, "MyTest", TestPasses);
- CuAssertStrEquals(tc, "MyTest", tc2.name);
- CuAssertTrue(tc, !tc2.failed);
- CuAssertTrue(tc, tc2.message == NULL);
- CuAssertTrue(tc, tc2.function == TestPasses);
- CuAssertTrue(tc, tc2.ran == 0);
- CuAssertTrue(tc, tc2.jumpBuf == NULL);
-}
-
-void TestCuAssert(CuTest* tc)
-{
- CuTest tc2;
- CuTestInit(&tc2, "MyTest", TestPasses);
-
- CuAssert(&tc2, "test 1", 5 == 4 + 1);
- CuAssertTrue(tc, !tc2.failed);
- CuAssertTrue(tc, tc2.message == NULL);
-
- CuAssert(&tc2, "test 2", 0);
- CuAssertTrue(tc, tc2.failed);
- CompareAsserts(tc, "CuAssert didn't fail", "test 2", tc2.message);
-
- CuAssert(&tc2, "test 3", 1);
- CuAssertTrue(tc, tc2.failed);
- CompareAsserts(tc, "CuAssert didn't fail", "test 2", tc2.message);
-
- CuAssert(&tc2, "test 4", 0);
- CuAssertTrue(tc, tc2.failed);
- CompareAsserts(tc, "CuAssert didn't fail", "test 4", tc2.message);
-
-}
-
-void TestCuAssertPtrEquals_Success(CuTest* tc)
-{
- CuTest tc2;
- int x;
-
- CuTestInit(&tc2, "MyTest", TestPasses);
-
- /* test success case */
- CuAssertPtrEquals(&tc2, &x, &x);
- CuAssertTrue(tc, ! tc2.failed);
- CuAssertTrue(tc, NULL == tc2.message);
-}
-
-void TestCuAssertPtrEquals_Failure(CuTest* tc)
-{
- CuTest tc2;
- int x;
- int* nullPtr = NULL;
- char expected_message[STRING_MAX];
-
- CuTestInit(&tc2, "MyTest", TestPasses);
-
- /* test failing case */
- sprintf(expected_message, "expected pointer <0x%p> but was <0x%p>", nullPtr, &x);
- CuAssertPtrEquals(&tc2, NULL, &x);
- CuAssertTrue(tc, tc2.failed);
- CompareAsserts(tc, "CuAssertPtrEquals failed", expected_message, tc2.message);
-}
-
-void TestCuAssertPtrNotNull_Success(CuTest* tc)
-{
- CuTest tc2;
- int x;
-
- CuTestInit(&tc2, "MyTest", TestPasses);
-
- /* test success case */
- CuAssertPtrNotNull(&tc2, &x);
- CuAssertTrue(tc, ! tc2.failed);
- CuAssertTrue(tc, NULL == tc2.message);
-}
-
-void TestCuAssertPtrNotNull_Failure(CuTest* tc)
-{
- CuTest tc2;
-
- CuTestInit(&tc2, "MyTest", TestPasses);
-
- /* test failing case */
- CuAssertPtrNotNull(&tc2, NULL);
- CuAssertTrue(tc, tc2.failed);
- CompareAsserts(tc, "CuAssertPtrNotNull failed", "null pointer unexpected", tc2.message);
-}
-
-void TestCuTestRun(CuTest* tc)
-{
- CuTest tc2;
- CuTestInit(&tc2, "MyTest", zTestFails);
- CuTestRun(&tc2);
-
- CuAssertStrEquals(tc, "MyTest", tc2.name);
- CuAssertTrue(tc, tc2.failed);
- CuAssertTrue(tc, tc2.ran);
- CompareAsserts(tc, "TestRun failed", "test should fail", tc2.message);
-}
-
-/*-------------------------------------------------------------------------*
- * CuSuite Test
- *-------------------------------------------------------------------------*/
-
-void TestCuSuiteInit(CuTest* tc)
-{
- CuSuite ts;
- CuSuiteInit(&ts);
- CuAssertTrue(tc, ts.count == 0);
- CuAssertTrue(tc, ts.failCount == 0);
-}
-
-void TestCuSuiteNew(CuTest* tc)
-{
- CuSuite* ts = CuSuiteNew();
- CuAssertTrue(tc, ts->count == 0);
- CuAssertTrue(tc, ts->failCount == 0);
-}
-
-void TestCuSuiteAddTest(CuTest* tc)
-{
- CuSuite ts;
- CuTest tc2;
-
- CuSuiteInit(&ts);
- CuTestInit(&tc2, "MyTest", zTestFails);
-
- CuSuiteAdd(&ts, &tc2);
- CuAssertTrue(tc, ts.count == 1);
-
- CuAssertStrEquals(tc, "MyTest", ts.list[0]->name);
-}
-
-void TestCuSuiteAddSuite(CuTest* tc)
-{
- CuSuite* ts1 = CuSuiteNew();
- CuSuite* ts2 = CuSuiteNew();
-
- CuSuiteAdd(ts1, CuTestNew("TestFails1", zTestFails));
- CuSuiteAdd(ts1, CuTestNew("TestFails2", zTestFails));
-
- CuSuiteAdd(ts2, CuTestNew("TestFails3", zTestFails));
- CuSuiteAdd(ts2, CuTestNew("TestFails4", zTestFails));
-
- CuSuiteAddSuite(ts1, ts2);
- CuAssertIntEquals(tc, 4, ts1->count);
-
- CuAssertStrEquals(tc, "TestFails1", ts1->list[0]->name);
- CuAssertStrEquals(tc, "TestFails2", ts1->list[1]->name);
- CuAssertStrEquals(tc, "TestFails3", ts1->list[2]->name);
- CuAssertStrEquals(tc, "TestFails4", ts1->list[3]->name);
-}
-
-void TestCuSuiteRun(CuTest* tc)
-{
- CuSuite ts;
- CuTest tc1, tc2, tc3, tc4;
-
- CuSuiteInit(&ts);
- CuTestInit(&tc1, "TestPasses", TestPasses);
- CuTestInit(&tc2, "TestPasses", TestPasses);
- CuTestInit(&tc3, "TestFails", zTestFails);
- CuTestInit(&tc4, "TestFails", zTestFails);
-
- CuSuiteAdd(&ts, &tc1);
- CuSuiteAdd(&ts, &tc2);
- CuSuiteAdd(&ts, &tc3);
- CuSuiteAdd(&ts, &tc4);
- CuAssertTrue(tc, ts.count == 4);
-
- CuSuiteRun(&ts);
- CuAssertTrue(tc, ts.count - ts.failCount == 2);
- CuAssertTrue(tc, ts.failCount == 2);
-}
-
-void TestCuSuiteSummary(CuTest* tc)
-{
- CuSuite ts;
- CuTest tc1, tc2;
- CuString summary;
-
- CuSuiteInit(&ts);
- CuTestInit(&tc1, "TestPasses", TestPasses);
- CuTestInit(&tc2, "TestFails", zTestFails);
- CuStringInit(&summary);
-
- CuSuiteAdd(&ts, &tc1);
- CuSuiteAdd(&ts, &tc2);
- CuSuiteRun(&ts);
-
- CuSuiteSummary(&ts, &summary);
-
- CuAssertTrue(tc, ts.count == 2);
- CuAssertTrue(tc, ts.failCount == 1);
- CuAssertStrEquals(tc, ".F\n\n", summary.buffer);
-}
-
-
-void TestCuSuiteDetails_SingleFail(CuTest* tc)
-{
- CuSuite ts;
- CuTest tc1, tc2;
- CuString details;
- const char* front;
- const char* back;
-
- CuSuiteInit(&ts);
- CuTestInit(&tc1, "TestPasses", TestPasses);
- CuTestInit(&tc2, "TestFails", zTestFails);
- CuStringInit(&details);
-
- CuSuiteAdd(&ts, &tc1);
- CuSuiteAdd(&ts, &tc2);
- CuSuiteRun(&ts);
-
- CuSuiteDetails(&ts, &details);
-
- CuAssertTrue(tc, ts.count == 2);
- CuAssertTrue(tc, ts.failCount == 1);
-
- front = "There was 1 failure:\n"
- "1) TestFails: ";
- back = "test should fail\n"
- "\n!!!FAILURES!!!\n"
- "Runs: 2 Passes: 1 Fails: 1\n";
-
- CuAssertStrEquals(tc, back, details.buffer + strlen(details.buffer) - strlen(back));
- details.buffer[strlen(front)] = 0;
- CuAssertStrEquals(tc, front, details.buffer);
-}
-
-
-void TestCuSuiteDetails_SinglePass(CuTest* tc)
-{
- CuSuite ts;
- CuTest tc1;
- CuString details;
- const char* expected;
-
- CuSuiteInit(&ts);
- CuTestInit(&tc1, "TestPasses", TestPasses);
- CuStringInit(&details);
-
- CuSuiteAdd(&ts, &tc1);
- CuSuiteRun(&ts);
-
- CuSuiteDetails(&ts, &details);
-
- CuAssertTrue(tc, ts.count == 1);
- CuAssertTrue(tc, ts.failCount == 0);
-
- expected =
- "OK (1 test)\n";
-
- CuAssertStrEquals(tc, expected, details.buffer);
-}
-
-void TestCuSuiteDetails_MultiplePasses(CuTest* tc)
-{
- CuSuite ts;
- CuTest tc1, tc2;
- CuString details;
- const char* expected;
-
- CuSuiteInit(&ts);
- CuTestInit(&tc1, "TestPasses", TestPasses);
- CuTestInit(&tc2, "TestPasses", TestPasses);
- CuStringInit(&details);
-
- CuSuiteAdd(&ts, &tc1);
- CuSuiteAdd(&ts, &tc2);
- CuSuiteRun(&ts);
-
- CuSuiteDetails(&ts, &details);
-
- CuAssertTrue(tc, ts.count == 2);
- CuAssertTrue(tc, ts.failCount == 0);
-
- expected =
- "OK (2 tests)\n";
-
- CuAssertStrEquals(tc, expected, details.buffer);
-}
-
-void TestCuSuiteDetails_MultipleFails(CuTest* tc)
-{
- CuSuite ts;
- CuTest tc1, tc2;
- CuString details;
- const char* front;
- const char* mid;
- const char* back;
-
- CuSuiteInit(&ts);
- CuTestInit(&tc1, "TestFails1", zTestFails);
- CuTestInit(&tc2, "TestFails2", zTestFails);
- CuStringInit(&details);
-
- CuSuiteAdd(&ts, &tc1);
- CuSuiteAdd(&ts, &tc2);
- CuSuiteRun(&ts);
-
- CuSuiteDetails(&ts, &details);
-
- CuAssertTrue(tc, ts.count == 2);
- CuAssertTrue(tc, ts.failCount == 2);
-
- front =
- "There were 2 failures:\n"
- "1) TestFails1: ";
- mid = "test should fail\n"
- "2) TestFails2: ";
- back = "test should fail\n"
- "\n!!!FAILURES!!!\n"
- "Runs: 2 Passes: 0 Fails: 2\n";
-
- CuAssertStrEquals(tc, back, details.buffer + strlen(details.buffer) - strlen(back));
- CuAssert(tc, "Couldn't find middle", strstr(details.buffer, mid) != NULL);
- details.buffer[strlen(front)] = 0;
- CuAssertStrEquals(tc, front, details.buffer);
-}
-
-
-/*-------------------------------------------------------------------------*
- * Misc Test
- *-------------------------------------------------------------------------*/
-
-void TestCuStrCopy(CuTest* tc)
-{
- const char* old = "hello world";
- const char* newStr = CuStrCopy(old);
- CuAssert(tc, "old is new", strcmp(old, newStr) == 0);
-}
-
-
-void TestCuStringAppendFormat(CuTest* tc)
-{
- int i;
- char* text = CuStrAlloc(301); /* long string */
- CuString* str = CuStringNew();
- for (i = 0 ; i < 300 ; ++i)
- text[i] = 'a';
- text[300] = '\0';
- CuStringAppendFormat(str, "%s", text);
-
- /* buffer limit raised to HUGE_STRING_LEN so no overflow */
-
- CuAssert(tc, "length of str->buffer is 300", 300 == strlen(str->buffer));
-}
-
-void TestFail(CuTest* tc)
-{
- jmp_buf buf;
- int pointReached = 0;
- CuTest* tc2 = CuTestNew("TestFails", zTestFails);
- tc2->jumpBuf = &buf;
- if (setjmp(buf) == 0)
- {
- CuFail(tc2, "hello world");
- pointReached = 1;
- }
- CuAssert(tc, "point was not reached", pointReached == 0);
-}
-
-void TestAssertStrEquals(CuTest* tc)
-{
- jmp_buf buf;
- CuTest *tc2 = CuTestNew("TestAssertStrEquals", zTestFails);
-
- const char* expected = "expected but was ";
- const char *expectedMsg = "some text: expected but was ";
-
- tc2->jumpBuf = &buf;
- if (setjmp(buf) == 0)
- {
- CuAssertStrEquals(tc2, "hello", "world");
- }
- CuAssertTrue(tc, tc2->failed);
- CompareAsserts(tc, "CuAssertStrEquals failed", expected, tc2->message);
- if (setjmp(buf) == 0)
- {
- CuAssertStrEquals_Msg(tc2, "some text", "hello", "world");
- }
- CuAssertTrue(tc, tc2->failed);
- CompareAsserts(tc, "CuAssertStrEquals failed", expectedMsg, tc2->message);
-}
-
-void TestAssertStrEquals_NULL(CuTest* tc)
-{
- jmp_buf buf;
- CuTest *tc2 = CuTestNew("TestAssertStrEquals_NULL", zTestFails);
-
- tc2->jumpBuf = &buf;
- if (setjmp(buf) == 0)
- {
- CuAssertStrEquals(tc2, NULL, NULL);
- }
- CuAssertTrue(tc, !tc2->failed);
- CompareAsserts(tc, "CuAssertStrEquals_NULL failed", NULL, tc2->message);
- if (setjmp(buf) == 0)
- {
- CuAssertStrEquals_Msg(tc2, "some text", NULL, NULL);
- }
- CuAssertTrue(tc, !tc2->failed);
- CompareAsserts(tc, "CuAssertStrEquals_NULL failed", NULL, tc2->message);
-}
-
-void TestAssertStrEquals_FailNULLStr(CuTest* tc)
-{
- jmp_buf buf;
- CuTest *tc2 = CuTestNew("TestAssertStrEquals_FailNULLStr", zTestFails);
-
- const char* expected = "expected but was ";
- const char *expectedMsg = "some text: expected but was ";
-
- tc2->jumpBuf = &buf;
- if (setjmp(buf) == 0)
- {
- CuAssertStrEquals(tc2, "hello", NULL);
- }
- CuAssertTrue(tc, tc2->failed);
- CompareAsserts(tc, "CuAssertStrEquals_FailNULLStr failed", expected, tc2->message);
- if (setjmp(buf) == 0)
- {
- CuAssertStrEquals_Msg(tc2, "some text", "hello", NULL);
- }
- CuAssertTrue(tc, tc2->failed);
- CompareAsserts(tc, "CuAssertStrEquals_FailNULLStr failed", expectedMsg, tc2->message);
-}
-
-void TestAssertStrEquals_FailStrNULL(CuTest* tc)
-{
- jmp_buf buf;
- CuTest *tc2 = CuTestNew("TestAssertStrEquals_FailStrNULL", zTestFails);
-
- const char* expected = "expected but was ";
- const char *expectedMsg = "some text: expected but was ";
-
- tc2->jumpBuf = &buf;
- if (setjmp(buf) == 0)
- {
- CuAssertStrEquals(tc2, NULL, "hello");
- }
- CuAssertTrue(tc, tc2->failed);
- CompareAsserts(tc, "CuAssertStrEquals_FailStrNULL failed", expected, tc2->message);
- if (setjmp(buf) == 0)
- {
- CuAssertStrEquals_Msg(tc2, "some text", NULL, "hello");
- }
- CuAssertTrue(tc, tc2->failed);
- CompareAsserts(tc, "CuAssertStrEquals_FailStrNULL failed", expectedMsg, tc2->message);
-}
-
-void TestAssertIntEquals(CuTest* tc)
-{
- jmp_buf buf;
- CuTest *tc2 = CuTestNew("TestAssertIntEquals", zTestFails);
- const char* expected = "expected <42> but was <32>";
- const char* expectedMsg = "some text: expected <42> but was <32>";
- tc2->jumpBuf = &buf;
- if (setjmp(buf) == 0)
- {
- CuAssertIntEquals(tc2, 42, 32);
- }
- CuAssertTrue(tc, tc2->failed);
- CompareAsserts(tc, "CuAssertIntEquals failed", expected, tc2->message);
- if (setjmp(buf) == 0)
- {
- CuAssertIntEquals_Msg(tc2, "some text", 42, 32);
- }
- CuAssertTrue(tc, tc2->failed);
- CompareAsserts(tc, "CuAssertStrEquals failed", expectedMsg, tc2->message);
-}
-
-void TestAssertDblEquals(CuTest* tc)
-{
- jmp_buf buf;
- double x = 3.33;
- double y = 10.0 / 3.0;
- CuTest *tc2 = CuTestNew("TestAssertDblEquals", zTestFails);
- char expected[STRING_MAX];
- char expectedMsg[STRING_MAX];
- sprintf(expected, "expected <%lf> but was <%lf>", x, y);
- sprintf(expectedMsg, "some text: expected <%lf> but was <%lf>", x, y);
-
- CuTestInit(tc2, "TestAssertDblEquals", TestPasses);
-
- CuAssertDblEquals(tc2, x, x, 0.0);
- CuAssertTrue(tc, ! tc2->failed);
- CuAssertTrue(tc, NULL == tc2->message);
-
- CuAssertDblEquals(tc2, x, y, 0.01);
- CuAssertTrue(tc, ! tc2->failed);
- CuAssertTrue(tc, NULL == tc2->message);
-
- tc2->jumpBuf = &buf;
- if (setjmp(buf) == 0)
- {
- CuAssertDblEquals(tc2, x, y, 0.001);
- }
- CuAssertTrue(tc, tc2->failed);
- CompareAsserts(tc, "CuAssertDblEquals failed", expected, tc2->message);
- tc2->jumpBuf = &buf;
- if (setjmp(buf) == 0)
- {
- CuAssertDblEquals_Msg(tc2, "some text", x, y, 0.001);
- }
- CuAssertTrue(tc, tc2->failed);
- CompareAsserts(tc, "CuAssertDblEquals failed", expectedMsg, tc2->message);
-}
-
-/*-------------------------------------------------------------------------*
- * main
- *-------------------------------------------------------------------------*/
-
-CuSuite* CuGetSuite(void)
-{
- CuSuite* suite = CuSuiteNew();
-
- SUITE_ADD_TEST(suite, TestCuStringAppendFormat);
- SUITE_ADD_TEST(suite, TestCuStrCopy);
- SUITE_ADD_TEST(suite, TestFail);
- SUITE_ADD_TEST(suite, TestAssertStrEquals);
- SUITE_ADD_TEST(suite, TestAssertStrEquals_NULL);
- SUITE_ADD_TEST(suite, TestAssertStrEquals_FailStrNULL);
- SUITE_ADD_TEST(suite, TestAssertStrEquals_FailNULLStr);
- SUITE_ADD_TEST(suite, TestAssertIntEquals);
- SUITE_ADD_TEST(suite, TestAssertDblEquals);
-
- SUITE_ADD_TEST(suite, TestCuTestNew);
- SUITE_ADD_TEST(suite, TestCuTestInit);
- SUITE_ADD_TEST(suite, TestCuAssert);
- SUITE_ADD_TEST(suite, TestCuAssertPtrEquals_Success);
- SUITE_ADD_TEST(suite, TestCuAssertPtrEquals_Failure);
- SUITE_ADD_TEST(suite, TestCuAssertPtrNotNull_Success);
- SUITE_ADD_TEST(suite, TestCuAssertPtrNotNull_Failure);
- SUITE_ADD_TEST(suite, TestCuTestRun);
-
- SUITE_ADD_TEST(suite, TestCuSuiteInit);
- SUITE_ADD_TEST(suite, TestCuSuiteNew);
- SUITE_ADD_TEST(suite, TestCuSuiteAddTest);
- SUITE_ADD_TEST(suite, TestCuSuiteAddSuite);
- SUITE_ADD_TEST(suite, TestCuSuiteRun);
- SUITE_ADD_TEST(suite, TestCuSuiteSummary);
- SUITE_ADD_TEST(suite, TestCuSuiteDetails_SingleFail);
- SUITE_ADD_TEST(suite, TestCuSuiteDetails_SinglePass);
- SUITE_ADD_TEST(suite, TestCuSuiteDetails_MultiplePasses);
- SUITE_ADD_TEST(suite, TestCuSuiteDetails_MultipleFails);
-
- return suite;
-}
diff --git a/src/external/cutest/README b/src/external/cutest/README
deleted file mode 100644
index 8bc154099..000000000
--- a/src/external/cutest/README
+++ /dev/null
@@ -1,209 +0,0 @@
-HOW TO USE
-
-You can use CuTest to create unit tests to drive your development
-in the style of Extreme Programming. You can also add unit tests to
-existing code to ensure that it works as you suspect.
-
-Your unit tests are an investment. They let you to change your
-code and add new features confidently without worrying about
-accidentally breaking earlier features.
-
-
-LICENSING
-
-For details on licensing see license.txt.
-
-
-GETTING STARTED
-
-To add unit testing to your C code the only files you need are
-CuTest.c and CuTest.h.
-
-CuTestTest.c and AllTests.c have been included to provide an
-example of how to write unit tests and then how to aggregate them
-into suites and into a single AllTests.c file. Suites allow you
-to put group tests into logical sets. AllTests.c combines all the
-suites and runs them.
-
-You should not have to look inside CuTest.c. Looking in
-CuTestTest.c and AllTests.c (for example usage) should be
-sufficient.
-
-After downloading the sources, run your compiler to create an
-executable called AllTests.exe. For example, if you are using
-Windows with the cl.exe compiler you would type:
-
- cl.exe AllTests.c CuTest.c CuTestTest.c
- AllTests.exe
-
-This will run all the unit tests associated with CuTest and print
-the output on the console. You can replace cl.exe with gcc or
-your favorite compiler in the command above.
-
-
-DETAILED EXAMPLE
-
-Here is a more detailed example. We will work through a simple
-test first exercise. The goal is to create a library of string
-utilities. First, lets write a function that converts a
-null-terminated string to all upper case.
-
-Ensure that CuTest.c and CuTest.h are accessible from your C
-project. Next, create a file called StrUtil.c with these
-contents:
-
- #include "CuTest.h"
-
- char* StrToUpper(char* str) {
- return str;
- }
-
- void TestStrToUpper(CuTest *tc) {
- char* input = strdup("hello world");
- char* actual = StrToUpper(input);
- char* expected = "HELLO WORLD";
- CuAssertStrEquals(tc, expected, actual);
- }
-
- CuSuite* StrUtilGetSuite() {
- CuSuite* suite = CuSuiteNew();
- SUITE_ADD_TEST(suite, TestStrToUpper);
- return suite;
- }
-
-Create another file called AllTests.c with these contents:
-
- #include "CuTest.h"
-
- CuSuite* StrUtilGetSuite();
-
- void RunAllTests(void) {
- CuString *output = CuStringNew();
- CuSuite* suite = CuSuiteNew();
-
- CuSuiteAddSuite(suite, StrUtilGetSuite());
-
- CuSuiteRun(suite);
- CuSuiteSummary(suite, output);
- CuSuiteDetails(suite, output);
- printf("%s\n", output->buffer);
- }
-
- int main(void) {
- RunAllTests();
- }
-
-Then type this on the command line:
-
- gcc AllTests.c CuTest.c StrUtil.c
-
-to compile. You can replace gcc with your favorite compiler.
-CuTest should be portable enough to handle all Windows and Unix
-compilers. Then to run the tests type:
-
- a.out
-
-This will print an error because we haven't implemented the
-StrToUpper function correctly. We are just returning the string
-without changing it to upper case.
-
- char* StrToUpper(char* str) {
- return str;
- }
-
-Rewrite this as follows:
-
- char* StrToUpper(char* str) {
- char* p;
- for (p = str ; *p ; ++p) *p = toupper(*p);
- return str;
- }
-
-Recompile and run the tests again. The test should pass this
-time.
-
-
-WHAT TO DO NEXT
-
-At this point you might want to write more tests for the
-StrToUpper function. Here are some ideas:
-
-TestStrToUpper_EmptyString : pass in ""
-TestStrToUpper_UpperCase : pass in "HELLO WORLD"
-TestStrToUpper_MixedCase : pass in "HELLO world"
-TestStrToUpper_Numbers : pass in "1234 hello"
-
-As you write each one of these tests add it to StrUtilGetSuite
-function. If you don't the tests won't be run. Later as you write
-other functions and write tests for them be sure to include those
-in StrUtilGetSuite also. The StrUtilGetSuite function should
-include all the tests in StrUtil.c
-
-Over time you will create another file called FunkyStuff.c
-containing other functions unrelated to StrUtil. Follow the same
-pattern. Create a FunkyStuffGetSuite function in FunkyStuff.c.
-And add FunkyStuffGetSuite to AllTests.c.
-
-The framework is designed in the way it is so that it is easy to
-organize a lot of tests.
-
-THE BIG PICTURE
-
-Each individual test corresponds to a CuTest. These are grouped
-to form a CuSuite. CuSuites can hold CuTests or other CuSuites.
-AllTests.c collects all the CuSuites in the program into a single
-CuSuite which it then runs as a single CuSuite.
-
-The project is open source so feel free to take a peek under the
-hood at the CuTest.c file to see how it works. CuTestTest.c
-contains tests for CuTest.c. So CuTest tests itself.
-
-Since AllTests.c has a main() you will need to exclude this when
-you are building your product. Here is a nicer way to do this if
-you want to avoid messing with multiple builds. Remove the main()
-in AllTests.c. Note that it just calls RunAllTests(). Instead
-we'll call this directly from the main program.
-
-Now in the main() of the actual program check to see if the
-command line option "--test" was passed. If it was then I call
-RunAllTests() from AllTests.c. Otherwise run the real program.
-
-Shipping the tests with the code can be useful. If you customers
-complain about a problem you can ask them to run the unit tests
-and send you the output. This can help you to quickly isolate the
-piece of your system that is malfunctioning in the customer's
-environment.
-
-CuTest offers a rich set of CuAssert functions. Here is a list:
-
-void CuAssert(CuTest* tc, char* message, int condition);
-void CuAssertTrue(CuTest* tc, int condition);
-void CuAssertStrEquals(CuTest* tc, char* expected, char* actual);
-void CuAssertIntEquals(CuTest* tc, int expected, int actual);
-void CuAssertPtrEquals(CuTest* tc, void* expected, void* actual);
-void CuAssertPtrNotNull(CuTest* tc, void* pointer);
-
-The project is open source and so you can add other more powerful
-asserts to make your tests easier to write and more concise.
-Please feel free to send me changes you make so that I can
-incorporate them into future releases.
-
-If you see any errors in this document please contact me at
-asimjalis@peakprogramming.com.
-
-
-AUTOMATING TEST SUITE GENERATION
-
-make-tests.sh will grep through all the .c files in the current
-directory and generate the code to run all the tests contained in
-them. Using this script you don't have to worry about writing
-AllTests.c or dealing with any of the other suite code.
-
-
-CREDITS
-
-[02.23.2003] Dave Glowacki has added
-(1) file name and line numbers to the error messages, (2)
-AssertDblEquals for doubles, (3) AssertEquals_Msg version of
-all the AssertEquals to pass in optional message which is
-printed out on assert failure.
diff --git a/src/external/cutest/license.txt b/src/external/cutest/license.txt
deleted file mode 100644
index fd81689df..000000000
--- a/src/external/cutest/license.txt
+++ /dev/null
@@ -1,38 +0,0 @@
-NOTE
-
-The license is based on the zlib/libpng license. For more details see
-http://www.opensource.org/licenses/zlib-license.html. The intent of the
-license is to:
-
-- keep the license as simple as possible
-- encourage the use of CuTest in both free and commercial applications
- and libraries
-- keep the source code together
-- give credit to the CuTest contributors for their work
-
-If you ship CuTest in source form with your source distribution, the
-following license document must be included with it in unaltered form.
-If you find CuTest useful we would like to hear about it.
-
-LICENSE
-
-Copyright (c) 2003 Asim Jalis
-
-This software is provided 'as-is', without any express or implied
-warranty. In no event will the authors be held liable for any damages
-arising from the use of this software.
-
-Permission is granted to anyone to use this software for any purpose,
-including commercial applications, and to alter it and redistribute it
-freely, subject to the following restrictions:
-
-1. The origin of this software must not be misrepresented; you must not
-claim that you wrote the original software. If you use this software in
-a product, an acknowledgment in the product documentation would be
-appreciated but is not required.
-
-2. Altered source versions must be plainly marked as such, and must not
-be misrepresented as being the original software.
-
-3. This notice may not be removed or altered from any source
-distribution.
diff --git a/src/external/cutest/make-tests.sh b/src/external/cutest/make-tests.sh
deleted file mode 100644
index 736aa659c..000000000
--- a/src/external/cutest/make-tests.sh
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/usr/local/bin/bash
-
-# Auto generate single AllTests file for CuTest.
-# Searches through all *.c files in the current directory.
-# Prints to stdout.
-# Author: Asim Jalis
-# Date: 01/08/2003
-
-if test $# -eq 0 ; then FILES=*.c ; else FILES=$* ; fi
-
-echo '
-
-/* This is auto-generated code. Edit at your own peril. */
-
-#include "CuTest.h"
-
-'
-
-cat $FILES | grep '^void Test' |
- sed -e 's/(.*$//' \
- -e 's/$/(CuTest*);/' \
- -e 's/^/extern /'
-
-echo \
-'
-
-void RunAllTests(void)
-{
- CuString *output = CuStringNew();
- CuSuite* suite = CuSuiteNew();
-
-'
-cat $FILES | grep '^void Test' |
- sed -e 's/^void //' \
- -e 's/(.*$//' \
- -e 's/^/ SUITE_ADD_TEST(suite, /' \
- -e 's/$/);/'
-
-echo \
-'
- CuSuiteRun(suite);
- CuSuiteSummary(suite, output);
- CuSuiteDetails(suite, output);
- printf("%s\n", output->buffer);
-}
-
-int main(void)
-{
- RunAllTests();
-}
-'
diff --git a/src/external/dlmalloc/malloc.c b/src/external/dlmalloc/malloc.c
deleted file mode 100644
index b1e6c8992..000000000
--- a/src/external/dlmalloc/malloc.c
+++ /dev/null
@@ -1,5567 +0,0 @@
-/*
- This is a version (aka dlmalloc) of malloc/free/realloc written by
- Doug Lea and released to the public domain. Use, modify, and
- redistribute this code without permission or acknowledgement in any
- way you wish. Send questions, comments, complaints, performance
- data, etc to dl@cs.oswego.edu
-
-* VERSION 2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)
-
- Note: There may be an updated version of this malloc obtainable at
- ftp://gee.cs.oswego.edu/pub/misc/malloc.c
- Check before installing!
-
-* Quickstart
-
- This library is all in one file to simplify the most common usage:
- ftp it, compile it (-O), and link it into another program. All
- of the compile-time options default to reasonable values for use on
- most unix platforms. Compile -DWIN32 for reasonable defaults on windows.
- You might later want to step through various compile-time and dynamic
- tuning options.
-
- For convenience, an include file for code using this malloc is at:
- ftp://gee.cs.oswego.edu/pub/misc/malloc-2.7.1.h
- You don't really need this .h file unless you call functions not
- defined in your system include files. The .h file contains only the
- excerpts from this file needed for using this malloc on ANSI C/C++
- systems, so long as you haven't changed compile-time options about
- naming and tuning parameters. If you do, then you can create your
- own malloc.h that does include all settings by cutting at the point
- indicated below.
-
-* Why use this malloc?
-
- This is not the fastest, most space-conserving, most portable, or
- most tunable malloc ever written. However it is among the fastest
- while also being among the most space-conserving, portable and tunable.
- Consistent balance across these factors results in a good general-purpose
- allocator for malloc-intensive programs.
-
- The main properties of the algorithms are:
- * For large (>= 512 bytes) requests, it is a pure best-fit allocator,
- with ties normally decided via FIFO (i.e. least recently used).
- * For small (<= 64 bytes by default) requests, it is a caching
- allocator, that maintains pools of quickly recycled chunks.
- * In between, and for combinations of large and small requests, it does
- the best it can trying to meet both goals at once.
- * For very large requests (>= 128KB by default), it relies on system
- memory mapping facilities, if supported.
-
- For a longer but slightly out of date high-level description, see
- http://gee.cs.oswego.edu/dl/html/malloc.html
-
- You may already by default be using a C library containing a malloc
- that is based on some version of this malloc (for example in
- linux). You might still want to use the one in this file in order to
- customize settings or to avoid overheads associated with library
- versions.
-
-* Contents, described in more detail in "description of public routines" below.
-
- Standard (ANSI/SVID/...) functions:
- malloc(size_t n);
- calloc(size_t n_elements, size_t element_size);
- free(Void_t* p);
- realloc(Void_t* p, size_t n);
- memalign(size_t alignment, size_t n);
- valloc(size_t n);
- mallinfo()
- mallopt(int parameter_number, int parameter_value)
-
- Additional functions:
- independent_calloc(size_t n_elements, size_t size, Void_t* chunks[]);
- independent_comalloc(size_t n_elements, size_t sizes[], Void_t* chunks[]);
- pvalloc(size_t n);
- cfree(Void_t* p);
- malloc_trim(size_t pad);
- malloc_usable_size(Void_t* p);
- malloc_stats();
-
-* Vital statistics:
-
- Supported pointer representation: 4 or 8 bytes
- Supported size_t representation: 4 or 8 bytes
- Note that size_t is allowed to be 4 bytes even if pointers are 8.
- You can adjust this by defining INTERNAL_SIZE_T
-
- Alignment: 2 * sizeof(size_t) (default)
- (i.e., 8 byte alignment with 4byte size_t). This suffices for
- nearly all current machines and C compilers. However, you can
- define MALLOC_ALIGNMENT to be wider than this if necessary.
-
- Minimum overhead per allocated chunk: 4 or 8 bytes
- Each malloced chunk has a hidden word of overhead holding size
- and status information.
-
- Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
- 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
-
- When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
- ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
- needed; 4 (8) for a trailing size field and 8 (16) bytes for
- free list pointers. Thus, the minimum allocatable size is
- 16/24/32 bytes.
-
- Even a request for zero bytes (i.e., malloc(0)) returns a
- pointer to something of the minimum allocatable size.
-
- The maximum overhead wastage (i.e., number of extra bytes
- allocated than were requested in malloc) is less than or equal
- to the minimum size, except for requests >= mmap_threshold that
- are serviced via mmap(), where the worst case wastage is 2 *
- sizeof(size_t) bytes plus the remainder from a system page (the
- minimal mmap unit); typically 4096 or 8192 bytes.
-
- Maximum allocated size: 4-byte size_t: 2^32 minus about two pages
- 8-byte size_t: 2^64 minus about two pages
-
- It is assumed that (possibly signed) size_t values suffice to
- represent chunk sizes. `Possibly signed' is due to the fact
- that `size_t' may be defined on a system as either a signed or
- an unsigned type. The ISO C standard says that it must be
- unsigned, but a few systems are known not to adhere to this.
- Additionally, even when size_t is unsigned, sbrk (which is by
- default used to obtain memory from system) accepts signed
- arguments, and may not be able to handle size_t-wide arguments
- with negative sign bit. Generally, values that would
- appear as negative after accounting for overhead and alignment
- are supported only via mmap(), which does not have this
- limitation.
-
- Requests for sizes outside the allowed range will perform an optional
- failure action and then return null. (Requests may also
- also fail because a system is out of memory.)
-
- Thread-safety: NOT thread-safe unless USE_MALLOC_LOCK defined
-
- When USE_MALLOC_LOCK is defined, wrappers are created to
- surround every public call with either a pthread mutex or
- a win32 spinlock (depending on WIN32). This is not
- especially fast, and can be a major bottleneck.
- It is designed only to provide minimal protection
- in concurrent environments, and to provide a basis for
- extensions. If you are using malloc in a concurrent program,
- you would be far better off obtaining ptmalloc, which is
- derived from a version of this malloc, and is well-tuned for
- concurrent programs. (See http://www.malloc.de) Note that
- even when USE_MALLOC_LOCK is defined, you can can guarantee
- full thread-safety only if no threads acquire memory through
- direct calls to MORECORE or other system-level allocators.
-
- Compliance: I believe it is compliant with the 1997 Single Unix Specification
- (See http://www.opennc.org). Also SVID/XPG, ANSI C, and probably
- others as well.
-
-* Synopsis of compile-time options:
-
- People have reported using previous versions of this malloc on all
- versions of Unix, sometimes by tweaking some of the defines
- below. It has been tested most extensively on Solaris and
- Linux. It is also reported to work on WIN32 platforms.
- People also report using it in stand-alone embedded systems.
-
- The implementation is in straight, hand-tuned ANSI C. It is not
- at all modular. (Sorry!) It uses a lot of macros. To be at all
- usable, this code should be compiled using an optimizing compiler
- (for example gcc -O3) that can simplify expressions and control
- paths. (FAQ: some macros import variables as arguments rather than
- declare locals because people reported that some debuggers
- otherwise get confused.)
-
- OPTION DEFAULT VALUE
-
- Compilation Environment options:
-
- __STD_C derived from C compiler defines
- WIN32 NOT defined
- HAVE_MEMCPY defined
- USE_MEMCPY 1 if HAVE_MEMCPY is defined
- HAVE_MMAP defined as 1
- MMAP_CLEARS 1
- HAVE_MREMAP 0 unless linux defined
- malloc_getpagesize derived from system #includes, or 4096 if not
- HAVE_USR_INCLUDE_MALLOC_H NOT defined
- LACKS_UNISTD_H NOT defined unless WIN32
- LACKS_SYS_PARAM_H NOT defined unless WIN32
- LACKS_SYS_MMAN_H NOT defined unless WIN32
- LACKS_FCNTL_H NOT defined
-
- Changing default word sizes:
-
- INTERNAL_SIZE_T size_t
- MALLOC_ALIGNMENT 2 * sizeof(INTERNAL_SIZE_T)
- PTR_UINT unsigned long
- CHUNK_SIZE_T unsigned long
-
- Configuration and functionality options:
-
- USE_DL_PREFIX NOT defined
- USE_PUBLIC_MALLOC_WRAPPERS NOT defined
- USE_MALLOC_LOCK NOT defined
- DL_DEBUG NOT defined
- REALLOC_ZERO_BYTES_FREES NOT defined
- MALLOC_FAILURE_ACTION errno = ENOMEM, if __STD_C defined, else no-op
- TRIM_FASTBINS 0
- FIRST_SORTED_BIN_SIZE 512
-
- Options for customizing MORECORE:
-
- MORECORE sbrk
- MORECORE_CONTIGUOUS 1
- MORECORE_CANNOT_TRIM NOT defined
- MMAP_AS_MORECORE_SIZE (1024 * 1024)
-
- Tuning options that are also dynamically changeable via mallopt:
-
- DEFAULT_MXFAST 64
- DEFAULT_TRIM_THRESHOLD 256 * 1024
- DEFAULT_TOP_PAD 0
- DEFAULT_MMAP_THRESHOLD 256 * 1024
- DEFAULT_MMAP_MAX 65536
-
- There are several other #defined constants and macros that you
- probably don't want to touch unless you are extending or adapting malloc.
-*/
-
-/*
- WIN32 sets up defaults for MS environment and compilers.
- Otherwise defaults are for unix.
-*/
-
-/* #define WIN32 */
-
-#ifdef WIN32
-
-#define WIN32_LEAN_AND_MEAN
-#include
-
-/* Win32 doesn't supply or need the following headers */
-#define LACKS_UNISTD_H
-#define LACKS_SYS_PARAM_H
-#define LACKS_SYS_MMAN_H
-
-/* Use the supplied emulation of sbrk */
-#define MORECORE sbrk
-#define MORECORE_CONTIGUOUS 1
-#define MORECORE_FAILURE ((void*)(-1))
-
-/* Use the supplied emulation of mmap and munmap */
-#define HAVE_MMAP 1
-#define MUNMAP_FAILURE (-1)
-#define MMAP_CLEARS 1
-
-/* These values don't really matter in windows mmap emulation */
-#define MAP_PRIVATE 1
-#define MAP_ANONYMOUS 2
-#define PROT_READ 1
-#define PROT_WRITE 2
-
-/* Emulation functions defined at the end of this file */
-
-/* If USE_MALLOC_LOCK, use supplied critical-section-based lock functions */
-#ifdef USE_MALLOC_LOCK
-static int slwait(int *sl);
-static int slrelease(int *sl);
-#endif
-
-static long getpagesize(void);
-static long getregionsize(void);
-static void *sbrk(long size);
-static void *mmap(void *ptr, long size, long prot, long type, long handle, long arg);
-static long munmap(void *ptr, long size);
-
-static void vminfo (unsigned long*free, unsigned long*reserved, unsigned long*committed);
-static int cpuinfo (int whole, unsigned long*kernel, unsigned long*user);
-
-#endif
-
-/*
- __STD_C should be nonzero if using ANSI-standard C compiler, a C++
- compiler, or a C compiler sufficiently close to ANSI to get away
- with it.
-*/
-
-#ifndef __STD_C
-#if defined(__STDC__) || defined(_cplusplus)
-#define __STD_C 1
-#else
-#define __STD_C 0
-#endif
-#endif /*__STD_C*/
-
-
-/*
- Void_t* is the pointer type that malloc should say it returns
-*/
-
-#ifndef Void_t
-#if (__STD_C || defined(WIN32))
-#define Void_t void
-#else
-#define Void_t char
-#endif
-#endif /*Void_t*/
-
-#if __STD_C
-#include /* for size_t */
-#else
-#include
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* define LACKS_UNISTD_H if your system does not have a . */
-
-/* #define LACKS_UNISTD_H */
-
-#ifndef LACKS_UNISTD_H
-#include
-#endif
-
-/* define LACKS_SYS_PARAM_H if your system does not have a . */
-
-/* #define LACKS_SYS_PARAM_H */
-
-
-#include /* needed for malloc_stats */
-#include /* needed for optional MALLOC_FAILURE_ACTION */
-
-
-/*
- Debugging:
-
- Because freed chunks may be overwritten with bookkeeping fields, this
- malloc will often die when freed memory is overwritten by user
- programs. This can be very effective (albeit in an annoying way)
- in helping track down dangling pointers.
-
- If you compile with -DDL_DEBUG, a number of assertion checks are
- enabled that will catch more memory errors. You probably won't be
- able to make much sense of the actual assertion errors, but they
- should help you locate incorrectly overwritten memory. The
- checking is fairly extensive, and will slow down execution
- noticeably. Calling malloc_stats or mallinfo with DL_DEBUG set will
- attempt to check every non-mmapped allocated and free chunk in the
- course of computing the summmaries. (By nature, mmapped regions
- cannot be checked very much automatically.)
-
- Setting DL_DEBUG may also be helpful if you are trying to modify
- this code. The assertions in the check routines spell out in more
- detail the assumptions and invariants underlying the algorithms.
-
- Setting DL_DEBUG does NOT provide an automated mechanism for checking
- that all accesses to malloced memory stay within their
- bounds. However, there are several add-ons and adaptations of this
- or other mallocs available that do this.
-*/
-
-#if DL_DEBUG
-#include
-#else
-#define assert(x) ((void)0)
-#endif
-
-/*
- The unsigned integer type used for comparing any two chunk sizes.
- This should be at least as wide as size_t, but should not be signed.
-*/
-
-#ifndef CHUNK_SIZE_T
-#define CHUNK_SIZE_T unsigned long
-#endif
-
-/*
- The unsigned integer type used to hold addresses when they are are
- manipulated as integers. Except that it is not defined on all
- systems, intptr_t would suffice.
-*/
-#ifndef PTR_UINT
-#define PTR_UINT unsigned long
-#endif
-
-
-/*
- INTERNAL_SIZE_T is the word-size used for internal bookkeeping
- of chunk sizes.
-
- The default version is the same as size_t.
-
- While not strictly necessary, it is best to define this as an
- unsigned type, even if size_t is a signed type. This may avoid some
- artificial size limitations on some systems.
-
- On a 64-bit machine, you may be able to reduce malloc overhead by
- defining INTERNAL_SIZE_T to be a 32 bit `unsigned int' at the
- expense of not being able to handle more than 2^32 of malloced
- space. If this limitation is acceptable, you are encouraged to set
- this unless you are on a platform requiring 16byte alignments. In
- this case the alignment requirements turn out to negate any
- potential advantages of decreasing size_t word size.
-
- Implementors: Beware of the possible combinations of:
- - INTERNAL_SIZE_T might be signed or unsigned, might be 32 or 64 bits,
- and might be the same width as int or as long
- - size_t might have different width and signedness as INTERNAL_SIZE_T
- - int and long might be 32 or 64 bits, and might be the same width
- To deal with this, most comparisons and difference computations
- among INTERNAL_SIZE_Ts should cast them to CHUNK_SIZE_T, being
- aware of the fact that casting an unsigned int to a wider long does
- not sign-extend. (This also makes checking for negative numbers
- awkward.) Some of these casts result in harmless compiler warnings
- on some systems.
-*/
-
-#ifndef INTERNAL_SIZE_T
-#define INTERNAL_SIZE_T size_t
-#endif
-
-/* The corresponding word size */
-#define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
-
-
-
-/*
- MALLOC_ALIGNMENT is the minimum alignment for malloc'ed chunks.
- It must be a power of two at least 2 * SIZE_SZ, even on machines
- for which smaller alignments would suffice. It may be defined as
- larger than this though. Note however that code and data structures
- are optimized for the case of 8-byte alignment.
-*/
-
-
-#ifndef MALLOC_ALIGNMENT
-#define MALLOC_ALIGNMENT (2 * SIZE_SZ)
-#endif
-
-/* The corresponding bit mask value */
-#define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
-
-
-
-/*
- REALLOC_ZERO_BYTES_FREES should be set if a call to
- realloc with zero bytes should be the same as a call to free.
- Some people think it should. Otherwise, since this malloc
- returns a unique pointer for malloc(0), so does realloc(p, 0).
-*/
-
-/* #define REALLOC_ZERO_BYTES_FREES */
-
-/*
- TRIM_FASTBINS controls whether free() of a very small chunk can
- immediately lead to trimming. Setting to true (1) can reduce memory
- footprint, but will almost always slow down programs that use a lot
- of small chunks.
-
- Define this only if you are willing to give up some speed to more
- aggressively reduce system-level memory footprint when releasing
- memory in programs that use many small chunks. You can get
- essentially the same effect by setting MXFAST to 0, but this can
- lead to even greater slowdowns in programs using many small chunks.
- TRIM_FASTBINS is an in-between compile-time option, that disables
- only those chunks bordering topmost memory from being placed in
- fastbins.
-*/
-
-#ifndef TRIM_FASTBINS
-#define TRIM_FASTBINS 0
-#endif
-
-
-/*
- USE_DL_PREFIX will prefix all public routines with the string 'dl'.
- This is necessary when you only want to use this malloc in one part
- of a program, using your regular system malloc elsewhere.
-*/
-
-/* #define USE_DL_PREFIX */
-
-
-/*
- USE_MALLOC_LOCK causes wrapper functions to surround each
- callable routine with pthread mutex lock/unlock.
-
- USE_MALLOC_LOCK forces USE_PUBLIC_MALLOC_WRAPPERS to be defined
-*/
-
-
-/* #define USE_MALLOC_LOCK */
-
-
-/*
- If USE_PUBLIC_MALLOC_WRAPPERS is defined, every public routine is
- actually a wrapper function that first calls MALLOC_PREACTION, then
- calls the internal routine, and follows it with
- MALLOC_POSTACTION. This is needed for locking, but you can also use
- this, without USE_MALLOC_LOCK, for purposes of interception,
- instrumentation, etc. It is a sad fact that using wrappers often
- noticeably degrades performance of malloc-intensive programs.
-*/
-
-#ifdef USE_MALLOC_LOCK
-#define USE_PUBLIC_MALLOC_WRAPPERS
-#else
-/* #define USE_PUBLIC_MALLOC_WRAPPERS */
-#endif
-
-
-/*
- Two-phase name translation.
- All of the actual routines are given mangled names.
- When wrappers are used, they become the public callable versions.
- When DL_PREFIX is used, the callable names are prefixed.
-*/
-
-#ifndef USE_PUBLIC_MALLOC_WRAPPERS
-#define cALLOc public_cALLOc
-#define fREe public_fREe
-#define cFREe public_cFREe
-#define mALLOc public_mALLOc
-#define mEMALIGn public_mEMALIGn
-#define rEALLOc public_rEALLOc
-#define vALLOc public_vALLOc
-#define pVALLOc public_pVALLOc
-#define mALLINFo public_mALLINFo
-#define mALLOPt public_mALLOPt
-#define mTRIm public_mTRIm
-#define mSTATs public_mSTATs
-#define mUSABLe public_mUSABLe
-#define iCALLOc public_iCALLOc
-#define iCOMALLOc public_iCOMALLOc
-#endif
-
-#ifdef USE_DL_PREFIX
-#define public_cALLOc dlcalloc
-#define public_fREe dlfree
-#define public_cFREe dlcfree
-#define public_mALLOc dlmalloc
-#define public_mEMALIGn dlmemalign
-#define public_rEALLOc dlrealloc
-#define public_vALLOc dlvalloc
-#define public_pVALLOc dlpvalloc
-#define public_mALLINFo dlmallinfo
-#define public_mALLOPt dlmallopt
-#define public_mTRIm dlmalloc_trim
-#define public_mSTATs dlmalloc_stats
-#define public_mUSABLe dlmalloc_usable_size
-#define public_iCALLOc dlindependent_calloc
-#define public_iCOMALLOc dlindependent_comalloc
-#else /* USE_DL_PREFIX */
-#define public_cALLOc calloc
-#define public_fREe free
-#define public_cFREe cfree
-#define public_mALLOc malloc
-#define public_mEMALIGn memalign
-#define public_rEALLOc realloc
-#define public_vALLOc valloc
-#define public_pVALLOc pvalloc
-#define public_mALLINFo mallinfo
-#define public_mALLOPt mallopt
-#define public_mTRIm malloc_trim
-#define public_mSTATs malloc_stats
-#define public_mUSABLe malloc_usable_size
-#define public_iCALLOc independent_calloc
-#define public_iCOMALLOc independent_comalloc
-#endif /* USE_DL_PREFIX */
-
-
-/*
- HAVE_MEMCPY should be defined if you are not otherwise using
- ANSI STD C, but still have memcpy and memset in your C library
- and want to use them in calloc and realloc. Otherwise simple
- macro versions are defined below.
-
- USE_MEMCPY should be defined as 1 if you actually want to
- have memset and memcpy called. People report that the macro
- versions are faster than libc versions on some systems.
-
- Even if USE_MEMCPY is set to 1, loops to copy/clear small chunks
- (of <= 36 bytes) are manually unrolled in realloc and calloc.
-*/
-
-#define HAVE_MEMCPY
-
-#ifndef USE_MEMCPY
-#ifdef HAVE_MEMCPY
-#define USE_MEMCPY 1
-#else
-#define USE_MEMCPY 0
-#endif
-#endif
-
-
-#if (__STD_C || defined(HAVE_MEMCPY))
-
-#ifdef WIN32
-/* On Win32 memset and memcpy are already declared in windows.h */
-#else
-#if __STD_C
-void* memset(void*, int, size_t);
-void* memcpy(void*, const void*, size_t);
-#else
-Void_t* memset();
-Void_t* memcpy();
-#endif
-#endif
-#endif
-
-/*
- MALLOC_FAILURE_ACTION is the action to take before "return 0" when
- malloc fails to be able to return memory, either because memory is
- exhausted or because of illegal arguments.
-
- By default, sets errno if running on STD_C platform, else does nothing.
-*/
-
-#ifndef MALLOC_FAILURE_ACTION
-#if __STD_C
-#define MALLOC_FAILURE_ACTION \
- errno = ENOMEM;
-
-#else
-#define MALLOC_FAILURE_ACTION
-#endif
-#endif
-
-/*
- MORECORE-related declarations. By default, rely on sbrk
-*/
-
-
-#ifdef LACKS_UNISTD_H
-#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
-#if __STD_C
-extern Void_t* sbrk(ptrdiff_t);
-#else
-extern Void_t* sbrk();
-#endif
-#endif
-#endif
-
-/*
- MORECORE is the name of the routine to call to obtain more memory
- from the system. See below for general guidance on writing
- alternative MORECORE functions, as well as a version for WIN32 and a
- sample version for pre-OSX macos.
-*/
-
-#ifndef MORECORE
-#define MORECORE sbrk
-#endif
-
-/*
- MORECORE_FAILURE is the value returned upon failure of MORECORE
- as well as mmap. Since it cannot be an otherwise valid memory address,
- and must reflect values of standard sys calls, you probably ought not
- try to redefine it.
-*/
-
-#ifndef MORECORE_FAILURE
-#define MORECORE_FAILURE (-1)
-#endif
-
-/*
- If MORECORE_CONTIGUOUS is true, take advantage of fact that
- consecutive calls to MORECORE with positive arguments always return
- contiguous increasing addresses. This is true of unix sbrk. Even
- if not defined, when regions happen to be contiguous, malloc will
- permit allocations spanning regions obtained from different
- calls. But defining this when applicable enables some stronger
- consistency checks and space efficiencies.
-*/
-
-#ifndef MORECORE_CONTIGUOUS
-#define MORECORE_CONTIGUOUS 1
-#endif
-
-/*
- Define MORECORE_CANNOT_TRIM if your version of MORECORE
- cannot release space back to the system when given negative
- arguments. This is generally necessary only if you are using
- a hand-crafted MORECORE function that cannot handle negative arguments.
-*/
-
-/* #define MORECORE_CANNOT_TRIM */
-
-
-/*
- Define HAVE_MMAP as true to optionally make malloc() use mmap() to
- allocate very large blocks. These will be returned to the
- operating system immediately after a free(). Also, if mmap
- is available, it is used as a backup strategy in cases where
- MORECORE fails to provide space from system.
-
- This malloc is best tuned to work with mmap for large requests.
- If you do not have mmap, operations involving very large chunks (1MB
- or so) may be slower than you'd like.
-*/
-
-#ifndef HAVE_MMAP
-#define HAVE_MMAP 1
-#endif
-
-#if HAVE_MMAP
-/*
- Standard unix mmap using /dev/zero clears memory so calloc doesn't
- need to.
-*/
-
-#ifndef MMAP_CLEARS
-#define MMAP_CLEARS 1
-#endif
-
-#else /* no mmap */
-#ifndef MMAP_CLEARS
-#define MMAP_CLEARS 0
-#endif
-#endif
-
-
-/*
- MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
- sbrk fails, and mmap is used as a backup (which is done only if
- HAVE_MMAP). The value must be a multiple of page size. This
- backup strategy generally applies only when systems have "holes" in
- address space, so sbrk cannot perform contiguous expansion, but
- there is still space available on system. On systems for which
- this is known to be useful (i.e. most linux kernels), this occurs
- only when programs allocate huge amounts of memory. Between this,
- and the fact that mmap regions tend to be limited, the size should
- be large, to avoid too many mmap calls and thus avoid running out
- of kernel resources.
-*/
-
-#ifndef MMAP_AS_MORECORE_SIZE
-#define MMAP_AS_MORECORE_SIZE (1024 * 1024)
-#endif
-
-/*
- Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
- large blocks. This is currently only possible on Linux with
- kernel versions newer than 1.3.77.
-*/
-
-#ifndef HAVE_MREMAP
-#if defined(linux) && defined(__USE_GNU)
-#define HAVE_MREMAP 1
-#else
-#define HAVE_MREMAP 0
-#endif
-
-#endif /* HAVE_MMAP */
-
-
-/*
- The system page size. To the extent possible, this malloc manages
- memory from the system in page-size units. Note that this value is
- cached during initialization into a field of malloc_state. So even
- if malloc_getpagesize is a function, it is only called once.
-
- The following mechanics for getpagesize were adapted from bsd/gnu
- getpagesize.h. If none of the system-probes here apply, a value of
- 4096 is used, which should be OK: If they don't apply, then using
- the actual value probably doesn't impact performance.
-*/
-
-
-#ifndef malloc_getpagesize
-
-#ifndef LACKS_UNISTD_H
-# include
-#endif
-
-# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
-# ifndef _SC_PAGE_SIZE
-# define _SC_PAGE_SIZE _SC_PAGESIZE
-# endif
-# endif
-
-# ifdef _SC_PAGE_SIZE
-# define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
-# else
-# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
- extern size_t getpagesize();
-# define malloc_getpagesize getpagesize()
-# else
-# ifdef WIN32 /* use supplied emulation of getpagesize */
-# define malloc_getpagesize getpagesize()
-# else
-# ifndef LACKS_SYS_PARAM_H
-# include
-# endif
-# ifdef EXEC_PAGESIZE
-# define malloc_getpagesize EXEC_PAGESIZE
-# else
-# ifdef NBPG
-# ifndef CLSIZE
-# define malloc_getpagesize NBPG
-# else
-# define malloc_getpagesize (NBPG * CLSIZE)
-# endif
-# else
-# ifdef NBPC
-# define malloc_getpagesize NBPC
-# else
-# ifdef PAGESIZE
-# define malloc_getpagesize PAGESIZE
-# else /* just guess */
-# define malloc_getpagesize (4096)
-# endif
-# endif
-# endif
-# endif
-# endif
-# endif
-# endif
-#endif
-
-/*
- This version of malloc supports the standard SVID/XPG mallinfo
- routine that returns a struct containing usage properties and
- statistics. It should work on any SVID/XPG compliant system that has
- a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
- install such a thing yourself, cut out the preliminary declarations
- as described above and below and save them in a malloc.h file. But
- there's no compelling reason to bother to do this.)
-
- The main declaration needed is the mallinfo struct that is returned
- (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
- bunch of fields that are not even meaningful in this version of
- malloc. These fields are are instead filled by mallinfo() with
- other numbers that might be of interest.
-
- HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
- /usr/include/malloc.h file that includes a declaration of struct
- mallinfo. If so, it is included; else an SVID2/XPG2 compliant
- version is declared below. These must be precisely the same for
- mallinfo() to work. The original SVID version of this struct,
- defined on most systems with mallinfo, declares all fields as
- ints. But some others define as unsigned long. If your system
- defines the fields using a type of different width than listed here,
- you must #include your system version and #define
- HAVE_USR_INCLUDE_MALLOC_H.
-*/
-
-/* #define HAVE_USR_INCLUDE_MALLOC_H */
-
-#ifdef HAVE_USR_INCLUDE_MALLOC_H
-#include "/usr/include/malloc.h"
-#else
-
-/* SVID2/XPG mallinfo structure */
-
-struct mallinfo {
- int arena; /* non-mmapped space allocated from system */
- int ordblks; /* number of free chunks */
- int smblks; /* number of fastbin blocks */
- int hblks; /* number of mmapped regions */
- int hblkhd; /* space in mmapped regions */
- int usmblks; /* maximum total allocated space */
- int fsmblks; /* space available in freed fastbin blocks */
- int uordblks; /* total allocated space */
- int fordblks; /* total free space */
- int keepcost; /* top-most, releasable (via malloc_trim) space */
-};
-
-/*
- SVID/XPG defines four standard parameter numbers for mallopt,
- normally defined in malloc.h. Only one of these (M_MXFAST) is used
- in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
- so setting them has no effect. But this malloc also supports other
- options in mallopt described below.
-*/
-#endif
-
-
-/* ---------- description of public routines ------------ */
-
-/*
- malloc(size_t n)
- Returns a pointer to a newly allocated chunk of at least n bytes, or null
- if no space is available. Additionally, on failure, errno is
- set to ENOMEM on ANSI C systems.
-
- If n is zero, malloc returns a minumum-sized chunk. (The minimum
- size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
- systems.) On most systems, size_t is an unsigned type, so calls
- with negative arguments are interpreted as requests for huge amounts
- of space, which will often fail. The maximum supported value of n
- differs across systems, but is in all cases less than the maximum
- representable value of a size_t.
-*/
-#if __STD_C
-Void_t* public_mALLOc(size_t);
-#else
-Void_t* public_mALLOc();
-#endif
-
-/*
- free(Void_t* p)
- Releases the chunk of memory pointed to by p, that had been previously
- allocated using malloc or a related routine such as realloc.
- It has no effect if p is null. It can have arbitrary (i.e., bad!)
- effects if p has already been freed.
-
- Unless disabled (using mallopt), freeing very large spaces will
- when possible, automatically trigger operations that give
- back unused memory to the system, thus reducing program footprint.
-*/
-#if __STD_C
-void public_fREe(Void_t*);
-#else
-void public_fREe();
-#endif
-
-/*
- calloc(size_t n_elements, size_t element_size);
- Returns a pointer to n_elements * element_size bytes, with all locations
- set to zero.
-*/
-#if __STD_C
-Void_t* public_cALLOc(size_t, size_t);
-#else
-Void_t* public_cALLOc();
-#endif
-
-/*
- realloc(Void_t* p, size_t n)
- Returns a pointer to a chunk of size n that contains the same data
- as does chunk p up to the minimum of (n, p's size) bytes, or null
- if no space is available.
-
- The returned pointer may or may not be the same as p. The algorithm
- prefers extending p when possible, otherwise it employs the
- equivalent of a malloc-copy-free sequence.
-
- If p is null, realloc is equivalent to malloc.
-
- If space is not available, realloc returns null, errno is set (if on
- ANSI) and p is NOT freed.
-
- if n is for fewer bytes than already held by p, the newly unused
- space is lopped off and freed if possible. Unless the #define
- REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
- zero (re)allocates a minimum-sized chunk.
-
- Large chunks that were internally obtained via mmap will always
- be reallocated using malloc-copy-free sequences unless
- the system supports MREMAP (currently only linux).
-
- The old unix realloc convention of allowing the last-free'd chunk
- to be used as an argument to realloc is not supported.
-*/
-#if __STD_C
-Void_t* public_rEALLOc(Void_t*, size_t);
-#else
-Void_t* public_rEALLOc();
-#endif
-
-/*
- memalign(size_t alignment, size_t n);
- Returns a pointer to a newly allocated chunk of n bytes, aligned
- in accord with the alignment argument.
-
- The alignment argument should be a power of two. If the argument is
- not a power of two, the nearest greater power is used.
- 8-byte alignment is guaranteed by normal malloc calls, so don't
- bother calling memalign with an argument of 8 or less.
-
- Overreliance on memalign is a sure way to fragment space.
-*/
-#if __STD_C
-Void_t* public_mEMALIGn(size_t, size_t);
-#else
-Void_t* public_mEMALIGn();
-#endif
-
-/*
- valloc(size_t n);
- Equivalent to memalign(pagesize, n), where pagesize is the page
- size of the system. If the pagesize is unknown, 4096 is used.
-*/
-#if __STD_C
-Void_t* public_vALLOc(size_t);
-#else
-Void_t* public_vALLOc();
-#endif
-
-
-
-/*
- mallopt(int parameter_number, int parameter_value)
- Sets tunable parameters The format is to provide a
- (parameter-number, parameter-value) pair. mallopt then sets the
- corresponding parameter to the argument value if it can (i.e., so
- long as the value is meaningful), and returns 1 if successful else
- 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
- normally defined in malloc.h. Only one of these (M_MXFAST) is used
- in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
- so setting them has no effect. But this malloc also supports four
- other options in mallopt. See below for details. Briefly, supported
- parameters are as follows (listed defaults are for "typical"
- configurations).
-
- Symbol param # default allowed param values
- M_MXFAST 1 64 0-80 (0 disables fastbins)
- M_TRIM_THRESHOLD -1 256*1024 any (-1U disables trimming)
- M_TOP_PAD -2 0 any
- M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)
- M_MMAP_MAX -4 65536 any (0 disables use of mmap)
-*/
-#if __STD_C
-int public_mALLOPt(int, int);
-#else
-int public_mALLOPt();
-#endif
-
-
-/*
- mallinfo()
- Returns (by copy) a struct containing various summary statistics:
-
- arena: current total non-mmapped bytes allocated from system
- ordblks: the number of free chunks
- smblks: the number of fastbin blocks (i.e., small chunks that
- have been freed but not use resused or consolidated)
- hblks: current number of mmapped regions
- hblkhd: total bytes held in mmapped regions
- usmblks: the maximum total allocated space. This will be greater
- than current total if trimming has occurred.
- fsmblks: total bytes held in fastbin blocks
- uordblks: current total allocated space (normal or mmapped)
- fordblks: total free space
- keepcost: the maximum number of bytes that could ideally be released
- back to system via malloc_trim. ("ideally" means that
- it ignores page restrictions etc.)
-
- Because these fields are ints, but internal bookkeeping may
- be kept as longs, the reported values may wrap around zero and
- thus be inaccurate.
-*/
-#if __STD_C
-struct mallinfo public_mALLINFo(void);
-#else
-struct mallinfo public_mALLINFo();
-#endif
-
-/*
- independent_calloc(size_t n_elements, size_t element_size, Void_t* chunks[]);
-
- independent_calloc is similar to calloc, but instead of returning a
- single cleared space, it returns an array of pointers to n_elements
- independent elements that can hold contents of size elem_size, each
- of which starts out cleared, and can be independently freed,
- realloc'ed etc. The elements are guaranteed to be adjacently
- allocated (this is not guaranteed to occur with multiple callocs or
- mallocs), which may also improve cache locality in some
- applications.
-
- The "chunks" argument is optional (i.e., may be null, which is
- probably the most typical usage). If it is null, the returned array
- is itself dynamically allocated and should also be freed when it is
- no longer needed. Otherwise, the chunks array must be of at least
- n_elements in length. It is filled in with the pointers to the
- chunks.
-
- In either case, independent_calloc returns this pointer array, or
- null if the allocation failed. If n_elements is zero and "chunks"
- is null, it returns a chunk representing an array with zero elements
- (which should be freed if not wanted).
-
- Each element must be individually freed when it is no longer
- needed. If you'd like to instead be able to free all at once, you
- should instead use regular calloc and assign pointers into this
- space to represent elements. (In this case though, you cannot
- independently free elements.)
-
- independent_calloc simplifies and speeds up implementations of many
- kinds of pools. It may also be useful when constructing large data
- structures that initially have a fixed number of fixed-sized nodes,
- but the number is not known at compile time, and some of the nodes
- may later need to be freed. For example:
-
- struct Node { int item; struct Node* next; };
-
- struct Node* build_list() {
- struct Node** pool;
- int n = read_number_of_nodes_needed();
- if (n <= 0) return 0;
- pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
- if (pool == 0) die();
- // organize into a linked list...
- struct Node* first = pool[0];
- for (i = 0; i < n-1; ++i)
- pool[i]->next = pool[i+1];
- free(pool); // Can now free the array (or not, if it is needed later)
- return first;
- }
-*/
-#if __STD_C
-Void_t** public_iCALLOc(size_t, size_t, Void_t**);
-#else
-Void_t** public_iCALLOc();
-#endif
-
-/*
- independent_comalloc(size_t n_elements, size_t sizes[], Void_t* chunks[]);
-
- independent_comalloc allocates, all at once, a set of n_elements
- chunks with sizes indicated in the "sizes" array. It returns
- an array of pointers to these elements, each of which can be
- independently freed, realloc'ed etc. The elements are guaranteed to
- be adjacently allocated (this is not guaranteed to occur with
- multiple callocs or mallocs), which may also improve cache locality
- in some applications.
-
- The "chunks" argument is optional (i.e., may be null). If it is null
- the returned array is itself dynamically allocated and should also
- be freed when it is no longer needed. Otherwise, the chunks array
- must be of at least n_elements in length. It is filled in with the
- pointers to the chunks.
-
- In either case, independent_comalloc returns this pointer array, or
- null if the allocation failed. If n_elements is zero and chunks is
- null, it returns a chunk representing an array with zero elements
- (which should be freed if not wanted).
-
- Each element must be individually freed when it is no longer
- needed. If you'd like to instead be able to free all at once, you
- should instead use a single regular malloc, and assign pointers at
- particular offsets in the aggregate space. (In this case though, you
- cannot independently free elements.)
-
- independent_comallac differs from independent_calloc in that each
- element may have a different size, and also that it does not
- automatically clear elements.
-
- independent_comalloc can be used to speed up allocation in cases
- where several structs or objects must always be allocated at the
- same time. For example:
-
- struct Head { ... }
- struct Foot { ... }
-
- void send_message(char* msg) {
- int msglen = strlen(msg);
- size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
- void* chunks[3];
- if (independent_comalloc(3, sizes, chunks) == 0)
- die();
- struct Head* head = (struct Head*)(chunks[0]);
- char* body = (char*)(chunks[1]);
- struct Foot* foot = (struct Foot*)(chunks[2]);
- // ...
- }
-
- In general though, independent_comalloc is worth using only for
- larger values of n_elements. For small values, you probably won't
- detect enough difference from series of malloc calls to bother.
-
- Overuse of independent_comalloc can increase overall memory usage,
- since it cannot reuse existing noncontiguous small chunks that
- might be available for some of the elements.
-*/
-#if __STD_C
-Void_t** public_iCOMALLOc(size_t, size_t*, Void_t**);
-#else
-Void_t** public_iCOMALLOc();
-#endif
-
-
-/*
- pvalloc(size_t n);
- Equivalent to valloc(minimum-page-that-holds(n)), that is,
- round up n to nearest pagesize.
- */
-#if __STD_C
-Void_t* public_pVALLOc(size_t);
-#else
-Void_t* public_pVALLOc();
-#endif
-
-/*
- cfree(Void_t* p);
- Equivalent to free(p).
-
- cfree is needed/defined on some systems that pair it with calloc,
- for odd historical reasons (such as: cfree is used in example
- code in the first edition of K&R).
-*/
-#if __STD_C
-void public_cFREe(Void_t*);
-#else
-void public_cFREe();
-#endif
-
-/*
- malloc_trim(size_t pad);
-
- If possible, gives memory back to the system (via negative
- arguments to sbrk) if there is unused memory at the `high' end of
- the malloc pool. You can call this after freeing large blocks of
- memory to potentially reduce the system-level memory requirements
- of a program. However, it cannot guarantee to reduce memory. Under
- some allocation patterns, some large free blocks of memory will be
- locked between two used chunks, so they cannot be given back to
- the system.
-
- The `pad' argument to malloc_trim represents the amount of free
- trailing space to leave untrimmed. If this argument is zero,
- only the minimum amount of memory to maintain internal data
- structures will be left (one page or less). Non-zero arguments
- can be supplied to maintain enough trailing space to service
- future expected allocations without having to re-obtain memory
- from the system.
-
- Malloc_trim returns 1 if it actually released any memory, else 0.
- On systems that do not support "negative sbrks", it will always
- rreturn 0.
-*/
-#if __STD_C
-int public_mTRIm(size_t);
-#else
-int public_mTRIm();
-#endif
-
-/*
- malloc_usable_size(Void_t* p);
-
- Returns the number of bytes you can actually use in
- an allocated chunk, which may be more than you requested (although
- often not) due to alignment and minimum size constraints.
- You can use this many bytes without worrying about
- overwriting other allocated objects. This is not a particularly great
- programming practice. malloc_usable_size can be more useful in
- debugging and assertions, for example:
-
- p = malloc(n);
- assert(malloc_usable_size(p) >= 256);
-
-*/
-#if __STD_C
-size_t public_mUSABLe(Void_t*);
-#else
-size_t public_mUSABLe();
-#endif
-
-/*
- malloc_stats();
- Prints on stderr the amount of space obtained from the system (both
- via sbrk and mmap), the maximum amount (which may be more than
- current if malloc_trim and/or munmap got called), and the current
- number of bytes allocated via malloc (or realloc, etc) but not yet
- freed. Note that this is the number of bytes allocated, not the
- number requested. It will be larger than the number requested
- because of alignment and bookkeeping overhead. Because it includes
- alignment wastage as being in use, this figure may be greater than
- zero even when no user-level chunks are allocated.
-
- The reported current and maximum system memory can be inaccurate if
- a program makes other calls to system memory allocation functions
- (normally sbrk) outside of malloc.
-
- malloc_stats prints only the most commonly interesting statistics.
- More information can be obtained by calling mallinfo.
-
-*/
-#if __STD_C
-void public_mSTATs(void);
-#else
-void public_mSTATs(void);
-#endif
-
-/* mallopt tuning options */
-
-/*
- M_MXFAST is the maximum request size used for "fastbins", special bins
- that hold returned chunks without consolidating their spaces. This
- enables future requests for chunks of the same size to be handled
- very quickly, but can increase fragmentation, and thus increase the
- overall memory footprint of a program.
-
- This malloc manages fastbins very conservatively yet still
- efficiently, so fragmentation is rarely a problem for values less
- than or equal to the default. The maximum supported value of MXFAST
- is 80. You wouldn't want it any higher than this anyway. Fastbins
- are designed especially for use with many small structs, objects or
- strings -- the default handles structs/objects/arrays with sizes up
- to 16 4byte fields, or small strings representing words, tokens,
- etc. Using fastbins for larger objects normally worsens
- fragmentation without improving speed.
-
- M_MXFAST is set in REQUEST size units. It is internally used in
- chunksize units, which adds padding and alignment. You can reduce
- M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
- algorithm to be a closer approximation of fifo-best-fit in all cases,
- not just for larger requests, but will generally cause it to be
- slower.
-*/
-
-
-/* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
-#ifndef M_MXFAST
-#define M_MXFAST 1
-#endif
-
-#ifndef DEFAULT_MXFAST
-#define DEFAULT_MXFAST 64
-#endif
-
-
-/*
- M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
- to keep before releasing via malloc_trim in free().
-
- Automatic trimming is mainly useful in long-lived programs.
- Because trimming via sbrk can be slow on some systems, and can
- sometimes be wasteful (in cases where programs immediately
- afterward allocate more large chunks) the value should be high
- enough so that your overall system performance would improve by
- releasing this much memory.
-
- The trim threshold and the mmap control parameters (see below)
- can be traded off with one another. Trimming and mmapping are
- two different ways of releasing unused memory back to the
- system. Between these two, it is often possible to keep
- system-level demands of a long-lived program down to a bare
- minimum. For example, in one test suite of sessions measuring
- the XF86 X server on Linux, using a trim threshold of 128K and a
- mmap threshold of 192K led to near-minimal long term resource
- consumption.
-
- If you are using this malloc in a long-lived program, it should
- pay to experiment with these values. As a rough guide, you
- might set to a value close to the average size of a process
- (program) running on your system. Releasing this much memory
- would allow such a process to run in memory. Generally, it's
- worth it to tune for trimming rather tham memory mapping when a
- program undergoes phases where several large chunks are
- allocated and released in ways that can reuse each other's
- storage, perhaps mixed with phases where there are no such
- chunks at all. And in well-behaved long-lived programs,
- controlling release of large blocks via trimming versus mapping
- is usually faster.
-
- However, in most programs, these parameters serve mainly as
- protection against the system-level effects of carrying around
- massive amounts of unneeded memory. Since frequent calls to
- sbrk, mmap, and munmap otherwise degrade performance, the default
- parameters are set to relatively high values that serve only as
- safeguards.
-
- The trim value must be greater than page size to have any useful
- effect. To disable trimming completely, you can set to
- (unsigned long)(-1)
-
- Trim settings interact with fastbin (MXFAST) settings: Unless
- TRIM_FASTBINS is defined, automatic trimming never takes place upon
- freeing a chunk with size less than or equal to MXFAST. Trimming is
- instead delayed until subsequent freeing of larger chunks. However,
- you can still force an attempted trim by calling malloc_trim.
-
- Also, trimming is not generally possible in cases where
- the main arena is obtained via mmap.
-
- Note that the trick some people use of mallocing a huge space and
- then freeing it at program startup, in an attempt to reserve system
- memory, doesn't have the intended effect under automatic trimming,
- since that memory will immediately be returned to the system.
-*/
-
-#define M_TRIM_THRESHOLD -1
-
-#ifndef DEFAULT_TRIM_THRESHOLD
-#define DEFAULT_TRIM_THRESHOLD (256 * 1024)
-#endif
-
-/*
- M_TOP_PAD is the amount of extra `padding' space to allocate or
- retain whenever sbrk is called. It is used in two ways internally:
-
- * When sbrk is called to extend the top of the arena to satisfy
- a new malloc request, this much padding is added to the sbrk
- request.
-
- * When malloc_trim is called automatically from free(),
- it is used as the `pad' argument.
-
- In both cases, the actual amount of padding is rounded
- so that the end of the arena is always a system page boundary.
-
- The main reason for using padding is to avoid calling sbrk so
- often. Having even a small pad greatly reduces the likelihood
- that nearly every malloc request during program start-up (or
- after trimming) will invoke sbrk, which needlessly wastes
- time.
-
- Automatic rounding-up to page-size units is normally sufficient
- to avoid measurable overhead, so the default is 0. However, in
- systems where sbrk is relatively slow, it can pay to increase
- this value, at the expense of carrying around more memory than
- the program needs.
-*/
-
-#define M_TOP_PAD -2
-
-#ifndef DEFAULT_TOP_PAD
-#define DEFAULT_TOP_PAD (0)
-#endif
-
-/*
- M_MMAP_THRESHOLD is the request size threshold for using mmap()
- to service a request. Requests of at least this size that cannot
- be allocated using already-existing space will be serviced via mmap.
- (If enough normal freed space already exists it is used instead.)
-
- Using mmap segregates relatively large chunks of memory so that
- they can be individually obtained and released from the host
- system. A request serviced through mmap is never reused by any
- other request (at least not directly; the system may just so
- happen to remap successive requests to the same locations).
-
- Segregating space in this way has the benefits that:
-
- 1. Mmapped space can ALWAYS be individually released back
- to the system, which helps keep the system level memory
- demands of a long-lived program low.
- 2. Mapped memory can never become `locked' between
- other chunks, as can happen with normally allocated chunks, which
- means that even trimming via malloc_trim would not release them.
- 3. On some systems with "holes" in address spaces, mmap can obtain
- memory that sbrk cannot.
-
- However, it has the disadvantages that:
-
- 1. The space cannot be reclaimed, consolidated, and then
- used to service later requests, as happens with normal chunks.
- 2. It can lead to more wastage because of mmap page alignment
- requirements
- 3. It causes malloc performance to be more dependent on host
- system memory management support routines which may vary in
- implementation quality and may impose arbitrary
- limitations. Generally, servicing a request via normal
- malloc steps is faster than going through a system's mmap.
-
- The advantages of mmap nearly always outweigh disadvantages for
- "large" chunks, but the value of "large" varies across systems. The
- default is an empirically derived value that works well in most
- systems.
-*/
-
-#define M_MMAP_THRESHOLD -3
-
-#ifndef DEFAULT_MMAP_THRESHOLD
-#define DEFAULT_MMAP_THRESHOLD (256 * 1024)
-#endif
-
-/*
- M_MMAP_MAX is the maximum number of requests to simultaneously
- service using mmap. This parameter exists because
-. Some systems have a limited number of internal tables for
- use by mmap, and using more than a few of them may degrade
- performance.
-
- The default is set to a value that serves only as a safeguard.
- Setting to 0 disables use of mmap for servicing large requests. If
- HAVE_MMAP is not set, the default value is 0, and attempts to set it
- to non-zero values in mallopt will fail.
-*/
-
-#define M_MMAP_MAX -4
-
-#ifndef DEFAULT_MMAP_MAX
-#if HAVE_MMAP
-#define DEFAULT_MMAP_MAX (65536)
-#else
-#define DEFAULT_MMAP_MAX (0)
-#endif
-#endif
-
-#ifdef __cplusplus
-}; /* end of extern "C" */
-#endif
-
-/*
- ========================================================================
- To make a fully customizable malloc.h header file, cut everything
- above this line, put into file malloc.h, edit to suit, and #include it
- on the next line, as well as in programs that use this malloc.
- ========================================================================
-*/
-
-/* #include "malloc.h" */
-
-/* --------------------- public wrappers ---------------------- */
-
-#ifdef USE_PUBLIC_MALLOC_WRAPPERS
-
-/* Declare all routines as internal */
-#if __STD_C
-static Void_t* mALLOc(size_t);
-static void fREe(Void_t*);
-static Void_t* rEALLOc(Void_t*, size_t);
-static Void_t* mEMALIGn(size_t, size_t);
-static Void_t* vALLOc(size_t);
-static Void_t* pVALLOc(size_t);
-static Void_t* cALLOc(size_t, size_t);
-static Void_t** iCALLOc(size_t, size_t, Void_t**);
-static Void_t** iCOMALLOc(size_t, size_t*, Void_t**);
-static void cFREe(Void_t*);
-static int mTRIm(size_t);
-static size_t mUSABLe(Void_t*);
-static void mSTATs();
-static int mALLOPt(int, int);
-static struct mallinfo mALLINFo(void);
-#else
-static Void_t* mALLOc();
-static void fREe();
-static Void_t* rEALLOc();
-static Void_t* mEMALIGn();
-static Void_t* vALLOc();
-static Void_t* pVALLOc();
-static Void_t* cALLOc();
-static Void_t** iCALLOc();
-static Void_t** iCOMALLOc();
-static void cFREe();
-static int mTRIm();
-static size_t mUSABLe();
-static void mSTATs();
-static int mALLOPt();
-static struct mallinfo mALLINFo();
-#endif
-
-/*
- MALLOC_PREACTION and MALLOC_POSTACTION should be
- defined to return 0 on success, and nonzero on failure.
- The return value of MALLOC_POSTACTION is currently ignored
- in wrapper functions since there is no reasonable default
- action to take on failure.
-*/
-
-
-#ifdef USE_MALLOC_LOCK
-
-#ifdef WIN32
-
-static int mALLOC_MUTEx;
-#define MALLOC_PREACTION slwait(&mALLOC_MUTEx)
-#define MALLOC_POSTACTION slrelease(&mALLOC_MUTEx)
-
-#else
-
-#include
-
-static pthread_mutex_t mALLOC_MUTEx = PTHREAD_MUTEX_INITIALIZER;
-
-#define MALLOC_PREACTION pthread_mutex_lock(&mALLOC_MUTEx)
-#define MALLOC_POSTACTION pthread_mutex_unlock(&mALLOC_MUTEx)
-
-#endif /* USE_MALLOC_LOCK */
-
-#else
-
-/* Substitute anything you like for these */
-
-#define MALLOC_PREACTION (0)
-#define MALLOC_POSTACTION (0)
-
-#endif
-
-Void_t* public_mALLOc(size_t bytes) {
- Void_t* m;
- if (MALLOC_PREACTION != 0) {
- return 0;
- }
- m = mALLOc(bytes);
- if (MALLOC_POSTACTION != 0) {
- }
- return m;
-}
-
-void public_fREe(Void_t* m) {
- if (MALLOC_PREACTION != 0) {
- return;
- }
- fREe(m);
- if (MALLOC_POSTACTION != 0) {
- }
-}
-
-Void_t* public_rEALLOc(Void_t* m, size_t bytes) {
- if (MALLOC_PREACTION != 0) {
- return 0;
- }
- m = rEALLOc(m, bytes);
- if (MALLOC_POSTACTION != 0) {
- }
- return m;
-}
-
-Void_t* public_mEMALIGn(size_t alignment, size_t bytes) {
- Void_t* m;
- if (MALLOC_PREACTION != 0) {
- return 0;
- }
- m = mEMALIGn(alignment, bytes);
- if (MALLOC_POSTACTION != 0) {
- }
- return m;
-}
-
-Void_t* public_vALLOc(size_t bytes) {
- Void_t* m;
- if (MALLOC_PREACTION != 0) {
- return 0;
- }
- m = vALLOc(bytes);
- if (MALLOC_POSTACTION != 0) {
- }
- return m;
-}
-
-Void_t* public_pVALLOc(size_t bytes) {
- Void_t* m;
- if (MALLOC_PREACTION != 0) {
- return 0;
- }
- m = pVALLOc(bytes);
- if (MALLOC_POSTACTION != 0) {
- }
- return m;
-}
-
-Void_t* public_cALLOc(size_t n, size_t elem_size) {
- Void_t* m;
- if (MALLOC_PREACTION != 0) {
- return 0;
- }
- m = cALLOc(n, elem_size);
- if (MALLOC_POSTACTION != 0) {
- }
- return m;
-}
-
-
-Void_t** public_iCALLOc(size_t n, size_t elem_size, Void_t** chunks) {
- Void_t** m;
- if (MALLOC_PREACTION != 0) {
- return 0;
- }
- m = iCALLOc(n, elem_size, chunks);
- if (MALLOC_POSTACTION != 0) {
- }
- return m;
-}
-
-Void_t** public_iCOMALLOc(size_t n, size_t sizes[], Void_t** chunks) {
- Void_t** m;
- if (MALLOC_PREACTION != 0) {
- return 0;
- }
- m = iCOMALLOc(n, sizes, chunks);
- if (MALLOC_POSTACTION != 0) {
- }
- return m;
-}
-
-void public_cFREe(Void_t* m) {
- if (MALLOC_PREACTION != 0) {
- return;
- }
- cFREe(m);
- if (MALLOC_POSTACTION != 0) {
- }
-}
-
-int public_mTRIm(size_t s) {
- int result;
- if (MALLOC_PREACTION != 0) {
- return 0;
- }
- result = mTRIm(s);
- if (MALLOC_POSTACTION != 0) {
- }
- return result;
-}
-
-size_t public_mUSABLe(Void_t* m) {
- size_t result;
- if (MALLOC_PREACTION != 0) {
- return 0;
- }
- result = mUSABLe(m);
- if (MALLOC_POSTACTION != 0) {
- }
- return result;
-}
-
-void public_mSTATs() {
- if (MALLOC_PREACTION != 0) {
- return;
- }
- mSTATs();
- if (MALLOC_POSTACTION != 0) {
- }
-}
-
-struct mallinfo public_mALLINFo() {
- struct mallinfo m;
- if (MALLOC_PREACTION != 0) {
- struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
- return nm;
- }
- m = mALLINFo();
- if (MALLOC_POSTACTION != 0) {
- }
- return m;
-}
-
-int public_mALLOPt(int p, int v) {
- int result;
- if (MALLOC_PREACTION != 0) {
- return 0;
- }
- result = mALLOPt(p, v);
- if (MALLOC_POSTACTION != 0) {
- }
- return result;
-}
-
-#endif
-
-
-
-/* ------------- Optional versions of memcopy ---------------- */
-
-
-#if USE_MEMCPY
-
-/*
- Note: memcpy is ONLY invoked with non-overlapping regions,
- so the (usually slower) memmove is not needed.
-*/
-
-#define MALLOC_COPY(dest, src, nbytes) memcpy(dest, src, nbytes)
-#define MALLOC_ZERO(dest, nbytes) memset(dest, 0, nbytes)
-
-#else /* !USE_MEMCPY */
-
-/* Use Duff's device for good zeroing/copying performance. */
-
-#define MALLOC_ZERO(charp, nbytes) \
-do { \
- INTERNAL_SIZE_T* mzp = (INTERNAL_SIZE_T*)(charp); \
- CHUNK_SIZE_T mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T); \
- long mcn; \
- if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
- switch (mctmp) { \
- case 0: for(;;) { *mzp++ = 0; \
- case 7: *mzp++ = 0; \
- case 6: *mzp++ = 0; \
- case 5: *mzp++ = 0; \
- case 4: *mzp++ = 0; \
- case 3: *mzp++ = 0; \
- case 2: *mzp++ = 0; \
- case 1: *mzp++ = 0; if(mcn <= 0) break; mcn--; } \
- } \
-} while(0)
-
-#define MALLOC_COPY(dest,src,nbytes) \
-do { \
- INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) src; \
- INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) dest; \
- CHUNK_SIZE_T mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T); \
- long mcn; \
- if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
- switch (mctmp) { \
- case 0: for(;;) { *mcdst++ = *mcsrc++; \
- case 7: *mcdst++ = *mcsrc++; \
- case 6: *mcdst++ = *mcsrc++; \
- case 5: *mcdst++ = *mcsrc++; \
- case 4: *mcdst++ = *mcsrc++; \
- case 3: *mcdst++ = *mcsrc++; \
- case 2: *mcdst++ = *mcsrc++; \
- case 1: *mcdst++ = *mcsrc++; if(mcn <= 0) break; mcn--; } \
- } \
-} while(0)
-
-#endif
-
-/* ------------------ MMAP support ------------------ */
-
-
-#if HAVE_MMAP
-
-#ifndef LACKS_FCNTL_H
-#include
-#endif
-
-#ifndef LACKS_SYS_MMAN_H
-#include
-#endif
-
-#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
-#define MAP_ANONYMOUS MAP_ANON
-#endif
-
-/*
- Nearly all versions of mmap support MAP_ANONYMOUS,
- so the following is unlikely to be needed, but is
- supplied just in case.
-*/
-
-#ifndef MAP_ANONYMOUS
-
-static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
-
-#define MMAP(addr, size, prot, flags) ((dev_zero_fd < 0) ? \
- (dev_zero_fd = open("/dev/zero", O_RDWR), \
- mmap((addr), (size), (prot), (flags), dev_zero_fd, 0)) : \
- mmap((addr), (size), (prot), (flags), dev_zero_fd, 0))
-
-#else
-
-#define MMAP(addr, size, prot, flags) \
- (mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS, -1, 0))
-
-#endif
-
-
-#endif /* HAVE_MMAP */
-
-
-/*
- ----------------------- Chunk representations -----------------------
-*/
-
-
-/*
- This struct declaration is misleading (but accurate and necessary).
- It declares a "view" into memory allowing access to necessary
- fields at known offsets from a given base. See explanation below.
-*/
-
-struct malloc_chunk {
-
- INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
- INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
-
- struct malloc_chunk* fd; /* double links -- used only if free. */
- struct malloc_chunk* bk;
-};
-
-
-typedef struct malloc_chunk* mchunkptr;
-
-/*
- malloc_chunk details:
-
- (The following includes lightly edited explanations by Colin Plumb.)
-
- Chunks of memory are maintained using a `boundary tag' method as
- described in e.g., Knuth or Standish. (See the paper by Paul
- Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
- survey of such techniques.) Sizes of free chunks are stored both
- in the front of each chunk and at the end. This makes
- consolidating fragmented chunks into bigger chunks very fast. The
- size fields also hold bits representing whether chunks are free or
- in use.
-
- An allocated chunk looks like this:
-
-
- chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- | Size of previous chunk, if allocated | |
- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- | Size of chunk, in bytes |P|
- mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- | User data starts here... .
- . .
- . (malloc_usable_space() bytes) .
- . |
-nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- | Size of chunk |
- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-
-
- Where "chunk" is the front of the chunk for the purpose of most of
- the malloc code, but "mem" is the pointer that is returned to the
- user. "Nextchunk" is the beginning of the next contiguous chunk.
-
- Chunks always begin on even word boundries, so the mem portion
- (which is returned to the user) is also on an even word boundary, and
- thus at least double-word aligned.
-
- Free chunks are stored in circular doubly-linked lists, and look like this:
-
- chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- | Size of previous chunk |
- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- `head:' | Size of chunk, in bytes |P|
- mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- | Forward pointer to next chunk in list |
- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- | Back pointer to previous chunk in list |
- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- | Unused space (may be 0 bytes long) .
- . .
- . |
-nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- `foot:' | Size of chunk, in bytes |
- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-
- The P (PREV_INUSE) bit, stored in the unused low-order bit of the
- chunk size (which is always a multiple of two words), is an in-use
- bit for the *previous* chunk. If that bit is *clear*, then the
- word before the current chunk size contains the previous chunk
- size, and can be used to find the front of the previous chunk.
- The very first chunk allocated always has this bit set,
- preventing access to non-existent (or non-owned) memory. If
- prev_inuse is set for any given chunk, then you CANNOT determine
- the size of the previous chunk, and might even get a memory
- addressing fault when trying to do so.
-
- Note that the `foot' of the current chunk is actually represented
- as the prev_size of the NEXT chunk. This makes it easier to
- deal with alignments etc but can be very confusing when trying
- to extend or adapt this code.
-
- The two exceptions to all this are
-
- 1. The special chunk `top' doesn't bother using the
- trailing size field since there is no next contiguous chunk
- that would have to index off it. After initialization, `top'
- is forced to always exist. If it would become less than
- MINSIZE bytes long, it is replenished.
-
- 2. Chunks allocated via mmap, which have the second-lowest-order
- bit (IS_MMAPPED) set in their size fields. Because they are
- allocated one-by-one, each must contain its own trailing size field.
-
-*/
-
-/*
- ---------- Size and alignment checks and conversions ----------
-*/
-
-/* conversion from malloc headers to user pointers, and back */
-
-#define chunk2mem(p) ((Void_t*)((char*)(p) + 2*SIZE_SZ))
-#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
-
-/* The smallest possible chunk */
-#define MIN_CHUNK_SIZE (sizeof(struct malloc_chunk))
-
-/* The smallest size we can malloc is an aligned minimal chunk */
-
-#define MINSIZE \
- (CHUNK_SIZE_T)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
-
-/* Check if m has acceptable alignment */
-
-#define aligned_OK(m) (((PTR_UINT)((m)) & (MALLOC_ALIGN_MASK)) == 0)
-
-
-/*
- Check if a request is so large that it would wrap around zero when
- padded and aligned. To simplify some other code, the bound is made
- low enough so that adding MINSIZE will also not wrap around sero.
-*/
-
-#define REQUEST_OUT_OF_RANGE(req) \
- ((CHUNK_SIZE_T)(req) >= \
- (CHUNK_SIZE_T)(INTERNAL_SIZE_T)(-2 * MINSIZE))
-
-/* pad request bytes into a usable size -- internal version */
-
-#define request2size(req) \
- (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
- MINSIZE : \
- ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
-
-/* Same, except also perform argument check */
-
-#define checked_request2size(req, sz) \
- if (REQUEST_OUT_OF_RANGE(req)) { \
- MALLOC_FAILURE_ACTION; \
- return 0; \
- } \
- (sz) = request2size(req);
-
-/*
- --------------- Physical chunk operations ---------------
-*/
-
-
-/* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
-#define PREV_INUSE 0x1
-
-/* extract inuse bit of previous chunk */
-#define prev_inuse(p) ((p)->size & PREV_INUSE)
-
-
-/* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
-#define IS_MMAPPED 0x2
-
-/* check for mmap()'ed chunk */
-#define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
-
-/*
- Bits to mask off when extracting size
-
- Note: IS_MMAPPED is intentionally not masked off from size field in
- macros for which mmapped chunks should never be seen. This should
- cause helpful core dumps to occur if it is tried by accident by
- people extending or adapting this malloc.
-*/
-#define SIZE_BITS (PREV_INUSE|IS_MMAPPED)
-
-/* Get size, ignoring use bits */
-#define chunksize(p) ((p)->size & ~(SIZE_BITS))
-
-
-/* Ptr to next physical malloc_chunk. */
-#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~PREV_INUSE) ))
-
-/* Ptr to previous physical malloc_chunk */
-#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
-
-/* Treat space at ptr + offset as a chunk */
-#define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
-
-/* extract p's inuse bit */
-#define inuse(p)\
-((((mchunkptr)(((char*)(p))+((p)->size & ~PREV_INUSE)))->size) & PREV_INUSE)
-
-/* set/clear chunk as being inuse without otherwise disturbing */
-#define set_inuse(p)\
-((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size |= PREV_INUSE
-
-#define clear_inuse(p)\
-((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size &= ~(PREV_INUSE)
-
-
-/* check/set/clear inuse bits in known places */
-#define inuse_bit_at_offset(p, s)\
- (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
-
-#define set_inuse_bit_at_offset(p, s)\
- (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
-
-#define clear_inuse_bit_at_offset(p, s)\
- (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
-
-
-/* Set size at head, without disturbing its use bit */
-#define set_head_size(p, s) ((p)->size = (((p)->size & PREV_INUSE) | (s)))
-
-/* Set size/use field */
-#define set_head(p, s) ((p)->size = (s))
-
-/* Set size at footer (only when chunk is not in use) */
-#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
-
-
-/*
- -------------------- Internal data structures --------------------
-
- All internal state is held in an instance of malloc_state defined
- below. There are no other static variables, except in two optional
- cases:
- * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
- * If HAVE_MMAP is true, but mmap doesn't support
- MAP_ANONYMOUS, a dummy file descriptor for mmap.
-
- Beware of lots of tricks that minimize the total bookkeeping space
- requirements. The result is a little over 1K bytes (for 4byte
- pointers and size_t.)
-*/
-
-/*
- Bins
-
- An array of bin headers for free chunks. Each bin is doubly
- linked. The bins are approximately proportionally (log) spaced.
- There are a lot of these bins (128). This may look excessive, but
- works very well in practice. Most bins hold sizes that are
- unusual as malloc request sizes, but are more usual for fragments
- and consolidated sets of chunks, which is what these bins hold, so
- they can be found quickly. All procedures maintain the invariant
- that no consolidated chunk physically borders another one, so each
- chunk in a list is known to be preceeded and followed by either
- inuse chunks or the ends of memory.
-
- Chunks in bins are kept in size order, with ties going to the
- approximately least recently used chunk. Ordering isn't needed
- for the small bins, which all contain the same-sized chunks, but
- facilitates best-fit allocation for larger chunks. These lists
- are just sequential. Keeping them in order almost never requires
- enough traversal to warrant using fancier ordered data
- structures.
-
- Chunks of the same size are linked with the most
- recently freed at the front, and allocations are taken from the
- back. This results in LRU (FIFO) allocation order, which tends
- to give each chunk an equal opportunity to be consolidated with
- adjacent freed chunks, resulting in larger free chunks and less
- fragmentation.
-
- To simplify use in double-linked lists, each bin header acts
- as a malloc_chunk. This avoids special-casing for headers.
- But to conserve space and improve locality, we allocate
- only the fd/bk pointers of bins, and then use repositioning tricks
- to treat these as the fields of a malloc_chunk*.
-*/
-
-typedef struct malloc_chunk* mbinptr;
-
-/* addressing -- note that bin_at(0) does not exist */
-#define bin_at(m, i) ((mbinptr)((char*)&((m)->bins[(i)<<1]) - (SIZE_SZ<<1)))
-
-/* analog of ++bin */
-#define next_bin(b) ((mbinptr)((char*)(b) + (sizeof(mchunkptr)<<1)))
-
-/* Reminders about list directionality within bins */
-#define first(b) ((b)->fd)
-#define last(b) ((b)->bk)
-
-/* Take a chunk off a bin list */
-#define unlink(P, BK, FD) { \
- FD = P->fd; \
- BK = P->bk; \
- FD->bk = BK; \
- BK->fd = FD; \
-}
-
-/*
- Indexing
-
- Bins for sizes < 512 bytes contain chunks of all the same size, spaced
- 8 bytes apart. Larger bins are approximately logarithmically spaced:
-
- 64 bins of size 8
- 32 bins of size 64
- 16 bins of size 512
- 8 bins of size 4096
- 4 bins of size 32768
- 2 bins of size 262144
- 1 bin of size what's left
-
- The bins top out around 1MB because we expect to service large
- requests via mmap.
-*/
-
-#define NBINS 96
-#define NSMALLBINS 32
-#define SMALLBIN_WIDTH 8
-#define MIN_LARGE_SIZE 256
-
-#define in_smallbin_range(sz) \
- ((CHUNK_SIZE_T)(sz) < (CHUNK_SIZE_T)MIN_LARGE_SIZE)
-
-#define smallbin_index(sz) (((unsigned)(sz)) >> 3)
-
-/*
- Compute index for size. We expect this to be inlined when
- compiled with optimization, else not, which works out well.
-*/
-static int largebin_index(unsigned int sz) {
- unsigned int x = sz >> SMALLBIN_WIDTH;
- unsigned int m; /* bit position of highest set bit of m */
-
- if (x >= 0x10000) return NBINS-1;
-
- /* On intel, use BSRL instruction to find highest bit */
-#if defined(__GNUC__) && defined(i386)
-
- __asm__("bsrl %1,%0\n\t"
- : "=r" (m)
- : "g" (x));
-
-#else
- {
- /*
- Based on branch-free nlz algorithm in chapter 5 of Henry
- S. Warren Jr's book "Hacker's Delight".
- */
-
- unsigned int n = ((x - 0x100) >> 16) & 8;
- x <<= n;
- m = ((x - 0x1000) >> 16) & 4;
- n += m;
- x <<= m;
- m = ((x - 0x4000) >> 16) & 2;
- n += m;
- x = (x << m) >> 14;
- m = 13 - n + (x & ~(x>>1));
- }
-#endif
-
- /* Use next 2 bits to create finer-granularity bins */
- return NSMALLBINS + (m << 2) + ((sz >> (m + 6)) & 3);
-}
-
-#define bin_index(sz) \
- ((in_smallbin_range(sz)) ? smallbin_index(sz) : largebin_index(sz))
-
-/*
- FIRST_SORTED_BIN_SIZE is the chunk size corresponding to the
- first bin that is maintained in sorted order. This must
- be the smallest size corresponding to a given bin.
-
- Normally, this should be MIN_LARGE_SIZE. But you can weaken
- best fit guarantees to sometimes speed up malloc by increasing value.
- Doing this means that malloc may choose a chunk that is
- non-best-fitting by up to the width of the bin.
-
- Some useful cutoff values:
- 512 - all bins sorted
- 2560 - leaves bins <= 64 bytes wide unsorted
- 12288 - leaves bins <= 512 bytes wide unsorted
- 65536 - leaves bins <= 4096 bytes wide unsorted
- 262144 - leaves bins <= 32768 bytes wide unsorted
- -1 - no bins sorted (not recommended!)
-*/
-
-#define FIRST_SORTED_BIN_SIZE MIN_LARGE_SIZE
-/* #define FIRST_SORTED_BIN_SIZE 65536 */
-
-/*
- Unsorted chunks
-
- All remainders from chunk splits, as well as all returned chunks,
- are first placed in the "unsorted" bin. They are then placed
- in regular bins after malloc gives them ONE chance to be used before
- binning. So, basically, the unsorted_chunks list acts as a queue,
- with chunks being placed on it in free (and malloc_consolidate),
- and taken off (to be either used or placed in bins) in malloc.
-*/
-
-/* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
-#define unsorted_chunks(M) (bin_at(M, 1))
-
-/*
- Top
-
- The top-most available chunk (i.e., the one bordering the end of
- available memory) is treated specially. It is never included in
- any bin, is used only if no other chunk is available, and is
- released back to the system if it is very large (see
- M_TRIM_THRESHOLD). Because top initially
- points to its own bin with initial zero size, thus forcing
- extension on the first malloc request, we avoid having any special
- code in malloc to check whether it even exists yet. But we still
- need to do so when getting memory from system, so we make
- initial_top treat the bin as a legal but unusable chunk during the
- interval between initialization and the first call to
- sYSMALLOc. (This is somewhat delicate, since it relies on
- the 2 preceding words to be zero during this interval as well.)
-*/
-
-/* Conveniently, the unsorted bin can be used as dummy top on first call */
-#define initial_top(M) (unsorted_chunks(M))
-
-/*
- Binmap
-
- To help compensate for the large number of bins, a one-level index
- structure is used for bin-by-bin searching. `binmap' is a
- bitvector recording whether bins are definitely empty so they can
- be skipped over during during traversals. The bits are NOT always
- cleared as soon as bins are empty, but instead only
- when they are noticed to be empty during traversal in malloc.
-*/
-
-/* Conservatively use 32 bits per map word, even if on 64bit system */
-#define BINMAPSHIFT 5
-#define BITSPERMAP (1U << BINMAPSHIFT)
-#define BINMAPSIZE (NBINS / BITSPERMAP)
-
-#define idx2block(i) ((i) >> BINMAPSHIFT)
-#define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT)-1))))
-
-#define mark_bin(m,i) ((m)->binmap[idx2block(i)] |= idx2bit(i))
-#define unmark_bin(m,i) ((m)->binmap[idx2block(i)] &= ~(idx2bit(i)))
-#define get_binmap(m,i) ((m)->binmap[idx2block(i)] & idx2bit(i))
-
-/*
- Fastbins
-
- An array of lists holding recently freed small chunks. Fastbins
- are not doubly linked. It is faster to single-link them, and
- since chunks are never removed from the middles of these lists,
- double linking is not necessary. Also, unlike regular bins, they
- are not even processed in FIFO order (they use faster LIFO) since
- ordering doesn't much matter in the transient contexts in which
- fastbins are normally used.
-
- Chunks in fastbins keep their inuse bit set, so they cannot
- be consolidated with other free chunks. malloc_consolidate
- releases all chunks in fastbins and consolidates them with
- other free chunks.
-*/
-
-typedef struct malloc_chunk* mfastbinptr;
-
-/* offset 2 to use otherwise unindexable first 2 bins */
-#define fastbin_index(sz) ((((unsigned int)(sz)) >> 3) - 2)
-
-/* The maximum fastbin request size we support */
-#define MAX_FAST_SIZE 80
-
-#define NFASTBINS (fastbin_index(request2size(MAX_FAST_SIZE))+1)
-
-/*
- FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
- that triggers automatic consolidation of possibly-surrounding
- fastbin chunks. This is a heuristic, so the exact value should not
- matter too much. It is defined at half the default trim threshold as a
- compromise heuristic to only attempt consolidation if it is likely
- to lead to trimming. However, it is not dynamically tunable, since
- consolidation reduces fragmentation surrounding loarge chunks even
- if trimming is not used.
-*/
-
-#define FASTBIN_CONSOLIDATION_THRESHOLD \
- ((unsigned long)(DEFAULT_TRIM_THRESHOLD) >> 1)
-
-/*
- Since the lowest 2 bits in max_fast don't matter in size comparisons,
- they are used as flags.
-*/
-
-/*
- ANYCHUNKS_BIT held in max_fast indicates that there may be any
- freed chunks at all. It is set true when entering a chunk into any
- bin.
-*/
-
-#define ANYCHUNKS_BIT (1U)
-
-#define have_anychunks(M) (((M)->max_fast & ANYCHUNKS_BIT))
-#define set_anychunks(M) ((M)->max_fast |= ANYCHUNKS_BIT)
-#define clear_anychunks(M) ((M)->max_fast &= ~ANYCHUNKS_BIT)
-
-/*
- FASTCHUNKS_BIT held in max_fast indicates that there are probably
- some fastbin chunks. It is set true on entering a chunk into any
- fastbin, and cleared only in malloc_consolidate.
-*/
-
-#define FASTCHUNKS_BIT (2U)
-
-#define have_fastchunks(M) (((M)->max_fast & FASTCHUNKS_BIT))
-#define set_fastchunks(M) ((M)->max_fast |= (FASTCHUNKS_BIT|ANYCHUNKS_BIT))
-#define clear_fastchunks(M) ((M)->max_fast &= ~(FASTCHUNKS_BIT))
-
-/*
- Set value of max_fast.
- Use impossibly small value if 0.
-*/
-
-#define set_max_fast(M, s) \
- (M)->max_fast = (((s) == 0)? SMALLBIN_WIDTH: request2size(s)) | \
- ((M)->max_fast & (FASTCHUNKS_BIT|ANYCHUNKS_BIT))
-
-#define get_max_fast(M) \
- ((M)->max_fast & ~(FASTCHUNKS_BIT | ANYCHUNKS_BIT))
-
-
-/*
- morecore_properties is a status word holding dynamically discovered
- or controlled properties of the morecore function
-*/
-
-#define MORECORE_CONTIGUOUS_BIT (1U)
-
-#define contiguous(M) \
- (((M)->morecore_properties & MORECORE_CONTIGUOUS_BIT))
-#define noncontiguous(M) \
- (((M)->morecore_properties & MORECORE_CONTIGUOUS_BIT) == 0)
-#define set_contiguous(M) \
- ((M)->morecore_properties |= MORECORE_CONTIGUOUS_BIT)
-#define set_noncontiguous(M) \
- ((M)->morecore_properties &= ~MORECORE_CONTIGUOUS_BIT)
-
-
-/*
- ----------- Internal state representation and initialization -----------
-*/
-
-struct malloc_state {
-
- /* The maximum chunk size to be eligible for fastbin */
- INTERNAL_SIZE_T max_fast; /* low 2 bits used as flags */
-
- /* Fastbins */
- mfastbinptr fastbins[NFASTBINS];
-
- /* Base of the topmost chunk -- not otherwise kept in a bin */
- mchunkptr top;
-
- /* The remainder from the most recent split of a small request */
- mchunkptr last_remainder;
-
- /* Normal bins packed as described above */
- mchunkptr bins[NBINS * 2];
-
- /* Bitmap of bins. Trailing zero map handles cases of largest binned size */
- unsigned int binmap[BINMAPSIZE+1];
-
- /* Tunable parameters */
- CHUNK_SIZE_T trim_threshold;
- INTERNAL_SIZE_T top_pad;
- INTERNAL_SIZE_T mmap_threshold;
-
- /* Memory map support */
- int n_mmaps;
- int n_mmaps_max;
- int max_n_mmaps;
-
- /* Cache malloc_getpagesize */
- unsigned int pagesize;
-
- /* Track properties of MORECORE */
- unsigned int morecore_properties;
-
- /* Statistics */
- INTERNAL_SIZE_T mmapped_mem;
- INTERNAL_SIZE_T sbrked_mem;
- INTERNAL_SIZE_T max_sbrked_mem;
- INTERNAL_SIZE_T max_mmapped_mem;
- INTERNAL_SIZE_T max_total_mem;
-};
-
-typedef struct malloc_state *mstate;
-
-/*
- There is exactly one instance of this struct in this malloc.
- If you are adapting this malloc in a way that does NOT use a static
- malloc_state, you MUST explicitly zero-fill it before using. This
- malloc relies on the property that malloc_state is initialized to
- all zeroes (as is true of C statics).
-*/
-
-static struct malloc_state av_; /* never directly referenced */
-
-/*
- All uses of av_ are via get_malloc_state().
- At most one "call" to get_malloc_state is made per invocation of
- the public versions of malloc and free, but other routines
- that in turn invoke malloc and/or free may call more then once.
- Also, it is called in check* routines if DL_DEBUG is set.
-*/
-
-#define get_malloc_state() (&(av_))
-
-/*
- Initialize a malloc_state struct.
-
- This is called only from within malloc_consolidate, which needs
- be called in the same contexts anyway. It is never called directly
- outside of malloc_consolidate because some optimizing compilers try
- to inline it at all call points, which turns out not to be an
- optimization at all. (Inlining it in malloc_consolidate is fine though.)
-*/
-
-#if __STD_C
-static void malloc_init_state(mstate av)
-#else
-static void malloc_init_state(av) mstate av;
-#endif
-{
- int i;
- mbinptr bin;
-
- /* Establish circular links for normal bins */
- for (i = 1; i < NBINS; ++i) {
- bin = bin_at(av,i);
- bin->fd = bin->bk = bin;
- }
-
- av->top_pad = DEFAULT_TOP_PAD;
- av->n_mmaps_max = DEFAULT_MMAP_MAX;
- av->mmap_threshold = DEFAULT_MMAP_THRESHOLD;
- av->trim_threshold = DEFAULT_TRIM_THRESHOLD;
-
-#if MORECORE_CONTIGUOUS
- set_contiguous(av);
-#else
- set_noncontiguous(av);
-#endif
-
-
- set_max_fast(av, DEFAULT_MXFAST);
-
- av->top = initial_top(av);
- av->pagesize = malloc_getpagesize;
-}
-
-/*
- Other internal utilities operating on mstates
-*/
-
-#if __STD_C
-static Void_t* sYSMALLOc(INTERNAL_SIZE_T, mstate);
-static int sYSTRIm(size_t, mstate);
-static void malloc_consolidate(mstate);
-static Void_t** iALLOc(size_t, size_t*, int, Void_t**);
-#else
-static Void_t* sYSMALLOc();
-static int sYSTRIm();
-static void malloc_consolidate();
-static Void_t** iALLOc();
-#endif
-
-/*
- Debugging support
-
- These routines make a number of assertions about the states
- of data structures that should be true at all times. If any
- are not true, it's very likely that a user program has somehow
- trashed memory. (It's also possible that there is a coding error
- in malloc. In which case, please report it!)
-*/
-
-#if ! DL_DEBUG
-
-#define check_chunk(P)
-#define check_free_chunk(P)
-#define check_inuse_chunk(P)
-#define check_remalloced_chunk(P,N)
-#define check_malloced_chunk(P,N)
-#define check_malloc_state()
-
-#else
-#define check_chunk(P) do_check_chunk(P)
-#define check_free_chunk(P) do_check_free_chunk(P)
-#define check_inuse_chunk(P) do_check_inuse_chunk(P)
-#define check_remalloced_chunk(P,N) do_check_remalloced_chunk(P,N)
-#define check_malloced_chunk(P,N) do_check_malloced_chunk(P,N)
-#define check_malloc_state() do_check_malloc_state()
-
-/*
- Properties of all chunks
-*/
-
-#if __STD_C
-static void do_check_chunk(mchunkptr p)
-#else
-static void do_check_chunk(p) mchunkptr p;
-#endif
-{
- mstate av = get_malloc_state();
- CHUNK_SIZE_T sz = chunksize(p);
- /* min and max possible addresses assuming contiguous allocation */
- char* max_address = (char*)(av->top) + chunksize(av->top);
- char* min_address = max_address - av->sbrked_mem;
-
- if (!chunk_is_mmapped(p)) {
-
- /* Has legal address ... */
- if (p != av->top) {
- if (contiguous(av)) {
- assert(((char*)p) >= min_address);
- assert(((char*)p + sz) <= ((char*)(av->top)));
- }
- }
- else {
- /* top size is always at least MINSIZE */
- assert((CHUNK_SIZE_T)(sz) >= MINSIZE);
- /* top predecessor always marked inuse */
- assert(prev_inuse(p));
- }
-
- }
- else {
-#if HAVE_MMAP
- /* address is outside main heap */
- if (contiguous(av) && av->top != initial_top(av)) {
- assert(((char*)p) < min_address || ((char*)p) > max_address);
- }
- /* chunk is page-aligned */
- assert(((p->prev_size + sz) & (av->pagesize-1)) == 0);
- /* mem is aligned */
- assert(aligned_OK(chunk2mem(p)));
-#else
- /* force an appropriate assert violation if debug set */
- assert(!chunk_is_mmapped(p));
-#endif
- }
-}
-
-/*
- Properties of free chunks
-*/
-
-#if __STD_C
-static void do_check_free_chunk(mchunkptr p)
-#else
-static void do_check_free_chunk(p) mchunkptr p;
-#endif
-{
- mstate av = get_malloc_state();
-
- INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
- mchunkptr next = chunk_at_offset(p, sz);
-
- do_check_chunk(p);
-
- /* Chunk must claim to be free ... */
- assert(!inuse(p));
- assert (!chunk_is_mmapped(p));
-
- /* Unless a special marker, must have OK fields */
- if ((CHUNK_SIZE_T)(sz) >= MINSIZE)
- {
- assert((sz & MALLOC_ALIGN_MASK) == 0);
- assert(aligned_OK(chunk2mem(p)));
- /* ... matching footer field */
- assert(next->prev_size == sz);
- /* ... and is fully consolidated */
- assert(prev_inuse(p));
- assert (next == av->top || inuse(next));
-
- /* ... and has minimally sane links */
- assert(p->fd->bk == p);
- assert(p->bk->fd == p);
- }
- else /* markers are always of size SIZE_SZ */
- assert(sz == SIZE_SZ);
-}
-
-/*
- Properties of inuse chunks
-*/
-
-#if __STD_C
-static void do_check_inuse_chunk(mchunkptr p)
-#else
-static void do_check_inuse_chunk(p) mchunkptr p;
-#endif
-{
- mstate av = get_malloc_state();
- mchunkptr next;
- do_check_chunk(p);
-
- if (chunk_is_mmapped(p))
- return; /* mmapped chunks have no next/prev */
-
- /* Check whether it claims to be in use ... */
- assert(inuse(p));
-
- next = next_chunk(p);
-
- /* ... and is surrounded by OK chunks.
- Since more things can be checked with free chunks than inuse ones,
- if an inuse chunk borders them and debug is on, it's worth doing them.
- */
- if (!prev_inuse(p)) {
- /* Note that we cannot even look at prev unless it is not inuse */
- mchunkptr prv = prev_chunk(p);
- assert(next_chunk(prv) == p);
- do_check_free_chunk(prv);
- }
-
- if (next == av->top) {
- assert(prev_inuse(next));
- assert(chunksize(next) >= MINSIZE);
- }
- else if (!inuse(next))
- do_check_free_chunk(next);
-}
-
-/*
- Properties of chunks recycled from fastbins
-*/
-
-#if __STD_C
-static void do_check_remalloced_chunk(mchunkptr p, INTERNAL_SIZE_T s)
-#else
-static void do_check_remalloced_chunk(p, s) mchunkptr p; INTERNAL_SIZE_T s;
-#endif
-{
- INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
-
- do_check_inuse_chunk(p);
-
- /* Legal size ... */
- assert((sz & MALLOC_ALIGN_MASK) == 0);
- assert((CHUNK_SIZE_T)(sz) >= MINSIZE);
- /* ... and alignment */
- assert(aligned_OK(chunk2mem(p)));
- /* chunk is less than MINSIZE more than request */
- assert((long)(sz) - (long)(s) >= 0);
- assert((long)(sz) - (long)(s + MINSIZE) < 0);
-}
-
-/*
- Properties of nonrecycled chunks at the point they are malloced
-*/
-
-#if __STD_C
-static void do_check_malloced_chunk(mchunkptr p, INTERNAL_SIZE_T s)
-#else
-static void do_check_malloced_chunk(p, s) mchunkptr p; INTERNAL_SIZE_T s;
-#endif
-{
- /* same as recycled case ... */
- do_check_remalloced_chunk(p, s);
-
- /*
- ... plus, must obey implementation invariant that prev_inuse is
- always true of any allocated chunk; i.e., that each allocated
- chunk borders either a previously allocated and still in-use
- chunk, or the base of its memory arena. This is ensured
- by making all allocations from the the `lowest' part of any found
- chunk. This does not necessarily hold however for chunks
- recycled via fastbins.
- */
-
- assert(prev_inuse(p));
-}
-
-
-/*
- Properties of malloc_state.
-
- This may be useful for debugging malloc, as well as detecting user
- programmer errors that somehow write into malloc_state.
-
- If you are extending or experimenting with this malloc, you can
- probably figure out how to hack this routine to print out or
- display chunk addresses, sizes, bins, and other instrumentation.
-*/
-
-static void do_check_malloc_state(void)
-{
- mstate av = get_malloc_state();
- int i;
- mchunkptr p;
- mchunkptr q;
- mbinptr b;
- unsigned int binbit;
- int empty;
- unsigned int idx;
- INTERNAL_SIZE_T size;
- CHUNK_SIZE_T total = 0;
- int max_fast_bin;
-
- /* internal size_t must be no wider than pointer type */
- assert(sizeof(INTERNAL_SIZE_T) <= sizeof(char*));
-
- /* alignment is a power of 2 */
- assert((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-1)) == 0);
-
- /* cannot run remaining checks until fully initialized */
- if (av->top == 0 || av->top == initial_top(av))
- return;
-
- /* pagesize is a power of 2 */
- assert((av->pagesize & (av->pagesize-1)) == 0);
-
- /* properties of fastbins */
-
- /* max_fast is in allowed range */
- assert(get_max_fast(av) <= request2size(MAX_FAST_SIZE));
-
- max_fast_bin = fastbin_index(av->max_fast);
-
- for (i = 0; i < NFASTBINS; ++i) {
- p = av->fastbins[i];
-
- /* all bins past max_fast are empty */
- if (i > max_fast_bin)
- assert(p == 0);
-
- while (p != 0) {
- /* each chunk claims to be inuse */
- do_check_inuse_chunk(p);
- total += chunksize(p);
- /* chunk belongs in this bin */
- assert(fastbin_index(chunksize(p)) == i);
- p = p->fd;
- }
- }
-
- if (total != 0)
- assert(have_fastchunks(av));
- else if (!have_fastchunks(av))
- assert(total == 0);
-
- /* check normal bins */
- for (i = 1; i < NBINS; ++i) {
- b = bin_at(av,i);
-
- /* binmap is accurate (except for bin 1 == unsorted_chunks) */
- if (i >= 2) {
- binbit = get_binmap(av,i);
- empty = last(b) == b;
- if (!binbit)
- assert(empty);
- else if (!empty)
- assert(binbit);
- }
-
- for (p = last(b); p != b; p = p->bk) {
- /* each chunk claims to be free */
- do_check_free_chunk(p);
- size = chunksize(p);
- total += size;
- if (i >= 2) {
- /* chunk belongs in bin */
- idx = bin_index(size);
- assert(idx == i);
- /* lists are sorted */
- if ((CHUNK_SIZE_T) size >= (CHUNK_SIZE_T)(FIRST_SORTED_BIN_SIZE)) {
- assert(p->bk == b ||
- (CHUNK_SIZE_T)chunksize(p->bk) >=
- (CHUNK_SIZE_T)chunksize(p));
- }
- }
- /* chunk is followed by a legal chain of inuse chunks */
- for (q = next_chunk(p);
- (q != av->top && inuse(q) &&
- (CHUNK_SIZE_T)(chunksize(q)) >= MINSIZE);
- q = next_chunk(q))
- do_check_inuse_chunk(q);
- }
- }
-
- /* top chunk is OK */
- check_chunk(av->top);
-
- /* sanity checks for statistics */
-
- assert(total <= (CHUNK_SIZE_T)(av->max_total_mem));
- assert(av->n_mmaps >= 0);
- assert(av->n_mmaps <= av->max_n_mmaps);
-
- assert((CHUNK_SIZE_T)(av->sbrked_mem) <=
- (CHUNK_SIZE_T)(av->max_sbrked_mem));
-
- assert((CHUNK_SIZE_T)(av->mmapped_mem) <=
- (CHUNK_SIZE_T)(av->max_mmapped_mem));
-
- assert((CHUNK_SIZE_T)(av->max_total_mem) >=
- (CHUNK_SIZE_T)(av->mmapped_mem) + (CHUNK_SIZE_T)(av->sbrked_mem));
-}
-#endif
-
-
-/* ----------- Routines dealing with system allocation -------------- */
-
-/*
- sysmalloc handles malloc cases requiring more memory from the system.
- On entry, it is assumed that av->top does not have enough
- space to service request for nb bytes, thus requiring that av->top
- be extended or replaced.
-*/
-
-#if __STD_C
-static Void_t* sYSMALLOc(INTERNAL_SIZE_T nb, mstate av)
-#else
-static Void_t* sYSMALLOc(nb, av) INTERNAL_SIZE_T nb; mstate av;
-#endif
-{
- mchunkptr old_top; /* incoming value of av->top */
- INTERNAL_SIZE_T old_size; /* its size */
- char* old_end; /* its end address */
-
- long size; /* arg to first MORECORE or mmap call */
- char* brk; /* return value from MORECORE */
-
- long correction; /* arg to 2nd MORECORE call */
- char* snd_brk; /* 2nd return val */
-
- INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
- INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
- char* aligned_brk; /* aligned offset into brk */
-
- mchunkptr p; /* the allocated/returned chunk */
- mchunkptr remainder; /* remainder from allocation */
- CHUNK_SIZE_T remainder_size; /* its size */
-
- CHUNK_SIZE_T sum; /* for updating stats */
-
- size_t pagemask = av->pagesize - 1;
-
- /*
- If there is space available in fastbins, consolidate and retry
- malloc from scratch rather than getting memory from system. This
- can occur only if nb is in smallbin range so we didn't consolidate
- upon entry to malloc. It is much easier to handle this case here
- than in malloc proper.
- */
-
- if (have_fastchunks(av)) {
- assert(in_smallbin_range(nb));
- malloc_consolidate(av);
- return mALLOc(nb - MALLOC_ALIGN_MASK);
- }
-
-
-#if HAVE_MMAP
-
- /*
- If have mmap, and the request size meets the mmap threshold, and
- the system supports mmap, and there are few enough currently
- allocated mmapped regions, try to directly map this request
- rather than expanding top.
- */
-
- if ((CHUNK_SIZE_T)(nb) >= (CHUNK_SIZE_T)(av->mmap_threshold) &&
- (av->n_mmaps < av->n_mmaps_max)) {
-
- char* mm; /* return value from mmap call*/
-
- /*
- Round up size to nearest page. For mmapped chunks, the overhead
- is one SIZE_SZ unit larger than for normal chunks, because there
- is no following chunk whose prev_size field could be used.
- */
- size = (nb + SIZE_SZ + MALLOC_ALIGN_MASK + pagemask) & ~pagemask;
-
- /* Don't try if size wraps around 0 */
- if ((CHUNK_SIZE_T)(size) > (CHUNK_SIZE_T)(nb)) {
-
- mm = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE));
-
- if (mm != (char*)(MORECORE_FAILURE)) {
-
- /*
- The offset to the start of the mmapped region is stored
- in the prev_size field of the chunk. This allows us to adjust
- returned start address to meet alignment requirements here
- and in memalign(), and still be able to compute proper
- address argument for later munmap in free() and realloc().
- */
-
- front_misalign = (INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK;
- if (front_misalign > 0) {
- correction = MALLOC_ALIGNMENT - front_misalign;
- p = (mchunkptr)(mm + correction);
- p->prev_size = correction;
- set_head(p, (size - correction) |IS_MMAPPED);
- }
- else {
- p = (mchunkptr)mm;
- p->prev_size = 0;
- set_head(p, size|IS_MMAPPED);
- }
-
- /* update statistics */
-
- if (++av->n_mmaps > av->max_n_mmaps)
- av->max_n_mmaps = av->n_mmaps;
-
- sum = av->mmapped_mem += size;
- if (sum > (CHUNK_SIZE_T)(av->max_mmapped_mem))
- av->max_mmapped_mem = sum;
- sum += av->sbrked_mem;
- if (sum > (CHUNK_SIZE_T)(av->max_total_mem))
- av->max_total_mem = sum;
-
- check_chunk(p);
-
- return chunk2mem(p);
- }
- }
- }
-#endif
-
- /* Record incoming configuration of top */
-
- old_top = av->top;
- old_size = chunksize(old_top);
- old_end = (char*)(chunk_at_offset(old_top, old_size));
-
- brk = snd_brk = (char*)(MORECORE_FAILURE);
-
- /*
- If not the first time through, we require old_size to be
- at least MINSIZE and to have prev_inuse set.
- */
-
- assert((old_top == initial_top(av) && old_size == 0) ||
- ((CHUNK_SIZE_T) (old_size) >= MINSIZE &&
- prev_inuse(old_top)));
-
- /* Precondition: not enough current space to satisfy nb request */
- assert((CHUNK_SIZE_T)(old_size) < (CHUNK_SIZE_T)(nb + MINSIZE));
-
- /* Precondition: all fastbins are consolidated */
- assert(!have_fastchunks(av));
-
-
- /* Request enough space for nb + pad + overhead */
-
- size = nb + av->top_pad + MINSIZE;
-
- /*
- If contiguous, we can subtract out existing space that we hope to
- combine with new space. We add it back later only if
- we don't actually get contiguous space.
- */
-
- if (contiguous(av))
- size -= old_size;
-
- /*
- Round to a multiple of page size.
- If MORECORE is not contiguous, this ensures that we only call it
- with whole-page arguments. And if MORECORE is contiguous and
- this is not first time through, this preserves page-alignment of
- previous calls. Otherwise, we correct to page-align below.
- */
-
- size = (size + pagemask) & ~pagemask;
-
- /*
- Don't try to call MORECORE if argument is so big as to appear
- negative. Note that since mmap takes size_t arg, it may succeed
- below even if we cannot call MORECORE.
- */
-
- if (size > 0)
- brk = (char*)(MORECORE(size));
-
- /*
- If have mmap, try using it as a backup when MORECORE fails or
- cannot be used. This is worth doing on systems that have "holes" in
- address space, so sbrk cannot extend to give contiguous space, but
- space is available elsewhere. Note that we ignore mmap max count
- and threshold limits, since the space will not be used as a
- segregated mmap region.
- */
-
-#if HAVE_MMAP
- if (brk == (char*)(MORECORE_FAILURE)) {
-
- /* Cannot merge with old top, so add its size back in */
- if (contiguous(av))
- size = (size + old_size + pagemask) & ~pagemask;
-
- /* If we are relying on mmap as backup, then use larger units */
- if ((CHUNK_SIZE_T)(size) < (CHUNK_SIZE_T)(MMAP_AS_MORECORE_SIZE))
- size = MMAP_AS_MORECORE_SIZE;
-
- /* Don't try if size wraps around 0 */
- if ((CHUNK_SIZE_T)(size) > (CHUNK_SIZE_T)(nb)) {
-
- brk = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE));
-
- if (brk != (char*)(MORECORE_FAILURE)) {
-
- /* We do not need, and cannot use, another sbrk call to find end */
- snd_brk = brk + size;
-
- /*
- Record that we no longer have a contiguous sbrk region.
- After the first time mmap is used as backup, we do not
- ever rely on contiguous space since this could incorrectly
- bridge regions.
- */
- set_noncontiguous(av);
- }
- }
- }
-#endif
-
- if (brk != (char*)(MORECORE_FAILURE)) {
- av->sbrked_mem += size;
-
- /*
- If MORECORE extends previous space, we can likewise extend top size.
- */
-
- if (brk == old_end && snd_brk == (char*)(MORECORE_FAILURE)) {
- set_head(old_top, (size + old_size) | PREV_INUSE);
- }
-
- /*
- Otherwise, make adjustments:
-
- * If the first time through or noncontiguous, we need to call sbrk
- just to find out where the end of memory lies.
-
- * We need to ensure that all returned chunks from malloc will meet
- MALLOC_ALIGNMENT
-
- * If there was an intervening foreign sbrk, we need to adjust sbrk
- request size to account for fact that we will not be able to
- combine new space with existing space in old_top.
-
- * Almost all systems internally allocate whole pages at a time, in
- which case we might as well use the whole last page of request.
- So we allocate enough more memory to hit a page boundary now,
- which in turn causes future contiguous calls to page-align.
- */
-
- else {
- front_misalign = 0;
- end_misalign = 0;
- correction = 0;
- aligned_brk = brk;
-
- /*
- If MORECORE returns an address lower than we have seen before,
- we know it isn't really contiguous. This and some subsequent
- checks help cope with non-conforming MORECORE functions and
- the presence of "foreign" calls to MORECORE from outside of
- malloc or by other threads. We cannot guarantee to detect
- these in all cases, but cope with the ones we do detect.
- */
- if (contiguous(av) && old_size != 0 && brk < old_end) {
- set_noncontiguous(av);
- }
-
- /* handle contiguous cases */
- if (contiguous(av)) {
-
- /*
- We can tolerate forward non-contiguities here (usually due
- to foreign calls) but treat them as part of our space for
- stats reporting.
- */
- if (old_size != 0)
- av->sbrked_mem += brk - old_end;
-
- /* Guarantee alignment of first new chunk made from this space */
-
- front_misalign = (INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK;
- if (front_misalign > 0) {
-
- /*
- Skip over some bytes to arrive at an aligned position.
- We don't need to specially mark these wasted front bytes.
- They will never be accessed anyway because
- prev_inuse of av->top (and any chunk created from its start)
- is always true after initialization.
- */
-
- correction = MALLOC_ALIGNMENT - front_misalign;
- aligned_brk += correction;
- }
-
- /*
- If this isn't adjacent to existing space, then we will not
- be able to merge with old_top space, so must add to 2nd request.
- */
-
- correction += old_size;
-
- /* Extend the end address to hit a page boundary */
- end_misalign = (INTERNAL_SIZE_T)(brk + size + correction);
- correction += ((end_misalign + pagemask) & ~pagemask) - end_misalign;
-
- assert(correction >= 0);
- snd_brk = (char*)(MORECORE(correction));
-
- if (snd_brk == (char*)(MORECORE_FAILURE)) {
- /*
- If can't allocate correction, try to at least find out current
- brk. It might be enough to proceed without failing.
- */
- correction = 0;
- snd_brk = (char*)(MORECORE(0));
- }
- else if (snd_brk < brk) {
- /*
- If the second call gives noncontiguous space even though
- it says it won't, the only course of action is to ignore
- results of second call, and conservatively estimate where
- the first call left us. Also set noncontiguous, so this
- won't happen again, leaving at most one hole.
-
- Note that this check is intrinsically incomplete. Because
- MORECORE is allowed to give more space than we ask for,
- there is no reliable way to detect a noncontiguity
- producing a forward gap for the second call.
- */
- snd_brk = brk + size;
- correction = 0;
- set_noncontiguous(av);
- }
-
- }
-
- /* handle non-contiguous cases */
- else {
- /* MORECORE/mmap must correctly align */
- assert(aligned_OK(chunk2mem(brk)));
-
- /* Find out current end of memory */
- if (snd_brk == (char*)(MORECORE_FAILURE)) {
- snd_brk = (char*)(MORECORE(0));
- av->sbrked_mem += snd_brk - brk - size;
- }
- }
-
- /* Adjust top based on results of second sbrk */
- if (snd_brk != (char*)(MORECORE_FAILURE)) {
- av->top = (mchunkptr)aligned_brk;
- set_head(av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
- av->sbrked_mem += correction;
-
- /*
- If not the first time through, we either have a
- gap due to foreign sbrk or a non-contiguous region. Insert a
- double fencepost at old_top to prevent consolidation with space
- we don't own. These fenceposts are artificial chunks that are
- marked as inuse and are in any case too small to use. We need
- two to make sizes and alignments work out.
- */
-
- if (old_size != 0) {
- /*
- Shrink old_top to insert fenceposts, keeping size a
- multiple of MALLOC_ALIGNMENT. We know there is at least
- enough space in old_top to do this.
- */
- old_size = (old_size - 3*SIZE_SZ) & ~MALLOC_ALIGN_MASK;
- set_head(old_top, old_size | PREV_INUSE);
-
- /*
- Note that the following assignments completely overwrite
- old_top when old_size was previously MINSIZE. This is
- intentional. We need the fencepost, even if old_top otherwise gets
- lost.
- */
- chunk_at_offset(old_top, old_size )->size =
- SIZE_SZ|PREV_INUSE;
-
- chunk_at_offset(old_top, old_size + SIZE_SZ)->size =
- SIZE_SZ|PREV_INUSE;
-
- /*
- If possible, release the rest, suppressing trimming.
- */
- if (old_size >= MINSIZE) {
- INTERNAL_SIZE_T tt = av->trim_threshold;
- av->trim_threshold = (INTERNAL_SIZE_T)(-1);
- fREe(chunk2mem(old_top));
- av->trim_threshold = tt;
- }
- }
- }
- }
-
- /* Update statistics */
- sum = av->sbrked_mem;
- if (sum > (CHUNK_SIZE_T)(av->max_sbrked_mem))
- av->max_sbrked_mem = sum;
-
- sum += av->mmapped_mem;
- if (sum > (CHUNK_SIZE_T)(av->max_total_mem))
- av->max_total_mem = sum;
-
- check_malloc_state();
-
- /* finally, do the allocation */
-
- p = av->top;
- size = chunksize(p);
-
- /* check that one of the above allocation paths succeeded */
- if ((CHUNK_SIZE_T)(size) >= (CHUNK_SIZE_T)(nb + MINSIZE)) {
- remainder_size = size - nb;
- remainder = chunk_at_offset(p, nb);
- av->top = remainder;
- set_head(p, nb | PREV_INUSE);
- set_head(remainder, remainder_size | PREV_INUSE);
- check_malloced_chunk(p, nb);
- return chunk2mem(p);
- }
-
- }
-
- /* catch all failure paths */
- MALLOC_FAILURE_ACTION;
- return 0;
-}
-
-
-
-
-/*
- sYSTRIm is an inverse of sorts to sYSMALLOc. It gives memory back
- to the system (via negative arguments to sbrk) if there is unused
- memory at the `high' end of the malloc pool. It is called
- automatically by free() when top space exceeds the trim
- threshold. It is also called by the public malloc_trim routine. It
- returns 1 if it actually released any memory, else 0.
-*/
-
-#if __STD_C
-static int sYSTRIm(size_t pad, mstate av)
-#else
-static int sYSTRIm(pad, av) size_t pad; mstate av;
-#endif
-{
- long top_size; /* Amount of top-most memory */
- long extra; /* Amount to release */
- long released; /* Amount actually released */
- char* current_brk; /* address returned by pre-check sbrk call */
- char* new_brk; /* address returned by post-check sbrk call */
- size_t pagesz;
-
- pagesz = av->pagesize;
- top_size = chunksize(av->top);
-
- /* Release in pagesize units, keeping at least one page */
- extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz;
-
- if (extra > 0) {
-
- /*
- Only proceed if end of memory is where we last set it.
- This avoids problems if there were foreign sbrk calls.
- */
- current_brk = (char*)(MORECORE(0));
- if (current_brk == (char*)(av->top) + top_size) {
-
- /*
- Attempt to release memory. We ignore MORECORE return value,
- and instead call again to find out where new end of memory is.
- This avoids problems if first call releases less than we asked,
- of if failure somehow altered brk value. (We could still
- encounter problems if it altered brk in some very bad way,
- but the only thing we can do is adjust anyway, which will cause
- some downstream failure.)
- */
-
- MORECORE(-extra);
- new_brk = (char*)(MORECORE(0));
-
- if (new_brk != (char*)MORECORE_FAILURE) {
- released = (long)(current_brk - new_brk);
-
- if (released != 0) {
- /* Success. Adjust top. */
- av->sbrked_mem -= released;
- set_head(av->top, (top_size - released) | PREV_INUSE);
- check_malloc_state();
- return 1;
- }
- }
- }
- }
- return 0;
-}
-
-/*
- ------------------------------ malloc ------------------------------
-*/
-
-
-#if __STD_C
-Void_t* mALLOc(size_t bytes)
-#else
- Void_t* mALLOc(bytes) size_t bytes;
-#endif
-{
- mstate av = get_malloc_state();
-
- INTERNAL_SIZE_T nb; /* normalized request size */
- unsigned int idx; /* associated bin index */
- mbinptr bin; /* associated bin */
- mfastbinptr* fb; /* associated fastbin */
-
- mchunkptr victim; /* inspected/selected chunk */
- INTERNAL_SIZE_T size; /* its size */
- int victim_index; /* its bin index */
-
- mchunkptr remainder; /* remainder from a split */
- CHUNK_SIZE_T remainder_size; /* its size */
-
- unsigned int block; /* bit map traverser */
- unsigned int bit; /* bit map traverser */
- unsigned int map; /* current word of binmap */
-
- mchunkptr fwd; /* misc temp for linking */
- mchunkptr bck; /* misc temp for linking */
-
- /*
- Convert request size to internal form by adding SIZE_SZ bytes
- overhead plus possibly more to obtain necessary alignment and/or
- to obtain a size of at least MINSIZE, the smallest allocatable
- size. Also, checked_request2size traps (returning 0) request sizes
- that are so large that they wrap around zero when padded and
- aligned.
- */
-
- checked_request2size(bytes, nb);
-
- /*
- Bypass search if no frees yet
- */
- if (!have_anychunks(av)) {
- if (av->max_fast == 0) /* initialization check */
- malloc_consolidate(av);
- goto use_top;
- }
-
- /*
- If the size qualifies as a fastbin, first check corresponding bin.
- */
-
- if ((CHUNK_SIZE_T)(nb) <= (CHUNK_SIZE_T)(av->max_fast)) {
- fb = &(av->fastbins[(fastbin_index(nb))]);
- if ( (victim = *fb) != 0) {
- *fb = victim->fd;
- check_remalloced_chunk(victim, nb);
- return chunk2mem(victim);
- }
- }
-
- /*
- If a small request, check regular bin. Since these "smallbins"
- hold one size each, no searching within bins is necessary.
- (For a large request, we need to wait until unsorted chunks are
- processed to find best fit. But for small ones, fits are exact
- anyway, so we can check now, which is faster.)
- */
-
- if (in_smallbin_range(nb)) {
- idx = smallbin_index(nb);
- bin = bin_at(av,idx);
-
- if ( (victim = last(bin)) != bin) {
- bck = victim->bk;
- set_inuse_bit_at_offset(victim, nb);
- bin->bk = bck;
- bck->fd = bin;
-
- check_malloced_chunk(victim, nb);
- return chunk2mem(victim);
- }
- }
-
- /*
- If this is a large request, consolidate fastbins before continuing.
- While it might look excessive to kill all fastbins before
- even seeing if there is space available, this avoids
- fragmentation problems normally associated with fastbins.
- Also, in practice, programs tend to have runs of either small or
- large requests, but less often mixtures, so consolidation is not
- invoked all that often in most programs. And the programs that
- it is called frequently in otherwise tend to fragment.
- */
-
- else {
- idx = largebin_index(nb);
- if (have_fastchunks(av))
- malloc_consolidate(av);
- }
-
- /*
- Process recently freed or remaindered chunks, taking one only if
- it is exact fit, or, if this a small request, the chunk is remainder from
- the most recent non-exact fit. Place other traversed chunks in
- bins. Note that this step is the only place in any routine where
- chunks are placed in bins.
- */
-
- while ( (victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) {
- bck = victim->bk;
- size = chunksize(victim);
-
- /*
- If a small request, try to use last remainder if it is the
- only chunk in unsorted bin. This helps promote locality for
- runs of consecutive small requests. This is the only
- exception to best-fit, and applies only when there is
- no exact fit for a small chunk.
- */
-
- if (in_smallbin_range(nb) &&
- bck == unsorted_chunks(av) &&
- victim == av->last_remainder &&
- (CHUNK_SIZE_T)(size) > (CHUNK_SIZE_T)(nb + MINSIZE)) {
-
- /* split and reattach remainder */
- remainder_size = size - nb;
- remainder = chunk_at_offset(victim, nb);
- unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
- av->last_remainder = remainder;
- remainder->bk = remainder->fd = unsorted_chunks(av);
-
- set_head(victim, nb | PREV_INUSE);
- set_head(remainder, remainder_size | PREV_INUSE);
- set_foot(remainder, remainder_size);
-
- check_malloced_chunk(victim, nb);
- return chunk2mem(victim);
- }
-
- /* remove from unsorted list */
- unsorted_chunks(av)->bk = bck;
- bck->fd = unsorted_chunks(av);
-
- /* Take now instead of binning if exact fit */
-
- if (size == nb) {
- set_inuse_bit_at_offset(victim, size);
- check_malloced_chunk(victim, nb);
- return chunk2mem(victim);
- }
-
- /* place chunk in bin */
-
- if (in_smallbin_range(size)) {
- victim_index = smallbin_index(size);
- bck = bin_at(av, victim_index);
- fwd = bck->fd;
- }
- else {
- victim_index = largebin_index(size);
- bck = bin_at(av, victim_index);
- fwd = bck->fd;
-
- if (fwd != bck) {
- /* if smaller than smallest, place first */
- if ((CHUNK_SIZE_T)(size) < (CHUNK_SIZE_T)(bck->bk->size)) {
- fwd = bck;
- bck = bck->bk;
- }
- else if ((CHUNK_SIZE_T)(size) >=
- (CHUNK_SIZE_T)(FIRST_SORTED_BIN_SIZE)) {
-
- /* maintain large bins in sorted order */
- size |= PREV_INUSE; /* Or with inuse bit to speed comparisons */
- while ((CHUNK_SIZE_T)(size) < (CHUNK_SIZE_T)(fwd->size))
- fwd = fwd->fd;
- bck = fwd->bk;
- }
- }
- }
-
- mark_bin(av, victim_index);
- victim->bk = bck;
- victim->fd = fwd;
- fwd->bk = victim;
- bck->fd = victim;
- }
-
- /*
- If a large request, scan through the chunks of current bin to
- find one that fits. (This will be the smallest that fits unless
- FIRST_SORTED_BIN_SIZE has been changed from default.) This is
- the only step where an unbounded number of chunks might be
- scanned without doing anything useful with them. However the
- lists tend to be short.
- */
-
- if (!in_smallbin_range(nb)) {
- bin = bin_at(av, idx);
-
- for (victim = last(bin); victim != bin; victim = victim->bk) {
- size = chunksize(victim);
-
- if ((CHUNK_SIZE_T)(size) >= (CHUNK_SIZE_T)(nb)) {
- remainder_size = size - nb;
- unlink(victim, bck, fwd);
-
- /* Exhaust */
- if (remainder_size < MINSIZE) {
- set_inuse_bit_at_offset(victim, size);
- check_malloced_chunk(victim, nb);
- return chunk2mem(victim);
- }
- /* Split */
- else {
- remainder = chunk_at_offset(victim, nb);
- unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
- remainder->bk = remainder->fd = unsorted_chunks(av);
- set_head(victim, nb | PREV_INUSE);
- set_head(remainder, remainder_size | PREV_INUSE);
- set_foot(remainder, remainder_size);
- check_malloced_chunk(victim, nb);
- return chunk2mem(victim);
- }
- }
- }
- }
-
- /*
- Search for a chunk by scanning bins, starting with next largest
- bin. This search is strictly by best-fit; i.e., the smallest
- (with ties going to approximately the least recently used) chunk
- that fits is selected.
-
- The bitmap avoids needing to check that most blocks are nonempty.
- */
-
- ++idx;
- bin = bin_at(av,idx);
- block = idx2block(idx);
- map = av->binmap[block];
- bit = idx2bit(idx);
-
- for (;;) {
-
- /* Skip rest of block if there are no more set bits in this block. */
- if (bit > map || bit == 0) {
- do {
- if (++block >= BINMAPSIZE) /* out of bins */
- goto use_top;
- } while ( (map = av->binmap[block]) == 0);
-
- bin = bin_at(av, (block << BINMAPSHIFT));
- bit = 1;
- }
-
- /* Advance to bin with set bit. There must be one. */
- while ((bit & map) == 0) {
- bin = next_bin(bin);
- bit <<= 1;
- assert(bit != 0);
- }
-
- /* Inspect the bin. It is likely to be non-empty */
- victim = last(bin);
-
- /* If a false alarm (empty bin), clear the bit. */
- if (victim == bin) {
- av->binmap[block] = map &= ~bit; /* Write through */
- bin = next_bin(bin);
- bit <<= 1;
- }
-
- else {
- size = chunksize(victim);
-
- /* We know the first chunk in this bin is big enough to use. */
- assert((CHUNK_SIZE_T)(size) >= (CHUNK_SIZE_T)(nb));
-
- remainder_size = size - nb;
-
- /* unlink */
- bck = victim->bk;
- bin->bk = bck;
- bck->fd = bin;
-
- /* Exhaust */
- if (remainder_size < MINSIZE) {
- set_inuse_bit_at_offset(victim, size);
- check_malloced_chunk(victim, nb);
- return chunk2mem(victim);
- }
-
- /* Split */
- else {
- remainder = chunk_at_offset(victim, nb);
-
- unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
- remainder->bk = remainder->fd = unsorted_chunks(av);
- /* advertise as last remainder */
- if (in_smallbin_range(nb))
- av->last_remainder = remainder;
-
- set_head(victim, nb | PREV_INUSE);
- set_head(remainder, remainder_size | PREV_INUSE);
- set_foot(remainder, remainder_size);
- check_malloced_chunk(victim, nb);
- return chunk2mem(victim);
- }
- }
- }
-
- use_top:
- /*
- If large enough, split off the chunk bordering the end of memory
- (held in av->top). Note that this is in accord with the best-fit
- search rule. In effect, av->top is treated as larger (and thus
- less well fitting) than any other available chunk since it can
- be extended to be as large as necessary (up to system
- limitations).
-
- We require that av->top always exists (i.e., has size >=
- MINSIZE) after initialization, so if it would otherwise be
- exhuasted by current request, it is replenished. (The main
- reason for ensuring it exists is that we may need MINSIZE space
- to put in fenceposts in sysmalloc.)
- */
-
- victim = av->top;
- size = chunksize(victim);
-
- if ((CHUNK_SIZE_T)(size) >= (CHUNK_SIZE_T)(nb + MINSIZE)) {
- remainder_size = size - nb;
- remainder = chunk_at_offset(victim, nb);
- av->top = remainder;
- set_head(victim, nb | PREV_INUSE);
- set_head(remainder, remainder_size | PREV_INUSE);
-
- check_malloced_chunk(victim, nb);
- return chunk2mem(victim);
- }
-
- /*
- If no space in top, relay to handle system-dependent cases
- */
- return sYSMALLOc(nb, av);
-}
-
-/*
- ------------------------------ free ------------------------------
-*/
-
-#if __STD_C
-void fREe(Void_t* mem)
-#else
-void fREe(mem) Void_t* mem;
-#endif
-{
- mstate av = get_malloc_state();
-
- mchunkptr p; /* chunk corresponding to mem */
- INTERNAL_SIZE_T size; /* its size */
- mfastbinptr* fb; /* associated fastbin */
- mchunkptr nextchunk; /* next contiguous chunk */
- INTERNAL_SIZE_T nextsize; /* its size */
- int nextinuse; /* true if nextchunk is used */
- INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
- mchunkptr bck; /* misc temp for linking */
- mchunkptr fwd; /* misc temp for linking */
-
- /* free(0) has no effect */
- if (mem != 0) {
- p = mem2chunk(mem);
- size = chunksize(p);
-
- check_inuse_chunk(p);
-
- /*
- If eligible, place chunk on a fastbin so it can be found
- and used quickly in malloc.
- */
-
- if ((CHUNK_SIZE_T)(size) <= (CHUNK_SIZE_T)(av->max_fast)
-
-#if TRIM_FASTBINS
- /*
- If TRIM_FASTBINS set, don't place chunks
- bordering top into fastbins
- */
- && (chunk_at_offset(p, size) != av->top)
-#endif
- ) {
-
- set_fastchunks(av);
- fb = &(av->fastbins[fastbin_index(size)]);
- p->fd = *fb;
- *fb = p;
- }
-
- /*
- Consolidate other non-mmapped chunks as they arrive.
- */
-
- else if (!chunk_is_mmapped(p)) {
- set_anychunks(av);
-
- nextchunk = chunk_at_offset(p, size);
- nextsize = chunksize(nextchunk);
-
- /* consolidate backward */
- if (!prev_inuse(p)) {
- prevsize = p->prev_size;
- size += prevsize;
- p = chunk_at_offset(p, -((long) prevsize));
- unlink(p, bck, fwd);
- }
-
- if (nextchunk != av->top) {
- /* get and clear inuse bit */
- nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
- set_head(nextchunk, nextsize);
-
- /* consolidate forward */
- if (!nextinuse) {
- unlink(nextchunk, bck, fwd);
- size += nextsize;
- }
-
- /*
- Place the chunk in unsorted chunk list. Chunks are
- not placed into regular bins until after they have
- been given one chance to be used in malloc.
- */
-
- bck = unsorted_chunks(av);
- fwd = bck->fd;
- p->bk = bck;
- p->fd = fwd;
- bck->fd = p;
- fwd->bk = p;
-
- set_head(p, size | PREV_INUSE);
- set_foot(p, size);
-
- check_free_chunk(p);
- }
-
- /*
- If the chunk borders the current high end of memory,
- consolidate into top
- */
-
- else {
- size += nextsize;
- set_head(p, size | PREV_INUSE);
- av->top = p;
- check_chunk(p);
- }
-
- /*
- If freeing a large space, consolidate possibly-surrounding
- chunks. Then, if the total unused topmost memory exceeds trim
- threshold, ask malloc_trim to reduce top.
-
- Unless max_fast is 0, we don't know if there are fastbins
- bordering top, so we cannot tell for sure whether threshold
- has been reached unless fastbins are consolidated. But we
- don't want to consolidate on each free. As a compromise,
- consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
- is reached.
- */
-
- if ((CHUNK_SIZE_T)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
- if (have_fastchunks(av))
- malloc_consolidate(av);
-
-#ifndef MORECORE_CANNOT_TRIM
- if ((CHUNK_SIZE_T)(chunksize(av->top)) >=
- (CHUNK_SIZE_T)(av->trim_threshold))
- sYSTRIm(av->top_pad, av);
-#endif
- }
-
- }
- /*
- If the chunk was allocated via mmap, release via munmap()
- Note that if HAVE_MMAP is false but chunk_is_mmapped is
- true, then user must have overwritten memory. There's nothing
- we can do to catch this error unless DL_DEBUG is set, in which case
- check_inuse_chunk (above) will have triggered error.
- */
-
- else {
-#if HAVE_MMAP
- int ret;
- INTERNAL_SIZE_T offset = p->prev_size;
- av->n_mmaps--;
- av->mmapped_mem -= (size + offset);
- ret = munmap((char*)p - offset, size + offset);
- /* munmap returns non-zero on failure */
- assert(ret == 0);
-#endif
- }
- }
-}
-
-/*
- ------------------------- malloc_consolidate -------------------------
-
- malloc_consolidate is a specialized version of free() that tears
- down chunks held in fastbins. Free itself cannot be used for this
- purpose since, among other things, it might place chunks back onto
- fastbins. So, instead, we need to use a minor variant of the same
- code.
-
- Also, because this routine needs to be called the first time through
- malloc anyway, it turns out to be the perfect place to trigger
- initialization code.
-*/
-
-#if __STD_C
-static void malloc_consolidate(mstate av)
-#else
-static void malloc_consolidate(av) mstate av;
-#endif
-{
- mfastbinptr* fb; /* current fastbin being consolidated */
- mfastbinptr* maxfb; /* last fastbin (for loop control) */
- mchunkptr p; /* current chunk being consolidated */
- mchunkptr nextp; /* next chunk to consolidate */
- mchunkptr unsorted_bin; /* bin header */
- mchunkptr first_unsorted; /* chunk to link to */
-
- /* These have same use as in free() */
- mchunkptr nextchunk;
- INTERNAL_SIZE_T size;
- INTERNAL_SIZE_T nextsize;
- INTERNAL_SIZE_T prevsize;
- int nextinuse;
- mchunkptr bck;
- mchunkptr fwd;
-
- /*
- If max_fast is 0, we know that av hasn't
- yet been initialized, in which case do so below
- */
-
- if (av->max_fast != 0) {
- clear_fastchunks(av);
-
- unsorted_bin = unsorted_chunks(av);
-
- /*
- Remove each chunk from fast bin and consolidate it, placing it
- then in unsorted bin. Among other reasons for doing this,
- placing in unsorted bin avoids needing to calculate actual bins
- until malloc is sure that chunks aren't immediately going to be
- reused anyway.
- */
-
- maxfb = &(av->fastbins[fastbin_index(av->max_fast)]);
- fb = &(av->fastbins[0]);
- do {
- if ( (p = *fb) != 0) {
- *fb = 0;
-
- do {
- check_inuse_chunk(p);
- nextp = p->fd;
-
- /* Slightly streamlined version of consolidation code in free() */
- size = p->size & ~PREV_INUSE;
- nextchunk = chunk_at_offset(p, size);
- nextsize = chunksize(nextchunk);
-
- if (!prev_inuse(p)) {
- prevsize = p->prev_size;
- size += prevsize;
- p = chunk_at_offset(p, -((long) prevsize));
- unlink(p, bck, fwd);
- }
-
- if (nextchunk != av->top) {
- nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
- set_head(nextchunk, nextsize);
-
- if (!nextinuse) {
- size += nextsize;
- unlink(nextchunk, bck, fwd);
- }
-
- first_unsorted = unsorted_bin->fd;
- unsorted_bin->fd = p;
- first_unsorted->bk = p;
-
- set_head(p, size | PREV_INUSE);
- p->bk = unsorted_bin;
- p->fd = first_unsorted;
- set_foot(p, size);
- }
-
- else {
- size += nextsize;
- set_head(p, size | PREV_INUSE);
- av->top = p;
- }
-
- } while ( (p = nextp) != 0);
-
- }
- } while (fb++ != maxfb);
- }
- else {
- malloc_init_state(av);
- check_malloc_state();
- }
-}
-
-/*
- ------------------------------ realloc ------------------------------
-*/
-
-
-#if __STD_C
-Void_t* rEALLOc(Void_t* oldmem, size_t bytes)
-#else
-Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes;
-#endif
-{
- mstate av = get_malloc_state();
-
- INTERNAL_SIZE_T nb; /* padded request size */
-
- mchunkptr oldp; /* chunk corresponding to oldmem */
- INTERNAL_SIZE_T oldsize; /* its size */
-
- mchunkptr newp; /* chunk to return */
- INTERNAL_SIZE_T newsize; /* its size */
- Void_t* newmem; /* corresponding user mem */
-
- mchunkptr next; /* next contiguous chunk after oldp */
-
- mchunkptr remainder; /* extra space at end of newp */
- CHUNK_SIZE_T remainder_size; /* its size */
-
- mchunkptr bck; /* misc temp for linking */
- mchunkptr fwd; /* misc temp for linking */
-
- CHUNK_SIZE_T copysize; /* bytes to copy */
- unsigned int ncopies; /* INTERNAL_SIZE_T words to copy */
- INTERNAL_SIZE_T* s; /* copy source */
- INTERNAL_SIZE_T* d; /* copy destination */
-
-
-#ifdef REALLOC_ZERO_BYTES_FREES
- if (bytes == 0) {
- fREe(oldmem);
- return 0;
- }
-#endif
-
- /* realloc of null is supposed to be same as malloc */
- if (oldmem == 0) return mALLOc(bytes);
-
- checked_request2size(bytes, nb);
-
- oldp = mem2chunk(oldmem);
- oldsize = chunksize(oldp);
-
- check_inuse_chunk(oldp);
-
- if (!chunk_is_mmapped(oldp)) {
-
- if ((CHUNK_SIZE_T)(oldsize) >= (CHUNK_SIZE_T)(nb)) {
- /* already big enough; split below */
- newp = oldp;
- newsize = oldsize;
- }
-
- else {
- next = chunk_at_offset(oldp, oldsize);
-
- /* Try to expand forward into top */
- if (next == av->top &&
- (CHUNK_SIZE_T)(newsize = oldsize + chunksize(next)) >=
- (CHUNK_SIZE_T)(nb + MINSIZE)) {
- set_head_size(oldp, nb);
- av->top = chunk_at_offset(oldp, nb);
- set_head(av->top, (newsize - nb) | PREV_INUSE);
- return chunk2mem(oldp);
- }
-
- /* Try to expand forward into next chunk; split off remainder below */
- else if (next != av->top &&
- !inuse(next) &&
- (CHUNK_SIZE_T)(newsize = oldsize + chunksize(next)) >=
- (CHUNK_SIZE_T)(nb)) {
- newp = oldp;
- unlink(next, bck, fwd);
- }
-
- /* allocate, copy, free */
- else {
- newmem = mALLOc(nb - MALLOC_ALIGN_MASK);
- if (newmem == 0)
- return 0; /* propagate failure */
-
- newp = mem2chunk(newmem);
- newsize = chunksize(newp);
-
- /*
- Avoid copy if newp is next chunk after oldp.
- */
- if (newp == next) {
- newsize += oldsize;
- newp = oldp;
- }
- else {
- /*
- Unroll copy of <= 36 bytes (72 if 8byte sizes)
- We know that contents have an odd number of
- INTERNAL_SIZE_T-sized words; minimally 3.
- */
-
- copysize = oldsize - SIZE_SZ;
- s = (INTERNAL_SIZE_T*)(oldmem);
- d = (INTERNAL_SIZE_T*)(newmem);
- ncopies = copysize / sizeof(INTERNAL_SIZE_T);
- assert(ncopies >= 3);
-
- if (ncopies > 9)
- MALLOC_COPY(d, s, copysize);
-
- else {
- *(d+0) = *(s+0);
- *(d+1) = *(s+1);
- *(d+2) = *(s+2);
- if (ncopies > 4) {
- *(d+3) = *(s+3);
- *(d+4) = *(s+4);
- if (ncopies > 6) {
- *(d+5) = *(s+5);
- *(d+6) = *(s+6);
- if (ncopies > 8) {
- *(d+7) = *(s+7);
- *(d+8) = *(s+8);
- }
- }
- }
- }
-
- fREe(oldmem);
- check_inuse_chunk(newp);
- return chunk2mem(newp);
- }
- }
- }
-
- /* If possible, free extra space in old or extended chunk */
-
- assert((CHUNK_SIZE_T)(newsize) >= (CHUNK_SIZE_T)(nb));
-
- remainder_size = newsize - nb;
-
- if (remainder_size < MINSIZE) { /* not enough extra to split off */
- set_head_size(newp, newsize);
- set_inuse_bit_at_offset(newp, newsize);
- }
- else { /* split remainder */
- remainder = chunk_at_offset(newp, nb);
- set_head_size(newp, nb);
- set_head(remainder, remainder_size | PREV_INUSE);
- /* Mark remainder as inuse so free() won't complain */
- set_inuse_bit_at_offset(remainder, remainder_size);
- fREe(chunk2mem(remainder));
- }
-
- check_inuse_chunk(newp);
- return chunk2mem(newp);
- }
-
- /*
- Handle mmap cases
- */
-
- else {
-#if HAVE_MMAP
-
-#if HAVE_MREMAP
- INTERNAL_SIZE_T offset = oldp->prev_size;
- size_t pagemask = av->pagesize - 1;
- char *cp;
- CHUNK_SIZE_T sum;
-
- /* Note the extra SIZE_SZ overhead */
- newsize = (nb + offset + SIZE_SZ + pagemask) & ~pagemask;
-
- /* don't need to remap if still within same page */
- if (oldsize == newsize - offset)
- return oldmem;
-
- cp = (char*)mremap((char*)oldp - offset, oldsize + offset, newsize, 1);
-
- if (cp != (char*)MORECORE_FAILURE) {
-
- newp = (mchunkptr)(cp + offset);
- set_head(newp, (newsize - offset)|IS_MMAPPED);
-
- assert(aligned_OK(chunk2mem(newp)));
- assert((newp->prev_size == offset));
-
- /* update statistics */
- sum = av->mmapped_mem += newsize - oldsize;
- if (sum > (CHUNK_SIZE_T)(av->max_mmapped_mem))
- av->max_mmapped_mem = sum;
- sum += av->sbrked_mem;
- if (sum > (CHUNK_SIZE_T)(av->max_total_mem))
- av->max_total_mem = sum;
-
- return chunk2mem(newp);
- }
-#endif
-
- /* Note the extra SIZE_SZ overhead. */
- if ((CHUNK_SIZE_T)(oldsize) >= (CHUNK_SIZE_T)(nb + SIZE_SZ))
- newmem = oldmem; /* do nothing */
- else {
- /* Must alloc, copy, free. */
- newmem = mALLOc(nb - MALLOC_ALIGN_MASK);
- if (newmem != 0) {
- MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);
- fREe(oldmem);
- }
- }
- return newmem;
-
-#else
- /* If !HAVE_MMAP, but chunk_is_mmapped, user must have overwritten mem */
- check_malloc_state();
- MALLOC_FAILURE_ACTION;
- return 0;
-#endif
- }
-}
-
-/*
- ------------------------------ memalign ------------------------------
-*/
-
-#if __STD_C
-Void_t* mEMALIGn(size_t alignment, size_t bytes)
-#else
-Void_t* mEMALIGn(alignment, bytes) size_t alignment; size_t bytes;
-#endif
-{
- INTERNAL_SIZE_T nb; /* padded request size */
- char* m; /* memory returned by malloc call */
- mchunkptr p; /* corresponding chunk */
- char* brk; /* alignment point within p */
- mchunkptr newp; /* chunk to return */
- INTERNAL_SIZE_T newsize; /* its size */
- INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
- mchunkptr remainder; /* spare room at end to split off */
- CHUNK_SIZE_T remainder_size; /* its size */
- INTERNAL_SIZE_T size;
-
- /* If need less alignment than we give anyway, just relay to malloc */
-
- if (alignment <= MALLOC_ALIGNMENT) return mALLOc(bytes);
-
- /* Otherwise, ensure that it is at least a minimum chunk size */
-
- if (alignment < MINSIZE) alignment = MINSIZE;
-
- /* Make sure alignment is power of 2 (in case MINSIZE is not). */
- if ((alignment & (alignment - 1)) != 0) {
- size_t a = MALLOC_ALIGNMENT * 2;
- while ((CHUNK_SIZE_T)a < (CHUNK_SIZE_T)alignment) a <<= 1;
- alignment = a;
- }
-
- checked_request2size(bytes, nb);
-
- /*
- Strategy: find a spot within that chunk that meets the alignment
- request, and then possibly free the leading and trailing space.
- */
-
-
- /* Call malloc with worst case padding to hit alignment. */
-
- m = (char*)(mALLOc(nb + alignment + MINSIZE));
-
- if (m == 0) return 0; /* propagate failure */
-
- p = mem2chunk(m);
-
- if ((((PTR_UINT)(m)) % alignment) != 0) { /* misaligned */
-
- /*
- Find an aligned spot inside chunk. Since we need to give back
- leading space in a chunk of at least MINSIZE, if the first
- calculation places us at a spot with less than MINSIZE leader,
- we can move to the next aligned spot -- we've allocated enough
- total room so that this is always possible.
- */
-
- brk = (char*)mem2chunk((PTR_UINT)(((PTR_UINT)(m + alignment - 1)) &
- -((signed long) alignment)));
- if ((CHUNK_SIZE_T)(brk - (char*)(p)) < MINSIZE)
- brk += alignment;
-
- newp = (mchunkptr)brk;
- leadsize = brk - (char*)(p);
- newsize = chunksize(p) - leadsize;
-
- /* For mmapped chunks, just adjust offset */
- if (chunk_is_mmapped(p)) {
- newp->prev_size = p->prev_size + leadsize;
- set_head(newp, newsize|IS_MMAPPED);
- return chunk2mem(newp);
- }
-
- /* Otherwise, give back leader, use the rest */
- set_head(newp, newsize | PREV_INUSE);
- set_inuse_bit_at_offset(newp, newsize);
- set_head_size(p, leadsize);
- fREe(chunk2mem(p));
- p = newp;
-
- assert (newsize >= nb &&
- (((PTR_UINT)(chunk2mem(p))) % alignment) == 0);
- }
-
- /* Also give back spare room at the end */
- if (!chunk_is_mmapped(p)) {
- size = chunksize(p);
- if ((CHUNK_SIZE_T)(size) > (CHUNK_SIZE_T)(nb + MINSIZE)) {
- remainder_size = size - nb;
- remainder = chunk_at_offset(p, nb);
- set_head(remainder, remainder_size | PREV_INUSE);
- set_head_size(p, nb);
- fREe(chunk2mem(remainder));
- }
- }
-
- check_inuse_chunk(p);
- return chunk2mem(p);
-}
-
-/*
- ------------------------------ calloc ------------------------------
-*/
-
-#if __STD_C
-Void_t* cALLOc(size_t n_elements, size_t elem_size)
-#else
-Void_t* cALLOc(n_elements, elem_size) size_t n_elements; size_t elem_size;
-#endif
-{
- mchunkptr p;
- CHUNK_SIZE_T clearsize;
- CHUNK_SIZE_T nclears;
- INTERNAL_SIZE_T* d;
-
- Void_t* mem = mALLOc(n_elements * elem_size);
-
- if (mem != 0) {
- p = mem2chunk(mem);
-
- if (!chunk_is_mmapped(p))
- {
- /*
- Unroll clear of <= 36 bytes (72 if 8byte sizes)
- We know that contents have an odd number of
- INTERNAL_SIZE_T-sized words; minimally 3.
- */
-
- d = (INTERNAL_SIZE_T*)mem;
- clearsize = chunksize(p) - SIZE_SZ;
- nclears = clearsize / sizeof(INTERNAL_SIZE_T);
- assert(nclears >= 3);
-
- if (nclears > 9)
- MALLOC_ZERO(d, clearsize);
-
- else {
- *(d+0) = 0;
- *(d+1) = 0;
- *(d+2) = 0;
- if (nclears > 4) {
- *(d+3) = 0;
- *(d+4) = 0;
- if (nclears > 6) {
- *(d+5) = 0;
- *(d+6) = 0;
- if (nclears > 8) {
- *(d+7) = 0;
- *(d+8) = 0;
- }
- }
- }
- }
- }
-#if ! MMAP_CLEARS
- else
- {
- d = (INTERNAL_SIZE_T*)mem;
- /*
- Note the additional SIZE_SZ
- */
- clearsize = chunksize(p) - 2*SIZE_SZ;
- MALLOC_ZERO(d, clearsize);
- }
-#endif
- }
- return mem;
-}
-
-/*
- ------------------------------ cfree ------------------------------
-*/
-
-#if __STD_C
-void cFREe(Void_t *mem)
-#else
-void cFREe(mem) Void_t *mem;
-#endif
-{
- fREe(mem);
-}
-
-/*
- ------------------------- independent_calloc -------------------------
-*/
-
-#if __STD_C
-Void_t** iCALLOc(size_t n_elements, size_t elem_size, Void_t* chunks[])
-#else
-Void_t** iCALLOc(n_elements, elem_size, chunks) size_t n_elements; size_t elem_size; Void_t* chunks[];
-#endif
-{
- size_t sz = elem_size; /* serves as 1-element array */
- /* opts arg of 3 means all elements are same size, and should be cleared */
- return iALLOc(n_elements, &sz, 3, chunks);
-}
-
-/*
- ------------------------- independent_comalloc -------------------------
-*/
-
-#if __STD_C
-Void_t** iCOMALLOc(size_t n_elements, size_t sizes[], Void_t* chunks[])
-#else
-Void_t** iCOMALLOc(n_elements, sizes, chunks) size_t n_elements; size_t sizes[]; Void_t* chunks[];
-#endif
-{
- return iALLOc(n_elements, sizes, 0, chunks);
-}
-
-
-/*
- ------------------------------ ialloc ------------------------------
- ialloc provides common support for independent_X routines, handling all of
- the combinations that can result.
-
- The opts arg has:
- bit 0 set if all elements are same size (using sizes[0])
- bit 1 set if elements should be zeroed
-*/
-
-
-#if __STD_C
-static Void_t** iALLOc(size_t n_elements,
- size_t* sizes,
- int opts,
- Void_t* chunks[])
-#else
-static Void_t** iALLOc(n_elements, sizes, opts, chunks) size_t n_elements; size_t* sizes; int opts; Void_t* chunks[];
-#endif
-{
- mstate av = get_malloc_state();
- INTERNAL_SIZE_T element_size; /* chunksize of each element, if all same */
- INTERNAL_SIZE_T contents_size; /* total size of elements */
- INTERNAL_SIZE_T array_size; /* request size of pointer array */
- Void_t* mem; /* malloced aggregate space */
- mchunkptr p; /* corresponding chunk */
- INTERNAL_SIZE_T remainder_size; /* remaining bytes while splitting */
- Void_t** marray; /* either "chunks" or malloced ptr array */
- mchunkptr array_chunk; /* chunk for malloced ptr array */
- int mmx; /* to disable mmap */
- INTERNAL_SIZE_T size;
- size_t i;
-
- /* Ensure initialization */
- if (av->max_fast == 0) malloc_consolidate(av);
-
- /* compute array length, if needed */
- if (chunks != 0) {
- if (n_elements == 0)
- return chunks; /* nothing to do */
- marray = chunks;
- array_size = 0;
- }
- else {
- /* if empty req, must still return chunk representing empty array */
- if (n_elements == 0)
- return (Void_t**) mALLOc(0);
- marray = 0;
- array_size = request2size(n_elements * (sizeof(Void_t*)));
- }
-
- /* compute total element size */
- if (opts & 0x1) { /* all-same-size */
- element_size = request2size(*sizes);
- contents_size = n_elements * element_size;
- }
- else { /* add up all the sizes */
- element_size = 0;
- contents_size = 0;
- for (i = 0; i != n_elements; ++i)
- contents_size += request2size(sizes[i]);
- }
-
- /* subtract out alignment bytes from total to minimize overallocation */
- size = contents_size + array_size - MALLOC_ALIGN_MASK;
-
- /*
- Allocate the aggregate chunk.
- But first disable mmap so malloc won't use it, since
- we would not be able to later free/realloc space internal
- to a segregated mmap region.
- */
- mmx = av->n_mmaps_max; /* disable mmap */
- av->n_mmaps_max = 0;
- mem = mALLOc(size);
- av->n_mmaps_max = mmx; /* reset mmap */
- if (mem == 0)
- return 0;
-
- p = mem2chunk(mem);
- assert(!chunk_is_mmapped(p));
- remainder_size = chunksize(p);
-
- if (opts & 0x2) { /* optionally clear the elements */
- MALLOC_ZERO(mem, remainder_size - SIZE_SZ - array_size);
- }
-
- /* If not provided, allocate the pointer array as final part of chunk */
- if (marray == 0) {
- array_chunk = chunk_at_offset(p, contents_size);
- marray = (Void_t**) (chunk2mem(array_chunk));
- set_head(array_chunk, (remainder_size - contents_size) | PREV_INUSE);
- remainder_size = contents_size;
- }
-
- /* split out elements */
- for (i = 0; ; ++i) {
- marray[i] = chunk2mem(p);
- if (i != n_elements-1) {
- if (element_size != 0)
- size = element_size;
- else
- size = request2size(sizes[i]);
- remainder_size -= size;
- set_head(p, size | PREV_INUSE);
- p = chunk_at_offset(p, size);
- }
- else { /* the final element absorbs any overallocation slop */
- set_head(p, remainder_size | PREV_INUSE);
- break;
- }
- }
-
-#if DL_DEBUG
- if (marray != chunks) {
- /* final element must have exactly exhausted chunk */
- if (element_size != 0)
- assert(remainder_size == element_size);
- else
- assert(remainder_size == request2size(sizes[i]));
- check_inuse_chunk(mem2chunk(marray));
- }
-
- for (i = 0; i != n_elements; ++i)
- check_inuse_chunk(mem2chunk(marray[i]));
-#endif
-
- return marray;
-}
-
-
-/*
- ------------------------------ valloc ------------------------------
-*/
-
-#if __STD_C
-Void_t* vALLOc(size_t bytes)
-#else
-Void_t* vALLOc(bytes) size_t bytes;
-#endif
-{
- /* Ensure initialization */
- mstate av = get_malloc_state();
- if (av->max_fast == 0) malloc_consolidate(av);
- return mEMALIGn(av->pagesize, bytes);
-}
-
-/*
- ------------------------------ pvalloc ------------------------------
-*/
-
-
-#if __STD_C
-Void_t* pVALLOc(size_t bytes)
-#else
-Void_t* pVALLOc(bytes) size_t bytes;
-#endif
-{
- mstate av = get_malloc_state();
- size_t pagesz;
-
- /* Ensure initialization */
- if (av->max_fast == 0) malloc_consolidate(av);
- pagesz = av->pagesize;
- return mEMALIGn(pagesz, (bytes + pagesz - 1) & ~(pagesz - 1));
-}
-
-
-/*
- ------------------------------ malloc_trim ------------------------------
-*/
-
-#if __STD_C
-int mTRIm(size_t pad)
-#else
-int mTRIm(pad) size_t pad;
-#endif
-{
- mstate av = get_malloc_state();
- /* Ensure initialization/consolidation */
- malloc_consolidate(av);
-
-#ifndef MORECORE_CANNOT_TRIM
- return sYSTRIm(pad, av);
-#else
- return 0;
-#endif
-}
-
-
-/*
- ------------------------- malloc_usable_size -------------------------
-*/
-
-#if __STD_C
-size_t mUSABLe(Void_t* mem)
-#else
-size_t mUSABLe(mem) Void_t* mem;
-#endif
-{
- mchunkptr p;
- if (mem != 0) {
- p = mem2chunk(mem);
- if (chunk_is_mmapped(p))
- return chunksize(p) - 2*SIZE_SZ;
- else if (inuse(p))
- return chunksize(p) - SIZE_SZ;
- }
- return 0;
-}
-
-/*
- ------------------------------ mallinfo ------------------------------
-*/
-
-struct mallinfo mALLINFo()
-{
- mstate av = get_malloc_state();
- struct mallinfo mi;
- int i;
- mbinptr b;
- mchunkptr p;
- INTERNAL_SIZE_T avail;
- INTERNAL_SIZE_T fastavail;
- int nblocks;
- int nfastblocks;
-
- /* Ensure initialization */
- if (av->top == 0) malloc_consolidate(av);
-
- check_malloc_state();
-
- /* Account for top */
- avail = chunksize(av->top);
- nblocks = 1; /* top always exists */
-
- /* traverse fastbins */
- nfastblocks = 0;
- fastavail = 0;
-
- for (i = 0; i < NFASTBINS; ++i) {
- for (p = av->fastbins[i]; p != 0; p = p->fd) {
- ++nfastblocks;
- fastavail += chunksize(p);
- }
- }
-
- avail += fastavail;
-
- /* traverse regular bins */
- for (i = 1; i < NBINS; ++i) {
- b = bin_at(av, i);
- for (p = last(b); p != b; p = p->bk) {
- ++nblocks;
- avail += chunksize(p);
- }
- }
-
- mi.smblks = nfastblocks;
- mi.ordblks = nblocks;
- mi.fordblks = avail;
- mi.uordblks = av->sbrked_mem - avail;
- mi.arena = av->sbrked_mem;
- mi.hblks = av->n_mmaps;
- mi.hblkhd = av->mmapped_mem;
- mi.fsmblks = fastavail;
- mi.keepcost = chunksize(av->top);
- mi.usmblks = av->max_total_mem;
- return mi;
-}
-
-/*
- ------------------------------ malloc_stats ------------------------------
-*/
-
-void mSTATs(void)
-{
- struct mallinfo mi = mALLINFo();
-
-#ifdef WIN32
- {
- CHUNK_SIZE_T free, reserved, committed;
- vminfo (&free, &reserved, &committed);
- fprintf(stderr, "free bytes = %10lu\n",
- free);
- fprintf(stderr, "reserved bytes = %10lu\n",
- reserved);
- fprintf(stderr, "committed bytes = %10lu\n",
- committed);
- }
-#endif
-
-
- fprintf(stderr, "max system bytes = %10lu\n",
- (CHUNK_SIZE_T)(mi.usmblks));
- fprintf(stderr, "system bytes = %10lu\n",
- (CHUNK_SIZE_T)(mi.arena + mi.hblkhd));
- fprintf(stderr, "in use bytes = %10lu\n",
- (CHUNK_SIZE_T)(mi.uordblks + mi.hblkhd));
-
-#ifdef WIN32
- {
- CHUNK_SIZE_T kernel, user;
- if (cpuinfo (TRUE, &kernel, &user)) {
- fprintf(stderr, "kernel ms = %10lu\n",
- kernel);
- fprintf(stderr, "user ms = %10lu\n",
- user);
- }
- }
-#endif
-}
-
-
-/*
- ------------------------------ mallopt ------------------------------
-*/
-
-#if __STD_C
-int mALLOPt(int param_number, int value)
-#else
-int mALLOPt(param_number, value) int param_number; int value;
-#endif
-{
- mstate av = get_malloc_state();
- /* Ensure initialization/consolidation */
- malloc_consolidate(av);
-
- switch(param_number) {
- case M_MXFAST:
- if (value >= 0 && value <= MAX_FAST_SIZE) {
- set_max_fast(av, value);
- return 1;
- }
- else
- return 0;
-
- case M_TRIM_THRESHOLD:
- av->trim_threshold = value;
- return 1;
-
- case M_TOP_PAD:
- av->top_pad = value;
- return 1;
-
- case M_MMAP_THRESHOLD:
- av->mmap_threshold = value;
- return 1;
-
- case M_MMAP_MAX:
-#if !HAVE_MMAP
- if (value != 0)
- return 0;
-#endif
- av->n_mmaps_max = value;
- return 1;
-
- default:
- return 0;
- }
-}
-
-
-/*
- -------------------- Alternative MORECORE functions --------------------
-*/
-
-
-/*
- General Requirements for MORECORE.
-
- The MORECORE function must have the following properties:
-
- If MORECORE_CONTIGUOUS is false:
-
- * MORECORE must allocate in multiples of pagesize. It will
- only be called with arguments that are multiples of pagesize.
-
- * MORECORE(0) must return an address that is at least
- MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
-
- else (i.e. If MORECORE_CONTIGUOUS is true):
-
- * Consecutive calls to MORECORE with positive arguments
- return increasing addresses, indicating that space has been
- contiguously extended.
-
- * MORECORE need not allocate in multiples of pagesize.
- Calls to MORECORE need not have args of multiples of pagesize.
-
- * MORECORE need not page-align.
-
- In either case:
-
- * MORECORE may allocate more memory than requested. (Or even less,
- but this will generally result in a malloc failure.)
-
- * MORECORE must not allocate memory when given argument zero, but
- instead return one past the end address of memory from previous
- nonzero call. This malloc does NOT call MORECORE(0)
- until at least one call with positive arguments is made, so
- the initial value returned is not important.
-
- * Even though consecutive calls to MORECORE need not return contiguous
- addresses, it must be OK for malloc'ed chunks to span multiple
- regions in those cases where they do happen to be contiguous.
-
- * MORECORE need not handle negative arguments -- it may instead
- just return MORECORE_FAILURE when given negative arguments.
- Negative arguments are always multiples of pagesize. MORECORE
- must not misinterpret negative args as large positive unsigned
- args. You can suppress all such calls from even occurring by defining
- MORECORE_CANNOT_TRIM,
-
- There is some variation across systems about the type of the
- argument to sbrk/MORECORE. If size_t is unsigned, then it cannot
- actually be size_t, because sbrk supports negative args, so it is
- normally the signed type of the same width as size_t (sometimes
- declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much
- matter though. Internally, we use "long" as arguments, which should
- work across all reasonable possibilities.
-
- Additionally, if MORECORE ever returns failure for a positive
- request, and HAVE_MMAP is true, then mmap is used as a noncontiguous
- system allocator. This is a useful backup strategy for systems with
- holes in address spaces -- in this case sbrk cannot contiguously
- expand the heap, but mmap may be able to map noncontiguous space.
-
- If you'd like mmap to ALWAYS be used, you can define MORECORE to be
- a function that always returns MORECORE_FAILURE.
-
- Malloc only has limited ability to detect failures of MORECORE
- to supply contiguous space when it says it can. In particular,
- multithreaded programs that do not use locks may result in
- rece conditions across calls to MORECORE that result in gaps
- that cannot be detected as such, and subsequent corruption.
-
- If you are using this malloc with something other than sbrk (or its
- emulation) to supply memory regions, you probably want to set
- MORECORE_CONTIGUOUS as false. As an example, here is a custom
- allocator kindly contributed for pre-OSX macOS. It uses virtually
- but not necessarily physically contiguous non-paged memory (locked
- in, present and won't get swapped out). You can use it by
- uncommenting this section, adding some #includes, and setting up the
- appropriate defines above:
-
- #define MORECORE osMoreCore
- #define MORECORE_CONTIGUOUS 0
-
- There is also a shutdown routine that should somehow be called for
- cleanup upon program exit.
-
- #define MAX_POOL_ENTRIES 100
- #define MINIMUM_MORECORE_SIZE (64 * 1024)
- static int next_os_pool;
- void *our_os_pools[MAX_POOL_ENTRIES];
-
- void *osMoreCore(int size)
- {
- void *ptr = 0;
- static void *sbrk_top = 0;
-
- if (size > 0)
- {
- if (size < MINIMUM_MORECORE_SIZE)
- size = MINIMUM_MORECORE_SIZE;
- if (CurrentExecutionLevel() == kTaskLevel)
- ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
- if (ptr == 0)
- {
- return (void *) MORECORE_FAILURE;
- }
- // save ptrs so they can be freed during cleanup
- our_os_pools[next_os_pool] = ptr;
- next_os_pool++;
- ptr = (void *) ((((CHUNK_SIZE_T) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
- sbrk_top = (char *) ptr + size;
- return ptr;
- }
- else if (size < 0)
- {
- // we don't currently support shrink behavior
- return (void *) MORECORE_FAILURE;
- }
- else
- {
- return sbrk_top;
- }
- }
-
- // cleanup any allocated memory pools
- // called as last thing before shutting down driver
-
- void osCleanupMem(void)
- {
- void **ptr;
-
- for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
- if (*ptr)
- {
- PoolDeallocate(*ptr);
- *ptr = 0;
- }
- }
-
-*/
-
-
-/*
- --------------------------------------------------------------
-
- Emulation of sbrk for win32.
- Donated by J. Walter .
- For additional information about this code, and malloc on Win32, see
- http://www.genesys-e.de/jwalter/
-*/
-
-
-#ifdef WIN32
-
-#ifdef _DEBUG
-/* #define TRACE */
-#endif
-
-/* Support for USE_MALLOC_LOCK */
-#ifdef USE_MALLOC_LOCK
-
-/* Wait for spin lock */
-static int slwait (int *sl) {
- while (InterlockedCompareExchange ((void **) sl, (void *) 1, (void *) 0) != 0)
- Sleep (0);
- return 0;
-}
-
-/* Release spin lock */
-static int slrelease (int *sl) {
- InterlockedExchange (sl, 0);
- return 0;
-}
-
-#ifdef NEEDED
-/* Spin lock for emulation code */
-static int g_sl;
-#endif
-
-#endif /* USE_MALLOC_LOCK */
-
-/* getpagesize for windows */
-static long getpagesize (void) {
- static long g_pagesize = 0;
- if (! g_pagesize) {
- SYSTEM_INFO system_info;
- GetSystemInfo (&system_info);
- g_pagesize = system_info.dwPageSize;
- }
- return g_pagesize;
-}
-static long getregionsize (void) {
- static long g_regionsize = 0;
- if (! g_regionsize) {
- SYSTEM_INFO system_info;
- GetSystemInfo (&system_info);
- g_regionsize = system_info.dwAllocationGranularity;
- }
- return g_regionsize;
-}
-
-/* A region list entry */
-typedef struct _region_list_entry {
- void *top_allocated;
- void *top_committed;
- void *top_reserved;
- long reserve_size;
- struct _region_list_entry *previous;
-} region_list_entry;
-
-/* Allocate and link a region entry in the region list */
-static int region_list_append (region_list_entry **last, void *base_reserved, long reserve_size) {
- region_list_entry *next = HeapAlloc (GetProcessHeap (), 0, sizeof (region_list_entry));
- if (! next)
- return FALSE;
- next->top_allocated = (char *) base_reserved;
- next->top_committed = (char *) base_reserved;
- next->top_reserved = (char *) base_reserved + reserve_size;
- next->reserve_size = reserve_size;
- next->previous = *last;
- *last = next;
- return TRUE;
-}
-/* Free and unlink the last region entry from the region list */
-static int region_list_remove (region_list_entry **last) {
- region_list_entry *previous = (*last)->previous;
- if (! HeapFree (GetProcessHeap (), sizeof (region_list_entry), *last))
- return FALSE;
- *last = previous;
- return TRUE;
-}
-
-#define CEIL(size,to) (((size)+(to)-1)&~((to)-1))
-#define FLOOR(size,to) ((size)&~((to)-1))
-
-#define SBRK_SCALE 0
-/* #define SBRK_SCALE 1 */
-/* #define SBRK_SCALE 2 */
-/* #define SBRK_SCALE 4 */
-
-/* sbrk for windows */
-static void *sbrk (long size) {
- static long g_pagesize, g_my_pagesize;
- static long g_regionsize, g_my_regionsize;
- static region_list_entry *g_last;
- void *result = (void *) MORECORE_FAILURE;
-#ifdef TRACE
- printf ("sbrk %d\n", size);
-#endif
-#if defined (USE_MALLOC_LOCK) && defined (NEEDED)
- /* Wait for spin lock */
- slwait (&g_sl);
-#endif
- /* First time initialization */
- if (! g_pagesize) {
- g_pagesize = getpagesize ();
- g_my_pagesize = g_pagesize << SBRK_SCALE;
- }
- if (! g_regionsize) {
- g_regionsize = getregionsize ();
- g_my_regionsize = g_regionsize << SBRK_SCALE;
- }
- if (! g_last) {
- if (! region_list_append (&g_last, 0, 0))
- goto sbrk_exit;
- }
- /* Assert invariants */
- assert (g_last);
- assert ((char *) g_last->top_reserved - g_last->reserve_size <= (char *) g_last->top_allocated &&
- g_last->top_allocated <= g_last->top_committed);
- assert ((char *) g_last->top_reserved - g_last->reserve_size <= (char *) g_last->top_committed &&
- g_last->top_committed <= g_last->top_reserved &&
- (unsigned) g_last->top_committed % g_pagesize == 0);
- assert ((unsigned) g_last->top_reserved % g_regionsize == 0);
- assert ((unsigned) g_last->reserve_size % g_regionsize == 0);
- /* Allocation requested? */
- if (size >= 0) {
- /* Allocation size is the requested size */
- long allocate_size = size;
- /* Compute the size to commit */
- long to_commit = (char *) g_last->top_allocated + allocate_size - (char *) g_last->top_committed;
- /* Do we reach the commit limit? */
- if (to_commit > 0) {
- /* Round size to commit */
- long commit_size = CEIL (to_commit, g_my_pagesize);
- /* Compute the size to reserve */
- long to_reserve = (char *) g_last->top_committed + commit_size - (char *) g_last->top_reserved;
- /* Do we reach the reserve limit? */
- if (to_reserve > 0) {
- /* Compute the remaining size to commit in the current region */
- long remaining_commit_size = (char *) g_last->top_reserved - (char *) g_last->top_committed;
- if (remaining_commit_size > 0) {
- /* Assert preconditions */
- assert ((unsigned) g_last->top_committed % g_pagesize == 0);
- assert (0 < remaining_commit_size && remaining_commit_size % g_pagesize == 0); {
- /* Commit this */
- void *base_committed = VirtualAlloc (g_last->top_committed, remaining_commit_size,
- MEM_COMMIT, PAGE_READWRITE);
- /* Check returned pointer for consistency */
- if (base_committed != g_last->top_committed)
- goto sbrk_exit;
- /* Assert postconditions */
- assert ((unsigned) base_committed % g_pagesize == 0);
-#ifdef TRACE
- printf ("Commit %p %d\n", base_committed, remaining_commit_size);
-#endif
- /* Adjust the regions commit top */
- g_last->top_committed = (char *) base_committed + remaining_commit_size;
- }
- } {
- /* Now we are going to search and reserve. */
- int contiguous = -1;
- int found = FALSE;
- MEMORY_BASIC_INFORMATION memory_info;
- void *base_reserved;
- long reserve_size;
- do {
- /* Assume contiguous memory */
- contiguous = TRUE;
- /* Round size to reserve */
- reserve_size = CEIL (to_reserve, g_my_regionsize);
- /* Start with the current region's top */
- memory_info.BaseAddress = g_last->top_reserved;
- /* Assert preconditions */
- assert ((unsigned) memory_info.BaseAddress % g_pagesize == 0);
- assert (0 < reserve_size && reserve_size % g_regionsize == 0);
- while (VirtualQuery (memory_info.BaseAddress, &memory_info, sizeof (memory_info))) {
- /* Assert postconditions */
- assert ((unsigned) memory_info.BaseAddress % g_pagesize == 0);
-#ifdef TRACE
- printf ("Query %p %d %s\n", memory_info.BaseAddress, memory_info.RegionSize,
- memory_info.State == MEM_FREE ? "FREE":
- (memory_info.State == MEM_RESERVE ? "RESERVED":
- (memory_info.State == MEM_COMMIT ? "COMMITTED": "?")));
-#endif
- /* Region is free, well aligned and big enough: we are done */
- if (memory_info.State == MEM_FREE &&
- (unsigned) memory_info.BaseAddress % g_regionsize == 0 &&
- memory_info.RegionSize >= (unsigned) reserve_size) {
- found = TRUE;
- break;
- }
- /* From now on we can't get contiguous memory! */
- contiguous = FALSE;
- /* Recompute size to reserve */
- reserve_size = CEIL (allocate_size, g_my_regionsize);
- memory_info.BaseAddress = (char *) memory_info.BaseAddress + memory_info.RegionSize;
- /* Assert preconditions */
- assert ((unsigned) memory_info.BaseAddress % g_pagesize == 0);
- assert (0 < reserve_size && reserve_size % g_regionsize == 0);
- }
- /* Search failed? */
- if (! found)
- goto sbrk_exit;
- /* Assert preconditions */
- assert ((unsigned) memory_info.BaseAddress % g_regionsize == 0);
- assert (0 < reserve_size && reserve_size % g_regionsize == 0);
- /* Try to reserve this */
- base_reserved = VirtualAlloc (memory_info.BaseAddress, reserve_size,
- MEM_RESERVE, PAGE_NOACCESS);
- if (! base_reserved) {
- int rc = GetLastError ();
- if (rc != ERROR_INVALID_ADDRESS)
- goto sbrk_exit;
- }
- /* A null pointer signals (hopefully) a race condition with another thread. */
- /* In this case, we try again. */
- } while (! base_reserved);
- /* Check returned pointer for consistency */
- if (memory_info.BaseAddress && base_reserved != memory_info.BaseAddress)
- goto sbrk_exit;
- /* Assert postconditions */
- assert ((unsigned) base_reserved % g_regionsize == 0);
-#ifdef TRACE
- printf ("Reserve %p %d\n", base_reserved, reserve_size);
-#endif
- /* Did we get contiguous memory? */
- if (contiguous) {
- long start_size = (char *) g_last->top_committed - (char *) g_last->top_allocated;
- /* Adjust allocation size */
- allocate_size -= start_size;
- /* Adjust the regions allocation top */
- g_last->top_allocated = g_last->top_committed;
- /* Recompute the size to commit */
- to_commit = (char *) g_last->top_allocated + allocate_size - (char *) g_last->top_committed;
- /* Round size to commit */
- commit_size = CEIL (to_commit, g_my_pagesize);
- }
- /* Append the new region to the list */
- if (! region_list_append (&g_last, base_reserved, reserve_size))
- goto sbrk_exit;
- /* Didn't we get contiguous memory? */
- if (! contiguous) {
- /* Recompute the size to commit */
- to_commit = (char *) g_last->top_allocated + allocate_size - (char *) g_last->top_committed;
- /* Round size to commit */
- commit_size = CEIL (to_commit, g_my_pagesize);
- }
- }
- }
- /* Assert preconditions */
- assert ((unsigned) g_last->top_committed % g_pagesize == 0);
- assert (0 < commit_size && commit_size % g_pagesize == 0); {
- /* Commit this */
- void *base_committed = VirtualAlloc (g_last->top_committed, commit_size,
- MEM_COMMIT, PAGE_READWRITE);
- /* Check returned pointer for consistency */
- if (base_committed != g_last->top_committed)
- goto sbrk_exit;
- /* Assert postconditions */
- assert ((unsigned) base_committed % g_pagesize == 0);
-#ifdef TRACE
- printf ("Commit %p %d\n", base_committed, commit_size);
-#endif
- /* Adjust the regions commit top */
- g_last->top_committed = (char *) base_committed + commit_size;
- }
- }
- /* Adjust the regions allocation top */
- g_last->top_allocated = (char *) g_last->top_allocated + allocate_size;
- result = (char *) g_last->top_allocated - size;
- /* Deallocation requested? */
- } else if (size < 0) {
- long deallocate_size = - size;
- /* As long as we have a region to release */
- while ((char *) g_last->top_allocated - deallocate_size < (char *) g_last->top_reserved - g_last->reserve_size) {
- /* Get the size to release */
- long release_size = g_last->reserve_size;
- /* Get the base address */
- void *base_reserved = (char *) g_last->top_reserved - release_size;
- /* Assert preconditions */
- assert ((unsigned) base_reserved % g_regionsize == 0);
- assert (0 < release_size && release_size % g_regionsize == 0); {
- /* Release this */
- int rc = VirtualFree (base_reserved, 0,
- MEM_RELEASE);
- /* Check returned code for consistency */
- if (! rc)
- goto sbrk_exit;
-#ifdef TRACE
- printf ("Release %p %d\n", base_reserved, release_size);
-#endif
- }
- /* Adjust deallocation size */
- deallocate_size -= (char *) g_last->top_allocated - (char *) base_reserved;
- /* Remove the old region from the list */
- if (! region_list_remove (&g_last))
- goto sbrk_exit;
- } {
- /* Compute the size to decommit */
- long to_decommit = (char *) g_last->top_committed - ((char *) g_last->top_allocated - deallocate_size);
- if (to_decommit >= g_my_pagesize) {
- /* Compute the size to decommit */
- long decommit_size = FLOOR (to_decommit, g_my_pagesize);
- /* Compute the base address */
- void *base_committed = (char *) g_last->top_committed - decommit_size;
- /* Assert preconditions */
- assert ((unsigned) base_committed % g_pagesize == 0);
- assert (0 < decommit_size && decommit_size % g_pagesize == 0); {
- /* Decommit this */
- int rc = VirtualFree ((char *) base_committed, decommit_size,
- MEM_DECOMMIT);
- /* Check returned code for consistency */
- if (! rc)
- goto sbrk_exit;
-#ifdef TRACE
- printf ("Decommit %p %d\n", base_committed, decommit_size);
-#endif
- }
- /* Adjust deallocation size and regions commit and allocate top */
- deallocate_size -= (char *) g_last->top_allocated - (char *) base_committed;
- g_last->top_committed = base_committed;
- g_last->top_allocated = base_committed;
- }
- }
- /* Adjust regions allocate top */
- g_last->top_allocated = (char *) g_last->top_allocated - deallocate_size;
- /* Check for underflow */
- if ((char *) g_last->top_reserved - g_last->reserve_size > (char *) g_last->top_allocated ||
- g_last->top_allocated > g_last->top_committed) {
- /* Adjust regions allocate top */
- g_last->top_allocated = (char *) g_last->top_reserved - g_last->reserve_size;
- goto sbrk_exit;
- }
- result = g_last->top_allocated;
- }
- /* Assert invariants */
- assert (g_last);
- assert ((char *) g_last->top_reserved - g_last->reserve_size <= (char *) g_last->top_allocated &&
- g_last->top_allocated <= g_last->top_committed);
- assert ((char *) g_last->top_reserved - g_last->reserve_size <= (char *) g_last->top_committed &&
- g_last->top_committed <= g_last->top_reserved &&
- (unsigned) g_last->top_committed % g_pagesize == 0);
- assert ((unsigned) g_last->top_reserved % g_regionsize == 0);
- assert ((unsigned) g_last->reserve_size % g_regionsize == 0);
-
-sbrk_exit:
-#if defined (USE_MALLOC_LOCK) && defined (NEEDED)
- /* Release spin lock */
- slrelease (&g_sl);
-#endif
- return result;
-}
-
-/* mmap for windows */
-static void *mmap (void *ptr, long size, long prot, long type, long handle, long arg) {
- static long g_pagesize;
- static long g_regionsize;
-#ifdef TRACE
- printf ("mmap %d\n", size);
-#endif
-#if defined (USE_MALLOC_LOCK) && defined (NEEDED)
- /* Wait for spin lock */
- slwait (&g_sl);
-#endif
- /* First time initialization */
- if (! g_pagesize)
- g_pagesize = getpagesize ();
- if (! g_regionsize)
- g_regionsize = getregionsize ();
- /* Assert preconditions */
- assert ((unsigned) ptr % g_regionsize == 0);
- assert (size % g_pagesize == 0);
- /* Allocate this */
- ptr = VirtualAlloc (ptr, size,
- MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE);
- if (! ptr) {
- ptr = (void *) MORECORE_FAILURE;
- goto mmap_exit;
- }
- /* Assert postconditions */
- assert ((unsigned) ptr % g_regionsize == 0);
-#ifdef TRACE
- printf ("Commit %p %d\n", ptr, size);
-#endif
-mmap_exit:
-#if defined (USE_MALLOC_LOCK) && defined (NEEDED)
- /* Release spin lock */
- slrelease (&g_sl);
-#endif
- return ptr;
-}
-
-/* munmap for windows */
-static long munmap (void *ptr, long size) {
- static long g_pagesize;
- static long g_regionsize;
- int rc = MUNMAP_FAILURE;
-#ifdef TRACE
- printf ("munmap %p %d\n", ptr, size);
-#endif
-#if defined (USE_MALLOC_LOCK) && defined (NEEDED)
- /* Wait for spin lock */
- slwait (&g_sl);
-#endif
- /* First time initialization */
- if (! g_pagesize)
- g_pagesize = getpagesize ();
- if (! g_regionsize)
- g_regionsize = getregionsize ();
- /* Assert preconditions */
- assert ((unsigned) ptr % g_regionsize == 0);
- assert (size % g_pagesize == 0);
- /* Free this */
- if (! VirtualFree (ptr, 0,
- MEM_RELEASE))
- goto munmap_exit;
- rc = 0;
-#ifdef TRACE
- printf ("Release %p %d\n", ptr, size);
-#endif
-munmap_exit:
-#if defined (USE_MALLOC_LOCK) && defined (NEEDED)
- /* Release spin lock */
- slrelease (&g_sl);
-#endif
- return rc;
-}
-
-static void vminfo (CHUNK_SIZE_T *free, CHUNK_SIZE_T *reserved, CHUNK_SIZE_T *committed) {
- MEMORY_BASIC_INFORMATION memory_info;
- memory_info.BaseAddress = 0;
- *free = *reserved = *committed = 0;
- while (VirtualQuery (memory_info.BaseAddress, &memory_info, sizeof (memory_info))) {
- switch (memory_info.State) {
- case MEM_FREE:
- *free += memory_info.RegionSize;
- break;
- case MEM_RESERVE:
- *reserved += memory_info.RegionSize;
- break;
- case MEM_COMMIT:
- *committed += memory_info.RegionSize;
- break;
- }
- memory_info.BaseAddress = (char *) memory_info.BaseAddress + memory_info.RegionSize;
- }
-}
-
-static int cpuinfo (int whole, CHUNK_SIZE_T *kernel, CHUNK_SIZE_T *user) {
- if (whole) {
- __int64 creation64, exit64, kernel64, user64;
- int rc = GetProcessTimes (GetCurrentProcess (),
- (FILETIME *) &creation64,
- (FILETIME *) &exit64,
- (FILETIME *) &kernel64,
- (FILETIME *) &user64);
- if (! rc) {
- *kernel = 0;
- *user = 0;
- return FALSE;
- }
- *kernel = (CHUNK_SIZE_T) (kernel64 / 10000);
- *user = (CHUNK_SIZE_T) (user64 / 10000);
- return TRUE;
- } else {
- __int64 creation64, exit64, kernel64, user64;
- int rc = GetThreadTimes (GetCurrentThread (),
- (FILETIME *) &creation64,
- (FILETIME *) &exit64,
- (FILETIME *) &kernel64,
- (FILETIME *) &user64);
- if (! rc) {
- *kernel = 0;
- *user = 0;
- return FALSE;
- }
- *kernel = (CHUNK_SIZE_T) (kernel64 / 10000);
- *user = (CHUNK_SIZE_T) (user64 / 10000);
- return TRUE;
- }
-}
-
-#endif /* WIN32 */
-
-/* ------------------------------------------------------------
-History:
- V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)
- * Fix malloc_state bitmap array misdeclaration
-
- V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee)
- * Allow tuning of FIRST_SORTED_BIN_SIZE
- * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.
- * Better detection and support for non-contiguousness of MORECORE.
- Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger
- * Bypass most of malloc if no frees. Thanks To Emery Berger.
- * Fix freeing of old top non-contiguous chunk im sysmalloc.
- * Raised default trim and map thresholds to 256K.
- * Fix mmap-related #defines. Thanks to Lubos Lunak.
- * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.
- * Branch-free bin calculation
- * Default trim and mmap thresholds now 256K.
-
- V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
- * Introduce independent_comalloc and independent_calloc.
- Thanks to Michael Pachos for motivation and help.
- * Make optional .h file available
- * Allow > 2GB requests on 32bit systems.
- * new WIN32 sbrk, mmap, munmap, lock code from .
- Thanks also to Andreas Mueller ,
- and Anonymous.
- * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for
- helping test this.)
- * memalign: check alignment arg
- * realloc: don't try to shift chunks backwards, since this
- leads to more fragmentation in some programs and doesn't
- seem to help in any others.
- * Collect all cases in malloc requiring system memory into sYSMALLOc
- * Use mmap as backup to sbrk
- * Place all internal state in malloc_state
- * Introduce fastbins (although similar to 2.5.1)
- * Many minor tunings and cosmetic improvements
- * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK
- * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS
- Thanks to Tony E. Bennett and others.
- * Include errno.h to support default failure action.
-
- V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)
- * return null for negative arguments
- * Added Several WIN32 cleanups from Martin C. Fong
- * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
- (e.g. WIN32 platforms)
- * Cleanup header file inclusion for WIN32 platforms
- * Cleanup code to avoid Microsoft Visual C++ compiler complaints
- * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
- memory allocation routines
- * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
- * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
- usage of 'assert' in non-WIN32 code
- * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
- avoid infinite loop
- * Always call 'fREe()' rather than 'free()'
-
- V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)
- * Fixed ordering problem with boundary-stamping
-
- V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
- * Added pvalloc, as recommended by H.J. Liu
- * Added 64bit pointer support mainly from Wolfram Gloger
- * Added anonymously donated WIN32 sbrk emulation
- * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
- * malloc_extend_top: fix mask error that caused wastage after
- foreign sbrks
- * Add linux mremap support code from HJ Liu
-
- V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
- * Integrated most documentation with the code.
- * Add support for mmap, with help from
- Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
- * Use last_remainder in more cases.
- * Pack bins using idea from colin@nyx10.cs.du.edu
- * Use ordered bins instead of best-fit threshhold
- * Eliminate block-local decls to simplify tracing and debugging.
- * Support another case of realloc via move into top
- * Fix error occuring when initial sbrk_base not word-aligned.
- * Rely on page size for units instead of SBRK_UNIT to
- avoid surprises about sbrk alignment conventions.
- * Add mallinfo, mallopt. Thanks to Raymond Nijssen
- (raymond@es.ele.tue.nl) for the suggestion.
- * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
- * More precautions for cases where other routines call sbrk,
- courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
- * Added macros etc., allowing use in linux libc from
- H.J. Lu (hjl@gnu.ai.mit.edu)
- * Inverted this history list
-
- V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
- * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
- * Removed all preallocation code since under current scheme
- the work required to undo bad preallocations exceeds
- the work saved in good cases for most test programs.
- * No longer use return list or unconsolidated bins since
- no scheme using them consistently outperforms those that don't
- given above changes.
- * Use best fit for very large chunks to prevent some worst-cases.
- * Added some support for debugging
-
- V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
- * Removed footers when chunks are in use. Thanks to
- Paul Wilson (wilson@cs.texas.edu) for the suggestion.
-
- V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
- * Added malloc_trim, with help from Wolfram Gloger
- (wmglo@Dent.MED.Uni-Muenchen.DE).
-
- V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
-
- V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
- * realloc: try to expand in both directions
- * malloc: swap order of clean-bin strategy;
- * realloc: only conditionally expand backwards
- * Try not to scavenge used bins
- * Use bin counts as a guide to preallocation
- * Occasionally bin return list chunks in first scan
- * Add a few optimizations from colin@nyx10.cs.du.edu
-
- V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
- * faster bin computation & slightly different binning
- * merged all consolidations to one part of malloc proper
- (eliminating old malloc_find_space & malloc_clean_bin)
- * Scan 2 returns chunks (not just 1)
- * Propagate failure in realloc if malloc returns 0
- * Add stuff to allow compilation on non-ANSI compilers
- from kpv@research.att.com
-
- V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
- * removed potential for odd address access in prev_chunk
- * removed dependency on getpagesize.h
- * misc cosmetics and a bit more internal documentation
- * anticosmetics: mangled names in macros to evade debugger strangeness
- * tested on sparc, hp-700, dec-mips, rs6000
- with gcc & native cc (hp, dec only) allowing
- Detlefs & Zorn comparison study (in SIGPLAN Notices.)
-
- Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
- * Based loosely on libg++-1.2X malloc. (It retains some of the overall
- structure of old version, but most details differ.)
-
-*/
diff --git a/src/external/dlmalloc/malloc.h b/src/external/dlmalloc/malloc.h
deleted file mode 100644
index 7a807ef42..000000000
--- a/src/external/dlmalloc/malloc.h
+++ /dev/null
@@ -1,679 +0,0 @@
-/*
- Default header file for malloc-2.7.2, written by Doug Lea
- and released to the public domain. Use, modify, and redistribute
- this code without permission or acknowledgement in any way you wish.
- Send questions, comments, complaints, performance data, etc to
- dl@cs.oswego.edu.
-
- last update: Sun Feb 25 18:38:11 2001 Doug Lea (dl at gee)
-
- This header is for ANSI C/C++ only. You can set either of
- the following #defines before including:
-
- * If USE_DL_PREFIX is defined, it is assumed that malloc.c
- was also compiled with this option, so all routines
- have names starting with "dl".
-
- * If HAVE_USR_INCLUDE_MALLOC_H is defined, it is assumed that this
- file will be #included AFTER . This is needed only if
- your system defines a struct mallinfo that is incompatible with the
- standard one declared here. Otherwise, you can include this file
- INSTEAD of your system system . At least on ANSI, all
- declarations should be compatible with system versions
-*/
-
-#ifndef MALLOC_270_H
-#define MALLOC_270_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include /* for size_t */
-
-/*
- malloc(size_t n)
- Returns a pointer to a newly allocated chunk of at least n bytes, or
- null if no space is available. Additionally, on failure, errno is
- set to ENOMEM on ANSI C systems.
-
- If n is zero, malloc returns a minimum-sized chunk. The minimum size
- is 16 bytes on most 32bit systems, and either 24 or 32 bytes on
- 64bit systems, depending on internal size and alignment restrictions.
-
- On most systems, size_t is an unsigned type. Calls with values of n
- that appear "negative" when signed are interpreted as requests for
- huge amounts of space, which will most often fail.
-
- The maximum allowed value of n differs across systems, but is in all
- cases less (typically by 8K) than the maximum representable value of
- a size_t. Requests greater than this value result in failure.
-*/
-
-#ifndef USE_DL_PREFIX
-void* malloc(size_t);
-#else
-void* dlmalloc(size_t);
-#endif
-
-/*
- free(void* p)
- Releases the chunk of memory pointed to by p, that had been previously
- allocated using malloc or a related routine such as realloc.
- It has no effect if p is null. It can have arbitrary (and bad!)
- effects if p has already been freed or was not obtained via malloc.
-
- Unless disabled using mallopt, freeing very large spaces will,
- when possible, automatically trigger operations that give
- back unused memory to the system, thus reducing program footprint.
-*/
-#ifndef USE_DL_PREFIX
-void free(void*);
-#else
-void dlfree(void*);
-#endif
-
-/*
- calloc(size_t n_elements, size_t element_size);
- Returns a pointer to n_elements * element_size bytes, with all locations
- set to zero.
-*/
-#ifndef USE_DL_PREFIX
-void* calloc(size_t, size_t);
-#else
-void* dlcalloc(size_t, size_t);
-#endif
-
-/*
- realloc(void* p, size_t n)
- Returns a pointer to a chunk of size n that contains the same data
- as does chunk p up to the minimum of (n, p's size) bytes.
-
- The returned pointer may or may not be the same as p. The algorithm
- prefers extending p when possible, otherwise it employs the
- equivalent of a malloc-copy-free sequence.
-
- If p is null, realloc is equivalent to malloc.
-
- If space is not available, realloc returns null, errno is set (if on
- ANSI) and p is NOT freed.
-
- if n is for fewer bytes than already held by p, the newly unused
- space is lopped off and freed if possible. Unless the #define
- REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
- zero (re)allocates a minimum-sized chunk.
-
- Large chunks that were internally obtained via mmap will always
- be reallocated using malloc-copy-free sequences unless
- the system supports MREMAP (currently only linux).
-
- The old unix realloc convention of allowing the last-free'd chunk
- to be used as an argument to realloc is not supported.
-*/
-
-#ifndef USE_DL_PREFIX
-void* realloc(void*, size_t);
-#else
-void* dlrealloc(void*, size_t);
-#endif
-
-/*
- memalign(size_t alignment, size_t n);
- Returns a pointer to a newly allocated chunk of n bytes, aligned
- in accord with the alignment argument.
-
- The alignment argument should be a power of two. If the argument is
- not a power of two, the nearest greater power is used.
- 8-byte alignment is guaranteed by normal malloc calls, so don't
- bother calling memalign with an argument of 8 or less.
-
- Overreliance on memalign is a sure way to fragment space.
-*/
-
-#ifndef USE_DL_PREFIX
-void* memalign(size_t, size_t);
-#else
-void* dlmemalign(size_t, size_t);
-#endif
-
-
-/*
- valloc(size_t n);
- Allocates a page-aligned chunk of at least n bytes.
- Equivalent to memalign(pagesize, n), where pagesize is the page
- size of the system. If the pagesize is unknown, 4096 is used.
-*/
-
-#ifndef USE_DL_PREFIX
-void* valloc(size_t);
-#else
-void* dlvalloc(size_t);
-#endif
-
-
-/*
- independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
-
- independent_calloc is similar to calloc, but instead of returning a
- single cleared space, it returns an array of pointers to n_elements
- independent elements, each of which can hold contents of size
- elem_size. Each element starts out cleared, and can be
- independently freed, realloc'ed etc. The elements are guaranteed to
- be adjacently allocated (this is not guaranteed to occur with
- multiple callocs or mallocs), which may also improve cache locality
- in some applications.
-
- The "chunks" argument is optional (i.e., may be null, which is
- probably the most typical usage). If it is null, the returned array
- is itself dynamically allocated and should also be freed when it is
- no longer needed. Otherwise, the chunks array must be of at least
- n_elements in length. It is filled in with the pointers to the
- chunks.
-
- In either case, independent_calloc returns this pointer array, or
- null if the allocation failed. If n_elements is zero and "chunks"
- is null, it returns a chunk representing an array with zero elements
- (which should be freed if not wanted).
-
- Each element must be individually freed when it is no longer
- needed. If you'd like to instead be able to free all at once, you
- should instead use regular calloc and assign pointers into this
- space to represent elements. (In this case though, you cannot
- independently free elements.)
-
- independent_calloc simplifies and speeds up implementations of many
- kinds of pools. It may also be useful when constructing large data
- structures that initially have a fixed number of fixed-sized nodes,
- but the number is not known at compile time, and some of the nodes
- may later need to be freed. For example:
-
- struct Node { int item; struct Node* next; };
-
- struct Node* build_list() {
- struct Node** pool;
- int n = read_number_of_nodes_needed();
- if (n <= 0) return 0;
- pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
- if (pool == 0) return 0; // failure
- // organize into a linked list...
- struct Node* first = pool[0];
- for (i = 0; i < n-1; ++i)
- pool[i]->next = pool[i+1];
- free(pool); // Can now free the array (or not, if it is needed later)
- return first;
- }
-*/
-
-#ifndef USE_DL_PREFIX
-void** independent_calloc(size_t, size_t, void**);
-#else
-void** dlindependent_calloc(size_t, size_t, void**);
-#endif
-
-/*
- independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
-
- independent_comalloc allocates, all at once, a set of n_elements
- chunks with sizes indicated in the "sizes" array. It returns
- an array of pointers to these elements, each of which can be
- independently freed, realloc'ed etc. The elements are guaranteed to
- be adjacently allocated (this is not guaranteed to occur with
- multiple callocs or mallocs), which may also improve cache locality
- in some applications.
-
- The "chunks" argument is optional (i.e., may be null). If it is null
- the returned array is itself dynamically allocated and should also
- be freed when it is no longer needed. Otherwise, the chunks array
- must be of at least n_elements in length. It is filled in with the
- pointers to the chunks.
-
- In either case, independent_comalloc returns this pointer array, or
- null if the allocation failed. If n_elements is zero and chunks is
- null, it returns a chunk representing an array with zero elements
- (which should be freed if not wanted).
-
- Each element must be individually freed when it is no longer
- needed. If you'd like to instead be able to free all at once, you
- should instead use a single regular malloc, and assign pointers at
- particular offsets in the aggregate space. (In this case though, you
- cannot independently free elements.)
-
- independent_comallac differs from independent_calloc in that each
- element may have a different size, and also that it does not
- automatically clear elements.
-
- independent_comalloc can be used to speed up allocation in cases
- where several structs or objects must always be allocated at the
- same time. For example:
-
- struct Head { ... }
- struct Foot { ... }
-
- void send_message(char* msg) {
- int msglen = strlen(msg);
- size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
- void* chunks[3];
- if (independent_comalloc(3, sizes, chunks) == 0)
- die();
- struct Head* head = (struct Head*)(chunks[0]);
- char* body = (char*)(chunks[1]);
- struct Foot* foot = (struct Foot*)(chunks[2]);
- // ...
- }
-
- In general though, independent_comalloc is worth using only for
- larger values of n_elements. For small values, you probably won't
- detect enough difference from series of malloc calls to bother.
-
- Overuse of independent_comalloc can increase overall memory usage,
- since it cannot reuse existing noncontiguous small chunks that
- might be available for some of the elements.
-*/
-
-#ifndef USE_DL_PREFIX
-void** independent_comalloc(size_t, size_t*, void**);
-#else
-void** dlindependent_comalloc(size_t, size_t*, void**);
-#endif
-
-
-/*
- pvalloc(size_t n);
- Equivalent to valloc(minimum-page-that-holds(n)), that is,
- round up n to nearest pagesize.
- */
-
-#ifndef USE_DL_PREFIX
-void* pvalloc(size_t);
-#else
-void* dlpvalloc(size_t);
-#endif
-
-/*
- cfree(void* p);
- Equivalent to free(p).
-
- cfree is needed/defined on some systems that pair it with calloc,
- for odd historical reasons (such as: cfree is used in example
- code in the first edition of K&R).
-*/
-
-#ifndef USE_DL_PREFIX
-void cfree(void*);
-#else
-void dlcfree(void*);
-#endif
-
-
-/*
- malloc_trim(size_t pad);
-
- If possible, gives memory back to the system (via negative
- arguments to sbrk) if there is unused memory at the `high' end of
- the malloc pool. You can call this after freeing large blocks of
- memory to potentially reduce the system-level memory requirements
- of a program. However, it cannot guarantee to reduce memory. Under
- some allocation patterns, some large free blocks of memory will be
- locked between two used chunks, so they cannot be given back to
- the system.
-
- The `pad' argument to malloc_trim represents the amount of free
- trailing space to leave untrimmed. If this argument is zero,
- only the minimum amount of memory to maintain internal data
- structures will be left (one page or less). Non-zero arguments
- can be supplied to maintain enough trailing space to service
- future expected allocations without having to re-obtain memory
- from the system.
-
- Malloc_trim returns 1 if it actually released any memory, else 0.
- On systems that do not support "negative sbrks", it will always
- return 0.
-*/
-
-#ifndef USE_DL_PREFIX
-int malloc_trim(size_t);
-#else
-int dlmalloc_trim(size_t);
-#endif
-
-
-/*
- malloc_usable_size(void* p);
-
- Returns the number of bytes you can actually use in an allocated
- chunk, which may be more than you requested (although often not) due
- to alignment and minimum size constraints. You can use this many
- bytes without worrying about overwriting other allocated
- objects. This is not a particularly great programming practice. But
- malloc_usable_size can be more useful in debugging and assertions,
- for example:
-
- p = malloc(n);
- assert(malloc_usable_size(p) >= 256);
-*/
-
-#ifndef USE_DL_PREFIX
-size_t malloc_usable_size(void*);
-#else
-size_t dlmalloc_usable_size(void*);
-#endif
-
-
-/*
- malloc_stats();
- Prints on stderr the amount of space obtained from the system (both
- via sbrk and mmap), the maximum amount (which may be more than
- current if malloc_trim and/or munmap got called), and the current
- number of bytes allocated via malloc (or realloc, etc) but not yet
- freed. Note that this is the number of bytes allocated, not the
- number requested. It will be larger than the number requested
- because of alignment and bookkeeping overhead. Because it includes
- alignment wastage as being in use, this figure may be greater than
- zero even when no user-level chunks are allocated.
-
- The reported current and maximum system memory can be inaccurate if
- a program makes other calls to system memory allocation functions
- (normally sbrk) outside of malloc.
-
- malloc_stats prints only the most commonly interesting statistics.
- More information can be obtained by calling mallinfo.
-*/
-
-#ifndef USE_DL_PREFIX
-void malloc_stats(void);
-#else
-void dlmalloc_stats(void);
-#endif
-
-/*
- mallinfo()
- Returns (by copy) a struct containing various summary statistics:
-
- arena: current total non-mmapped bytes allocated from system
- ordblks: the number of free chunks
- smblks: the number of fastbin blocks (i.e., small chunks that
- have been freed but not use resused or consolidated)
- hblks: current number of mmapped regions
- hblkhd: total bytes held in mmapped regions
- usmblks: the maximum total allocated space. This will be greater
- than current total if trimming has occurred.
- fsmblks: total bytes held in fastbin blocks
- uordblks: current total allocated space (normal or mmapped)
- fordblks: total free space
- keepcost: the maximum number of bytes that could ideally be released
- back to system via malloc_trim. ("ideally" means that
- it ignores page restrictions etc.)
-
- The names of some of these fields don't bear much relation with
- their contents because this struct was defined as standard in
- SVID/XPG so reflects the malloc implementation that was then used
- in SystemV Unix.
-
- The original SVID version of this struct, defined on most systems
- with mallinfo, declares all fields as ints. But some others define
- as unsigned long. If your system defines the fields using a type of
- different width than listed here, you should #include your system
- version before including this file. The struct declaration is
- suppressed if _MALLOC_H is defined (which is done in most system
- malloc.h files). You can also suppress it by defining
- HAVE_USR_INCLUDE_MALLOC_H.
-
- Because these fields are ints, but internal bookkeeping is done with
- unsigned longs, the reported values may appear as negative, and may
- wrap around zero and thus be inaccurate.
-*/
-
-#ifndef HAVE_USR_INCLUDE_MALLOC_H
-#ifndef _MALLOC_H
-struct mallinfo {
- int arena;
- int ordblks;
- int smblks;
- int hblks;
- int hblkhd;
- int usmblks;
- int fsmblks;
- int uordblks;
- int fordblks;
- int keepcost;
-};
-#endif
-#endif
-
-#ifndef USE_DL_PREFIX
-struct mallinfo mallinfo(void);
-#else
-struct mallinfo mallinfo(void);
-#endif
-
-/*
- mallopt(int parameter_number, int parameter_value)
- Sets tunable parameters The format is to provide a
- (parameter-number, parameter-value) pair. mallopt then sets the
- corresponding parameter to the argument value if it can (i.e., so
- long as the value is meaningful), and returns 1 if successful else
- 0. SVID/XPG defines four standard param numbers for mallopt,
- normally defined in malloc.h. Only one of these (M_MXFAST) is used
- in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
- so setting them has no effect. But this malloc also supports four
- other options in mallopt. See below for details. Briefly, supported
- parameters are as follows (listed defaults are for "typical"
- configurations).
-
- Symbol param # default allowed param values
- M_MXFAST 1 64 0-80 (0 disables fastbins)
- M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
- M_TOP_PAD -2 0 any
- M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
- M_MMAP_MAX -4 65536 any (0 disables use of mmap)
-*/
-
-#ifndef USE_DL_PREFIX
-int mallopt(int, int);
-#else
-int dlmallopt(int, int);
-#endif
-
-/* Descriptions of tuning options */
-
-/*
- M_MXFAST is the maximum request size used for "fastbins", special bins
- that hold returned chunks without consolidating their spaces. This
- enables future requests for chunks of the same size to be handled
- very quickly, but can increase fragmentation, and thus increase the
- overall memory footprint of a program.
-
- This malloc manages fastbins very conservatively yet still
- efficiently, so fragmentation is rarely a problem for values less
- than or equal to the default. The maximum supported value of MXFAST
- is 80. You wouldn't want it any higher than this anyway. Fastbins
- are designed especially for use with many small structs, objects or
- strings -- the default handles structs/objects/arrays with sizes up
- to 8 4byte fields, or small strings representing words, tokens,
- etc. Using fastbins for larger objects normally worsens
- fragmentation without improving speed.
-
- You can reduce M_MXFAST to 0 to disable all use of fastbins. This
- causes the malloc algorithm to be a closer approximation of
- fifo-best-fit in all cases, not just for larger requests, but will
- generally cause it to be slower.
-*/
-
-#ifndef M_MXFAST
-#define M_MXFAST 1
-#endif
-
-/*
- M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
- to keep before releasing via malloc_trim in free().
-
- Automatic trimming is mainly useful in long-lived programs.
- Because trimming via sbrk can be slow on some systems, and can
- sometimes be wasteful (in cases where programs immediately
- afterward allocate more large chunks) the value should be high
- enough so that your overall system performance would improve by
- releasing this much memory.
-
- The trim threshold and the mmap control parameters (see below)
- can be traded off with one another. Trimming and mmapping are
- two different ways of releasing unused memory back to the
- system. Between these two, it is often possible to keep
- system-level demands of a long-lived program down to a bare
- minimum. For example, in one test suite of sessions measuring
- the XF86 X server on Linux, using a trim threshold of 128K and a
- mmap threshold of 192K led to near-minimal long term resource
- consumption.
-
- If you are using this malloc in a long-lived program, it should
- pay to experiment with these values. As a rough guide, you
- might set to a value close to the average size of a process
- (program) running on your system. Releasing this much memory
- would allow such a process to run in memory. Generally, it's
- worth it to tune for trimming rather tham memory mapping when a
- program undergoes phases where several large chunks are
- allocated and released in ways that can reuse each other's
- storage, perhaps mixed with phases where there are no such
- chunks at all. And in well-behaved long-lived programs,
- controlling release of large blocks via trimming versus mapping
- is usually faster.
-
- However, in most programs, these parameters serve mainly as
- protection against the system-level effects of carrying around
- massive amounts of unneeded memory. Since frequent calls to
- sbrk, mmap, and munmap otherwise degrade performance, the default
- parameters are set to relatively high values that serve only as
- safeguards.
-
- The trim value It must be greater than page size to have any useful
- effect. To disable trimming completely, you can set to
- (unsigned long)(-1)
-
- Trim settings interact with fastbin (MXFAST) settings: Unless
- compiled with TRIM_FASTBINS defined, automatic trimming never takes
- place upon freeing a chunk with size less than or equal to
- MXFAST. Trimming is instead delayed until subsequent freeing of
- larger chunks. However, you can still force an attempted trim by
- calling malloc_trim.
-
- Also, trimming is not generally possible in cases where
- the main arena is obtained via mmap.
-
- Note that the trick some people use of mallocing a huge space and
- then freeing it at program startup, in an attempt to reserve system
- memory, doesn't have the intended effect under automatic trimming,
- since that memory will immediately be returned to the system.
-*/
-
-#define M_TRIM_THRESHOLD -1
-
-/*
- M_TOP_PAD is the amount of extra `padding' space to allocate or
- retain whenever sbrk is called. It is used in two ways internally:
-
- * When sbrk is called to extend the top of the arena to satisfy
- a new malloc request, this much padding is added to the sbrk
- request.
-
- * When malloc_trim is called automatically from free(),
- it is used as the `pad' argument.
-
- In both cases, the actual amount of padding is rounded
- so that the end of the arena is always a system page boundary.
-
- The main reason for using padding is to avoid calling sbrk so
- often. Having even a small pad greatly reduces the likelihood
- that nearly every malloc request during program start-up (or
- after trimming) will invoke sbrk, which needlessly wastes
- time.
-
- Automatic rounding-up to page-size units is normally sufficient
- to avoid measurable overhead, so the default is 0. However, in
- systems where sbrk is relatively slow, it can pay to increase
- this value, at the expense of carrying around more memory than
- the program needs.
-*/
-
-#define M_TOP_PAD -2
-
-
-/*
- M_MMAP_THRESHOLD is the request size threshold for using mmap()
- to service a request. Requests of at least this size that cannot
- be allocated using already-existing space will be serviced via mmap.
- (If enough normal freed space already exists it is used instead.)
-
- Using mmap segregates relatively large chunks of memory so that
- they can be individually obtained and released from the host
- system. A request serviced through mmap is never reused by any
- other request (at least not directly; the system may just so
- happen to remap successive requests to the same locations).
-
- Segregating space in this way has the benefits that:
-
- 1. Mmapped space can ALWAYS be individually released back
- to the system, which helps keep the system level memory
- demands of a long-lived program low.
- 2. Mapped memory can never become `locked' between
- other chunks, as can happen with normally allocated chunks, which
- means that even trimming via malloc_trim would not release them.
- 3. On some systems with "holes" in address spaces, mmap can obtain
- memory that sbrk cannot.
-
- However, it has the disadvantages that:
-
- 1. The space cannot be reclaimed, consolidated, and then
- used to service later requests, as happens with normal chunks.
- 2. It can lead to more wastage because of mmap page alignment
- requirements
- 3. It causes malloc performance to be more dependent on host
- system memory management support routines.
-
- The advantages of mmap nearly always outweigh disadvantages for
- "large" chunks, but the value of "large" varies across systems. The
- default is an empirically derived value that works well in most
- systems.
-*/
-
-#define M_MMAP_THRESHOLD -3
-
-/*
- M_MMAP_MAX is the maximum number of requests to simultaneously
- service using mmap. This parameter exists because
- some systems have a limited number of internal tables for
- use by mmap, and using more than a few of them may degrade
- performance.
-
- The default is set to a value that serves only as a safeguard.
- Setting to 0 disables use of mmap for servicing large requests. If
- mmap is not supported on a system, the default value is 0, and
- attempts to set it to non-zero values in mallopt will fail.
-*/
-
-#define M_MMAP_MAX -4
-
-
-/* Unused SVID2/XPG mallopt options, listed for completeness */
-
-#ifndef M_NBLKS
-#define M_NLBLKS 2 /* UNUSED in this malloc */
-#endif
-#ifndef M_GRAIN
-#define M_GRAIN 3 /* UNUSED in this malloc */
-#endif
-#ifndef M_KEEP
-#define M_KEEP 4 /* UNUSED in this malloc */
-#endif
-
-/*
- Some malloc.h's declare alloca, even though it is not part of malloc.
-*/
-
-#ifndef _ALLOCA_H
-extern void* alloca(size_t);
-#endif
-
-#ifdef __cplusplus
-}; /* end of extern "C" */
-#endif
-
-#endif /* MALLOC_270_H */
diff --git a/src/external/external.vcproj b/src/external/external.vcproj
deleted file mode 100644
index e1d665ee0..000000000
--- a/src/external/external.vcproj
+++ /dev/null
@@ -1,250 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/external/iniparser/iniparser.c b/src/external/iniparser/iniparser.c
deleted file mode 100644
index acdbf1797..000000000
--- a/src/external/iniparser/iniparser.c
+++ /dev/null
@@ -1,918 +0,0 @@
-/*
- Based upon libiniparser, by Nicolas Devillard
- Hacked into 1 file (m-iniparser) by Freek/2005
- Original terms following:
-
- -- -
-
- Copyright (c) 2000 by Nicolas Devillard (ndevilla AT free DOT fr).
-
- Written by Nicolas Devillard. Not derived from licensed software.
-
- Permission is granted to anyone to use this software for any
- purpose on any computer system, and to redistribute it freely,
- subject to the following restrictions:
-
- 1. The author is not responsible for the consequences of use of
- this software, no matter how awful, even if they arise
- from defects in it.
-
- 2. The origin of this software must not be misrepresented, either
- by explicit claim or by omission.
-
- 3. Altered versions must be plainly marked as such, and must not
- be misrepresented as being the original software.
-
- 4. This notice may not be removed or altered.
-
- */
-
-
-#include
-#include
-#include
-#include
-
-#include "iniparser.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* strlib.c following */
-
-#define ASCIILINESZ 1024
-/*-------------------------------------------------------------------------*/
-/**
- @brief Convert a string to lowercase.
- @param s String to convert.
- @return ptr to statically allocated string.
-
- This function returns a pointer to a statically allocated string
- containing a lowercased version of the input string. Do not free
- or modify the returned string! Since the returned string is statically
- allocated, it will be modified at each function call (not re-entrant).
- */
-/*--------------------------------------------------------------------------*/
-
-static char * strlwc(const char * s)
-{
- static char l[ASCIILINESZ+1]; /* STATIC_RETURN: used for return, not across calls */
- int i ;
-
- if (s==NULL) return NULL ;
- memset(l, 0, ASCIILINESZ+1);
- i=0 ;
- while (s[i] && i l) {
- if (!isxspace((int)*(last-1)))
- break ;
- last -- ;
- }
- *last = (char)0;
- return l ;
-}
-
-
-/* dictionary.c.c following */
-/** Maximum value size for integers and doubles. */
-#define MAXVALSZ 1024
-
-/** Minimal allocated number of entries in a dictionary */
-#define DICTMINSZ 128
-
-/** Invalid key token */
-#define DICT_INVALID_KEY ((char*)-1)
-
-/*
- Doubles the allocated size associated to a pointer
- 'size' is the current allocated size.
- */
-static void * mem_double(void * ptr, int size)
-{
- void *newptr;
-
- newptr = calloc(2*size, 1);
- memcpy(newptr, ptr, size);
- free(ptr);
- return newptr ;
-}
-
-
-/*---------------------------------------------------------------------------
- Function codes
- ---------------------------------------------------------------------------*/
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Compute the hash key for a string.
- @param key Character string to use for key.
- @return 1 unsigned int on at least 32 bits.
-
- This hash function has been taken from an Article in Dr Dobbs Journal.
- This is normally a collision-free function, distributing keys evenly.
- The key is stored anyway in the struct so that collision can be avoided
- by comparing the key itself in last resort.
- */
-/*--------------------------------------------------------------------------*/
-
-static unsigned dictionary_hash(const char * key)
-{
- size_t len ;
- unsigned int hash ;
- unsigned int i;
-
- len = strlen(key);
- for (hash=0, i=0 ; i>6) ;
- }
- hash += (hash <<3);
- hash ^= (hash >>11);
- hash += (hash <<15);
- return hash ;
-}
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Create a new dictionary object.
- @param size Optional initial size of the dictionary.
- @return 1 newly allocated dictionary objet.
-
- This function allocates a new dictionary object of given size and returns
- it. If you do not know in advance (roughly) the number of entries in the
- dictionary, give size=0.
- */
-/*--------------------------------------------------------------------------*/
-
-static dictionary * dictionary_new(int size)
-{
- dictionary *d ;
-
- /* If no size was specified, allocate space for DICTMINSZ */
- if (sizesize = size ;
- d->val = (char **)calloc(size, sizeof(char*));
- d->key = (char **)calloc(size, sizeof(char*));
- d->hash = (unsigned int *)calloc(size, sizeof(unsigned));
-
- return d;
-}
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Delete a dictionary object
- @param d dictionary object to deallocate.
- @return void
-
- Deallocate a dictionary object and all memory associated to it.
- */
-/*--------------------------------------------------------------------------*/
-
-static void dictionary_del(dictionary * d)
-{
- int i ;
-
- if (d==NULL) return ;
- for (i=0 ; isize ; i++) {
- if (d->key[i]!=NULL)
- free(d->key[i]);
- if (d->val[i]!=NULL)
- free(d->val[i]);
- }
- free(d->val);
- free(d->key);
- free(d->hash);
- free(d);
-
- return;
-}
-
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Get a value from a dictionary.
- @param d dictionary object to search.
- @param key Key to look for in the dictionary.
- @param def Default value to return if key not found.
- @return 1 pointer to internally allocated character string.
-
- This function locates a key in a dictionary and returns a pointer to its
- value, or the passed 'def' pointer if no such key can be found in
- dictionary. The returned character pointer points to data internal to the
- dictionary object, you should not try to free it or modify it.
- */
-/*--------------------------------------------------------------------------*/
-static const char * dictionary_get(dictionary * d, const char * key, const char * def)
-{
- unsigned hash ;
- int i ;
-
- hash = dictionary_hash(key);
- for (i=0 ; isize ; i++) {
- if (d->key==NULL)
- continue ;
- /* Compare hash */
- if (hash==d->hash[i]) {
- /* Compare string, to avoid hash collisions */
- if (!strcmp(key, d->key[i])) {
- return d->val[i] ;
- }
- }
- }
- return def ;
-}
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Set a value in a dictionary.
- @param d dictionary object to modify.
- @param key Key to modify or add.
- @param val Value to add.
- @return void
-
- If the given key is found in the dictionary, the associated value is
- replaced by the provided one. If the key cannot be found in the
- dictionary, it is added to it.
-
- It is Ok to provide a NULL value for val, but NULL values for the dictionary
- or the key are considered as errors: the function will return immediately
- in such a case.
-
- Notice that if you dictionary_set a variable to NULL, a call to
- dictionary_get will return a NULL value: the variable will be found, and
- its value (NULL) is returned. In other words, setting the variable
- content to NULL is equivalent to deleting the variable from the
- dictionary. It is not possible (in this implementation) to have a key in
- the dictionary without value.
- */
-/*--------------------------------------------------------------------------*/
-
-static void dictionary_set(dictionary * d, const char * key, const char * val)
-{
- int i ;
- unsigned hash ;
-
- if (d==NULL || key==NULL) return ;
-
- /* Compute hash for this key */
- hash = dictionary_hash(key) ;
- /* Find if value is already in blackboard */
- if (d->n>0) {
- for (i=0 ; isize ; i++) {
- if (d->key[i]==NULL)
- continue ;
- if (hash==d->hash[i]) { /* Same hash value */
- if (!strcmp(key, d->key[i])) { /* Same key */
- /* Found a value: modify and return */
- if (d->val[i]!=NULL)
- free(d->val[i]);
- d->val[i] = val ? strdup(val) : NULL ;
- /* Value has been modified: return */
- return ;
- }
- }
- }
- }
- /* Add a new value */
- /* See if dictionary needs to grow */
- if (d->n==d->size) {
-
- /* Reached maximum size: reallocate blackboard */
- d->val = (char **)mem_double(d->val, d->size * sizeof(char*)) ;
- d->key = (char **)mem_double(d->key, d->size * sizeof(char*)) ;
- d->hash = (unsigned int *)mem_double(d->hash, d->size * sizeof(unsigned)) ;
-
- /* Double size */
- d->size *= 2 ;
- }
-
- /* Insert key in the first empty slot */
- for (i=0 ; isize ; i++) {
- if (d->key[i]==NULL) {
- /* Add key here */
- break ;
- }
- }
- /* Copy key */
- d->key[i] = strdup(key);
- d->val[i] = val ? strdup(val) : NULL ;
- d->hash[i] = hash;
- d->n ++ ;
- return ;
-}
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Delete a key in a dictionary
- @param d dictionary object to modify.
- @param key Key to remove.
- @return void
-
- This function deletes a key in a dictionary. Nothing is done if the
- key cannot be found.
- */
-/*--------------------------------------------------------------------------*/
-static void dictionary_unset(dictionary * d, char * key)
-{
- unsigned hash ;
- int i ;
-
- hash = dictionary_hash(key);
- for (i=0 ; isize ; i++) {
- if (d->key[i]==NULL)
- continue ;
- /* Compare hash */
- if (hash==d->hash[i]) {
- /* Compare string, to avoid hash collisions */
- if (!strcmp(key, d->key[i])) {
- /* Found key */
- break ;
- }
- }
- }
- if (i>=d->size)
- /* Key not found */
- return ;
-
- free(d->key[i]);
- d->key[i] = NULL ;
- if (d->val[i]!=NULL) {
- free(d->val[i]);
- d->val[i] = NULL ;
- }
- d->hash[i] = 0 ;
- d->n -- ;
- return ;
-}
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Dump a dictionary to an opened file pointer.
- @param d Dictionary to dump
- @param f Opened file pointer.
- @return void
-
- Dumps a dictionary onto an opened file pointer. Key pairs are printed out
- as @c [Key]=[Value], one per line. It is Ok to provide stdout or stderr as
- output file pointers.
- */
-/*--------------------------------------------------------------------------*/
-
-static void dictionary_dump(dictionary *d, FILE *f)
-{
- int i;
-
- if (d==NULL || f==NULL) return;
-
- for (i=0; isize; i++) {
- if (d->key[i] == NULL)
- continue ;
- if (d->val[i] != NULL) {
- fprintf(f, "[%s]=[%s]\n", d->key[i], d->val[i]);
- } else {
- fprintf(f, "[%s]=UNDEF\n", d->key[i]);
- }
- }
-
- return;
-}
-
-
-/* iniparser.c.c following */
-#define ASCIILINESZ 1024
-#define INI_INVALID_KEY ((char*)-1)
-
-/* Private: add an entry to the dictionary */
-static void iniparser_add_entry(
- dictionary * d,
- char * sec,
- char * key,
- char * val)
-{
- char longkey[2*ASCIILINESZ+1];
-
- /* Make a key as section:keyword */
- if (key!=NULL) {
- sprintf(longkey, "%s:%s", sec, key);
- } else {
- strcpy(longkey, sec);
- }
-
- /* Add (key,val) to dictionary */
- dictionary_set(d, longkey, val);
- return ;
-}
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Get number of sections in a dictionary
- @param d Dictionary to examine
- @return int Number of sections found in dictionary
-
- This function returns the number of sections found in a dictionary.
- The test to recognize sections is done on the string stored in the
- dictionary: a section name is given as "section" whereas a key is
- stored as "section:key", thus the test looks for entries that do not
- contain a colon.
-
- This clearly fails in the case a section name contains a colon, but
- this should simply be avoided.
-
- This function returns -1 in case of error.
- */
-/*--------------------------------------------------------------------------*/
-
-int iniparser_getnsec(dictionary * d)
-{
- int i ;
- int nsec ;
-
- if (d==NULL) return -1 ;
- nsec=0 ;
- for (i=0 ; isize ; i++) {
- if (d->key[i]==NULL)
- continue ;
- if (strchr(d->key[i], ':')==NULL) {
- nsec ++ ;
- }
- }
- return nsec ;
-}
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Get name for section n in a dictionary.
- @param d Dictionary to examine
- @param n Section number (from 0 to nsec-1).
- @return Pointer to char string
-
- This function locates the n-th section in a dictionary and returns
- its name as a pointer to a string statically allocated inside the
- dictionary. Do not free or modify the returned string!
-
- This function returns NULL in case of error.
- */
-/*--------------------------------------------------------------------------*/
-
-char * iniparser_getsecname(dictionary * d, int n)
-{
- int i ;
- int foundsec ;
-
- if (d==NULL || n<0) return NULL ;
- foundsec=0 ;
- for (i=0 ; isize ; i++) {
- if (d->key[i]==NULL)
- continue ;
- if (strchr(d->key[i], ':')==NULL) {
- foundsec++ ;
- if (foundsec>n)
- break ;
- }
- }
- if (foundsec<=n) {
- return NULL ;
- }
- return d->key[i] ;
-}
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Dump a dictionary to an opened file pointer.
- @param d Dictionary to dump.
- @param f Opened file pointer to dump to.
- @return void
-
- This function prints out the contents of a dictionary, one element by
- line, onto the provided file pointer. It is OK to specify @c stderr
- or @c stdout as output files. This function is meant for debugging
- purposes mostly.
- */
-/*--------------------------------------------------------------------------*/
-void iniparser_dump(dictionary * d, FILE * f)
-{
- dictionary_dump(d,f);
-}
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Save a dictionary to a loadable ini file
- @param d Dictionary to dump
- @param f Opened file pointer to dump to
- @return void
-
- This function dumps a given dictionary into a loadable ini file.
- It is Ok to specify @c stderr or @c stdout as output files.
- */
-/*--------------------------------------------------------------------------*/
-
-void iniparser_dump_ini(dictionary * d, FILE * f)
-{
- int i, j ;
- char keym[ASCIILINESZ+1];
- int nsec ;
- char * secname ;
- int seclen ;
-
- if (d==NULL || f==NULL) return ;
-
- nsec = iniparser_getnsec(d);
- if (nsec<1) {
- /* No section in file: dump all keys as they are */
- for (i=0 ; isize ; i++) {
- if (d->key[i]==NULL)
- continue ;
- fprintf(f, "%s = %s\n", d->key[i], d->val[i]);
- }
- return ;
- }
- for (i=0 ; isize ; j++) {
- if (d->key[j]==NULL)
- continue ;
- if (!strncmp(d->key[j], keym, seclen+1)) {
- fprintf(f,
- "%-30s = %s\n",
- d->key[j]+seclen+1,
- d->val[j] ? d->val[j] : "");
- }
- }
- }
- fprintf(f, "\n");
- return ;
-}
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Get the string associated to a key, return NULL if not found
- @param d Dictionary to search
- @param key Key string to look for
- @return pointer to statically allocated character string, or NULL.
-
- This function queries a dictionary for a key. A key as read from an
- ini file is given as "section:key". If the key cannot be found,
- NULL is returned.
- The returned char pointer is pointing to a string allocated in
- the dictionary, do not free or modify it.
-
- This function is only provided for backwards compatibility with
- previous versions of iniparser. It is recommended to use
- iniparser_getstring() instead.
- */
-/*--------------------------------------------------------------------------*/
-const char * iniparser_getstr(dictionary * d, const char * key)
-{
- return iniparser_getstring(d, key, NULL);
-}
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Get the string associated to a key
- @param d Dictionary to search
- @param key Key string to look for
- @param def Default value to return if key not found.
- @return pointer to statically allocated character string
-
- This function queries a dictionary for a key. A key as read from an
- ini file is given as "section:key". If the key cannot be found,
- the pointer passed as 'def' is returned.
- The returned char pointer is pointing to a string allocated in
- the dictionary, do not free or modify it.
- */
-/*--------------------------------------------------------------------------*/
-const char * iniparser_getstring(dictionary * d, const char * key, const char * def)
-{
- char * lc_key ;
- const char * sval ;
-
- if (d==NULL || key==NULL)
- return def ;
-
- lc_key = strdup(strlwc(key));
- sval = dictionary_get(d, lc_key, def);
- free(lc_key);
- return sval ;
-}
-
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Get the string associated to a key, convert to an int
- @param d Dictionary to search
- @param key Key string to look for
- @param notfound Value to return in case of error
- @return integer
-
- This function queries a dictionary for a key. A key as read from an
- ini file is given as "section:key". If the key cannot be found,
- the notfound value is returned.
- */
-/*--------------------------------------------------------------------------*/
-int iniparser_getint(dictionary * d, const char * key, int notfound)
-{
- const char * str ;
-
- str = iniparser_getstring(d, key, INI_INVALID_KEY);
- if (str==INI_INVALID_KEY) return notfound ;
- return atoi(str);
-}
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Get the string associated to a key, convert to a double
- @param d Dictionary to search
- @param key Key string to look for
- @param notfound Value to return in case of error
- @return double
-
- This function queries a dictionary for a key. A key as read from an
- ini file is given as "section:key". If the key cannot be found,
- the notfound value is returned.
- */
-/*--------------------------------------------------------------------------*/
-double iniparser_getdouble(dictionary * d, char * key, double notfound)
-{
- const char * str ;
-
- str = iniparser_getstring(d, key, INI_INVALID_KEY);
- if (str==INI_INVALID_KEY) return notfound ;
- return atof(str);
-}
-
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Get the string associated to a key, convert to a boolean
- @param d Dictionary to search
- @param key Key string to look for
- @param notfound Value to return in case of error
- @return integer
-
- This function queries a dictionary for a key. A key as read from an
- ini file is given as "section:key". If the key cannot be found,
- the notfound value is returned.
-
- A true boolean is found if one of the following is matched:
-
- - A string starting with 'y'
- - A string starting with 'Y'
- - A string starting with 't'
- - A string starting with 'T'
- - A string starting with '1'
-
- A false boolean is found if one of the following is matched:
-
- - A string starting with 'n'
- - A string starting with 'N'
- - A string starting with 'f'
- - A string starting with 'F'
- - A string starting with '0'
-
- The notfound value returned if no boolean is identified, does not
- necessarily have to be 0 or 1.
- */
-/*--------------------------------------------------------------------------*/
-int iniparser_getboolean(dictionary * d, char * key, int notfound)
-{
- const char * c ;
- int ret ;
-
- c = iniparser_getstring(d, key, INI_INVALID_KEY);
- if (c==INI_INVALID_KEY) return notfound ;
- if (c[0]=='y' || c[0]=='Y' || c[0]=='1' || c[0]=='t' || c[0]=='T') {
- ret = 1 ;
- } else if (c[0]=='n' || c[0]=='N' || c[0]=='0' || c[0]=='f' || c[0]=='F') {
- ret = 0 ;
- } else {
- ret = notfound ;
- }
- return ret;
-}
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Finds out if a given entry exists in a dictionary
- @param ini Dictionary to search
- @param entry Name of the entry to look for
- @return integer 1 if entry exists, 0 otherwise
-
- Finds out if a given entry exists in the dictionary. Since sections
- are stored as keys with NULL associated values, this is the only way
- of querying for the presence of sections in a dictionary.
- */
-/*--------------------------------------------------------------------------*/
-
-int iniparser_find_entry(
- dictionary * ini,
- char * entry
-)
-{
- int found=0 ;
- if (iniparser_getstring(ini, entry, INI_INVALID_KEY)!=INI_INVALID_KEY) {
- found = 1 ;
- }
- return found ;
-}
-
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Set an entry in a dictionary.
- @param ini Dictionary to modify.
- @param entry Entry to modify (entry name)
- @param val New value to associate to the entry.
- @return int 0 if Ok, -1 otherwise.
-
- If the given entry can be found in the dictionary, it is modified to
- contain the provided value. If it cannot be found, -1 is returned.
- It is Ok to set val to NULL.
- */
-/*--------------------------------------------------------------------------*/
-
-int iniparser_setstr(dictionary * ini, char * entry, char * val)
-{
- dictionary_set(ini, strlwc(entry), val);
- return 0 ;
-}
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Delete an entry in a dictionary
- @param ini Dictionary to modify
- @param entry Entry to delete (entry name)
- @return void
-
- If the given entry can be found, it is deleted from the dictionary.
- */
-/*--------------------------------------------------------------------------*/
-void iniparser_unset(dictionary * ini, char * entry)
-{
- dictionary_unset(ini, strlwc(entry));
-}
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Parse an ini file and return an allocated dictionary object
- @param ininame Name of the ini file to read.
- @return Pointer to newly allocated dictionary
-
- This is the parser for ini files. This function is called, providing
- the name of the file to be read. It returns a dictionary object that
- should not be accessed directly, but through accessor functions
- instead.
-
- The returned dictionary must be freed using iniparser_free().
- */
-/*--------------------------------------------------------------------------*/
-
-dictionary * iniparser_new(const char *ininame)
-{
- dictionary * d ;
- char lin[ASCIILINESZ+1];
- char sec[ASCIILINESZ+1];
- char key[ASCIILINESZ+1];
- char val[ASCIILINESZ+1];
- char * where ;
- FILE * ini ;
- int lineno ;
-
- if ((ini=fopen(ininame, "r"))==NULL) {
- return NULL ;
- }
-
- sec[0]=0;
-
- /*
- * Initialize a new dictionary entry
- */
- d = dictionary_new(0);
- lineno = 0 ;
- while (fgets(lin, ASCIILINESZ, ini)!=NULL) {
- lineno++ ;
- where = strskp(lin); /* Skip leading spaces */
- if (*where==';' || *where=='#' || *where==0)
- continue ; /* Comment lines */
- else {
- if (sscanf(where, "[%[^]]", sec)==1) {
- /* Valid section name */
- strcpy(sec, strlwc(sec));
- iniparser_add_entry(d, sec, NULL, NULL);
- } else if (sscanf (where, "%[^=] = \"%[^\"]\"", key, val) == 2
- || sscanf (where, "%[^=] = '%[^\']'", key, val) == 2
- || sscanf (where, "%[^=] = %[^;#]", key, val) == 2) {
- strcpy(key, strlwc(strcrop(key)));
- /*
- * sscanf cannot handle "" or '' as empty value,
- * this is done here
- */
- if (!strcmp(val, "\"\"") || !strcmp(val, "''")) {
- val[0] = (char)0;
- } else {
- strcpy(val, strcrop(val));
- }
- iniparser_add_entry(d, sec, key, val);
- }
- }
- }
- fclose(ini);
- return d ;
-}
-
-
-
-/*-------------------------------------------------------------------------*/
-/**
- @brief Free all memory associated to an ini dictionary
- @param d Dictionary to free
- @return void
-
- Free all memory associated to an ini dictionary.
- It is mandatory to call this function before the dictionary object
- gets out of the current context.
- */
-/*--------------------------------------------------------------------------*/
-
-void iniparser_free(dictionary * d)
-{
- dictionary_del(d);
-}
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/src/external/iniparser/iniparser.h b/src/external/iniparser/iniparser.h
deleted file mode 100644
index 675b5a26a..000000000
--- a/src/external/iniparser/iniparser.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- Based upon libiniparser, by Nicolas Devillard
- Hacked into 1 file (m-iniparser) by Freek/2005
- Original terms following:
-
- -- -
-
- Copyright (c) 2000 by Nicolas Devillard (ndevilla AT free DOT fr).
-
- Written by Nicolas Devillard. Not derived from licensed software.
-
- Permission is granted to anyone to use this software for any
- purpose on any computer system, and to redistribute it freely,
- subject to the following restrictions:
-
- 1. The author is not responsible for the consequences of use of
- this software, no matter how awful, even if they arise
- from defects in it.
-
- 2. The origin of this software must not be misrepresented, either
- by explicit claim or by omission.
-
- 3. Altered versions must be plainly marked as such, and must not
- be misrepresented as being the original software.
-
- 4. This notice may not be removed or altered.
-
- */
-
-
-#ifndef _INIPARSER_H_
-#define _INIPARSER_H_
-#include
-#include
-#include
-#include
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-typedef struct _dictionary_ {
- /** Number of entries in dictionary */
- int n;
- /** Storage size */
- int size;
- /** List of string values */
- char **val;
- /** List of string keys */
- char **key ;
- /** List of hash values for keys */
- unsigned *hash;
-} dictionary ;
-
-
-/* generated by genproto */
-
-dictionary * iniparser_new(const char *ininame);
-void iniparser_free(dictionary * d);
-
-int iniparser_getnsec(dictionary * d);
-char * iniparser_getsecname(dictionary * d, int n);
-void iniparser_dump(dictionary * d, FILE * f);
-void iniparser_dump_ini(dictionary * d, FILE * f);
-char * iniparser_getkey(dictionary *d, char *section, char *key);
-const char * iniparser_getstr(dictionary * d, const char * key);
-const char * iniparser_getstring(dictionary * d, const char * key, const char * def);
-int iniparser_getint(dictionary * d, const char * key, int notfound);
-double iniparser_getdouble(dictionary * d, char * key, double notfound);
-int iniparser_getboolean(dictionary * d, char * key, int notfound);
-int iniparser_find_entry(dictionary * ini, char * entry);
-int iniparser_setstr(dictionary * ini, char * entry, char * val);
-void iniparser_unset(dictionary * ini, char * entry);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
diff --git a/src/external/lunit/ANNOUNCE b/src/external/lunit/ANNOUNCE
deleted file mode 100644
index c2e97fab5..000000000
--- a/src/external/lunit/ANNOUNCE
+++ /dev/null
@@ -1,15 +0,0 @@
-
- Lunit Release 0.5
- ===================
-
-Lunit is a unit testing framework for lua, written in lua.
-
-Lunit provides 27 assert functions, and a few misc functions
-for usage in an easy unit testing framework.
-
-Lunit comes with a test suite to test itself. The testsuite
-consists of approximately 710 assertions.
-
-Lunit is licensed under the MIT license.
-
-Lunit can downloaded from http://www.mroth.net/lunit/
diff --git a/src/external/lunit/CHANGES b/src/external/lunit/CHANGES
deleted file mode 100644
index 09927e537..000000000
--- a/src/external/lunit/CHANGES
+++ /dev/null
@@ -1,30 +0,0 @@
-Release 0.5:
-
- New test function assert_error_match().
- Lunit shell script returns an error code on failed tests.
- Be more compatible with Darwin / Mac OS X.
- Bug fixes.
-
-Release 0.4:
-
- Mostly complete rewrite.
- Lua-5.1 only.
-
-
-Release 0.3 (alpha):
-
- New function lunit.wrap() to wrap a single function in a
- complete test case.
-
- Now a backtrace is printed, if an error or failure occurs
- in a test case.
-
-
-Release 0.2 (alpha):
-
- The test suite consists now of approximately 630 assertions.
-
- Fixed an ugly bug in lunit.assert()! Testcases for lunit.assert()
- added.
-
- Now all assert functions return the actual value on success.
diff --git a/src/external/lunit/DOCUMENTATION b/src/external/lunit/DOCUMENTATION
deleted file mode 100644
index bcf33762e..000000000
--- a/src/external/lunit/DOCUMENTATION
+++ /dev/null
@@ -1,245 +0,0 @@
-
-To use the lunit unit testing framework copy these files to your
-lua search path or include it to your package:
-
- lunit
- lunit.lua
- lunit-console.lua
-
-
-To write a testcase, open the framework using require. The "lunit" shell script
-works hard to find the "lunit.lua" and "lunit-console.lua" in all cases.
-
- require "lunit"
-
-
-Lunit uses the lua-5.1 module system. A testcase is a arbitrarily named module
-marked with "lunit.testcase" as a testcase. An example:
-
- require "lunit"
-
- module( "my_testcase", lunit.testcase, package.seeall )
-
-
-The tests itself in a testcase are functions whose names must begin
-or end with 'test'. The function names are case insensitive. Example:
-
- require "lunit"
-
- module( "my_testcase", lunit.testcase, package.seeall )
-
- function FirstTest()
- -- Test code goes here
- end
-
- function test_something()
- -- Test code goes here
- end
-
-
-Inside the test functions you use asserts to test your code or package.
-Lunit defines 26 assert functions:
-
- fail( [msg] )
-
- Always fails.
-
- assert( assertion, [msg] )
-
- Fails, if 'assertion' is false or nil.
-
- assert_true( actual, [msg] )
-
- Fails, if 'actual' isn't true.
-
- assert_false( actual, [msg] )
-
- Fails, if 'actual' isn't false. (Even fails if 'actual' is
- a nil value!)
-
- assert_equal( expected, actual, [msg] )
-
- Fails, if 'actual' is different from 'expected'. Make sure
- that you don't mix 'expected' and 'actual' because they are
- used to build a nice error message.
-
- assert_not_equal( unexpected, actual, [msg] )
-
- Fails, if 'actual' and 'unexpected' are equal.
-
- assert_match( pattern, actual, [msg] )
-
- Fails, if the string 'actual' doesn't match 'pattern'.
-
- assert_not_match( pattern, actual, [msg] )
-
- Fails, if the string 'actual' match 'pattern'.
-
- assert_nil( actual, [msg] )
-
- Fails, if 'actual' isn't a nil value.
-
- assert_not_nil( actual, [msg] )
-
- Fails, if 'actual' is a nil value.
-
- assert_boolean( actual, [msg] )
-
- Fails, if 'actual' isn't true or false.
-
- assert_not_boolean( actual, [msg] )
-
- Fails, if 'actual' is true or false.
-
- assert_number( actual, [msg] )
-
- Fails, if 'actual' isn't a number.
-
- assert_not_number( actual, [msg] )
-
- Fails, if 'actual' is a number.
-
- assert_string( actual, [msg] )
-
- Fails, if 'actual' isn't a string.
-
- assert_not_string( actual, [msg] )
-
- Fails, if 'actual' is a string.
-
- assert_table( actual, [msg] )
-
- Fails, if 'actual' isn't a table.
-
- assert_not_table( actual, [msg] )
-
- Fails, if 'actual' is a table.
-
- assert_function( actual, [msg] )
-
- Fails, if 'actual' isn't a function.
-
- assert_not_function( actual, [msg] )
-
- Fails, if 'actual' is a function.
-
- assert_thread( actual, [msg] )
-
- Fails, if 'actual' isn't a thread (created by
- coroutine.create or coroutine.wrap).
-
- assert_not_thread( actual, [msg] )
-
- Fails, if 'actual' is a thread.
-
- assert_userdata( actual, [msg] )
-
- Fails, if 'actual' isn't userdata.
-
- assert_not_userdata( actual, [msg] )
-
- Fails, if 'actual' is userdata.
-
- assert_error( [msg], func )
-
- Fails, if 'func' doesn't raises an error (using error()).
-
- assert_pass( [msg], func )
-
- Fails, if 'func' raises an error.
-
-
-All assert functions take an optional message as the last argument. Only
-assert_pass() and assert_error() require the optional message as the first
-argument. The last argument of these two are functions.
-
-There are also useful functions to test for the type of a value:
-
- is_nil( actual )
- is_boolean( actual )
- is_number( actual )
- is_string( actual )
- is_table( actual )
- is_function( actual )
- is_thread( actual )
- is_userdata( actual )
-
-These all returns true if 'actual' is of correct type, otherwise false.
-
-You use the assert functions and the is_type functions in your tests to check
-your code or package. Example:
-
- require "lunit"
-
- module( "my_testcase", lunit.testcase, package.seeall )
-
- function FirstTest()
- local result = compute_some_value()
- assert_string( result )
- assert_equal("foobar", result)
- end
-
- function test_something()
- local result = flip_coin() -- flip_coin returns at random 0 or 1
- assert_number(result)
- if result == 0 then
- -- ok
- elseif result == 1 then
- -- ok
- else
- fail("flip_coin: invalid number: "..tostring(result))
- end
- end
-
-
-You can define the functions setup() and teardown() if you have to allocate
-some resources or obtain some handles for your tests.
-The setup() function is called before every test and teardown() is
-called after every test. Example:
-
- require "lunit"
-
- module( "resource_testcase", lunit.testcase, package.seeall )
-
- local orig_content, handle
-
- function setup()
- orig_content = { "row 1", "row 2", "row 3" }
- handle = database_open("test.db")
- database_create_table(handle, ...)
- database_fill_table(handle, orig_content, ...)
- end
-
- function teardown()
- database_drop_table(handle, ...)
- database_close(handle)
- handle = nil
- orig_content = nil
- delete_file("test.db")
- end
-
- function test_select()
- local content = database_select(handle, ...)
- assert_table( content )
- assert_equal( orig_content, content )
- end
-
- function test_insert()
- database_insert(handle, "row 4", ...)
- local content = database_select(handle, ...)
- assert_table( content )
- assert_equal( { "row 1", "row 2", "row 3", "row 4" }, content )
- end
-
- function test_delete()
- database_delete(handle, "row 2", ...)
- local content = database_select(handle, ...)
- assert_table( content )
- assert_equal( { "row 1", "row 3" }, content )
- end
-
-
-To run your testcases, simply use the shell script "lunit". Example:
-
- # ./lunit my_testcase.lua
-
diff --git a/src/external/lunit/LICENSE b/src/external/lunit/LICENSE
deleted file mode 100644
index 1cd362603..000000000
--- a/src/external/lunit/LICENSE
+++ /dev/null
@@ -1,32 +0,0 @@
-
-Lunit License
--------------
-
-Lunit is written by Michael Roth and is licensed
-under the terms of the MIT license reproduced below.
-
-========================================================================
-
-Copyright (c) 2004-2009 Michael Roth
-
-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.
-
-========================================================================
-
diff --git a/src/external/lunit/PATCHES b/src/external/lunit/PATCHES
deleted file mode 100644
index 2226ac119..000000000
--- a/src/external/lunit/PATCHES
+++ /dev/null
@@ -1,12 +0,0 @@
-Lunit is available through a public GIT repository.
-To get the latest lunit source code, do:
-
- git clone git://repo.or.cz/lunit.git
-
-Currently there is no mailing list dedicated to lunit so if you have patches,
-please send them to:
-
- mroth@nessie.de
-
-Please don't forget to add a Signed-Off-By line (git option -s or --signoff)
-to state that your patches apply to the MIT license.
diff --git a/src/external/lunit/README b/src/external/lunit/README
deleted file mode 100644
index 690c148a1..000000000
--- a/src/external/lunit/README
+++ /dev/null
@@ -1,12 +0,0 @@
-This is lunit Version 0.5.
-
-Lunit is a unit testing framework for lua.
-
-To learn more about lunit take a look in ANNOUNCE
-and look in DOCUMENTATION and check example.lua.
-
-If you have suggestions, questions or feature request please
-feel free to contact me.
-
-
-Michael Roth
diff --git a/src/external/lunit/example.lua b/src/external/lunit/example.lua
deleted file mode 100644
index 45347d5bc..000000000
--- a/src/external/lunit/example.lua
+++ /dev/null
@@ -1,40 +0,0 @@
-
-require "lunit"
-
-
-
-module( "simple", package.seeall, lunit.testcase )
-
-function test_success()
- assert_true( true, "This test never fails.")
-end
-
-function test_failure()
- assert_true( false, "This test always fails!")
-end
-
-
-
-module( "enhanced", package.seeall, lunit.testcase )
-
-local foobar = nil
-
-function setup()
- foobar = "Hello World"
-end
-
-function teardown()
- foobar = nil
-end
-
-function test1()
- assert_equal("Hello World", foobar)
- foobar = string.sub(foobar, 1, 5)
- assert_equal("Hello", foobar)
-end
-
-function test2()
- assert_equal("Hello World", foobar)
- foobar = string.sub(foobar, -5)
- assert_equal("World", foobar)
-end
diff --git a/src/external/lunit/lunit-console.lua b/src/external/lunit/lunit-console.lua
deleted file mode 100644
index 90c5165ed..000000000
--- a/src/external/lunit/lunit-console.lua
+++ /dev/null
@@ -1,141 +0,0 @@
-
---[[--------------------------------------------------------------------------
-
- This file is part of lunit 0.5.
-
- For Details about lunit look at: http://www.mroth.net/lunit/
-
- Author: Michael Roth
-
- Copyright (c) 2006-2008 Michael Roth
-
- 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.
-
---]]--------------------------------------------------------------------------
-
-
-
---[[
-
- begin()
- run(testcasename, testname)
- err(fullname, message, traceback)
- fail(fullname, where, message, usermessage)
- pass(testcasename, testname)
- done()
-
- Fullname:
- testcase.testname
- testcase.testname:setupname
- testcase.testname:teardownname
-
---]]
-
-
-require "lunit"
-
-module( "lunit-console", package.seeall )
-
-
-local function printformat(format, ...)
- io.write( string.format(format, ...) )
-end
-
-
-local columns_printed = 0
-
-local function writestatus(char)
- if columns_printed == 0 then
- io.write(" ")
- end
- if columns_printed == 60 then
- io.write("\n ")
- columns_printed = 0
- end
- io.write(char)
- io.flush()
- columns_printed = columns_printed + 1
-end
-
-
-local msgs = {}
-
-
-function begin()
- local total_tc = 0
- local total_tests = 0
-
- for tcname in lunit.testcases() do
- total_tc = total_tc + 1
- for testname, test in lunit.tests(tcname) do
- total_tests = total_tests + 1
- end
- end
-
- printformat("Loaded testsuite with %d tests in %d testcases.\n\n", total_tests, total_tc)
-end
-
-
-function run(testcasename, testname)
- -- NOP
-end
-
-
-function err(fullname, message, traceback)
- writestatus("E")
- msgs[#msgs+1] = "Error! ("..fullname.."):\n"..message.."\n\t"..table.concat(traceback, "\n\t") .. "\n"
-end
-
-
-function fail(fullname, where, message, usermessage)
- writestatus("F")
- local text = "Failure ("..fullname.."):\n"..
- where..": "..message.."\n"
-
- if usermessage then
- text = text .. where..": "..usermessage.."\n"
- end
-
- msgs[#msgs+1] = text
-end
-
-
-function pass(testcasename, testname)
- writestatus(".")
-end
-
-
-
-function done()
- printformat("\n\n%d Assertions checked.\n", lunit.stats.assertions )
- print()
-
- for i, msg in ipairs(msgs) do
- printformat( "%3d) %s\n", i, msg )
- end
-
- printformat("Testsuite finished (%d passed, %d failed, %d errors).\n",
- lunit.stats.passed, lunit.stats.failed, lunit.stats.errors )
-end
-
-
-
-
-
diff --git a/src/external/lunit/lunit-tests.lua b/src/external/lunit/lunit-tests.lua
deleted file mode 100644
index c5e39623a..000000000
--- a/src/external/lunit/lunit-tests.lua
+++ /dev/null
@@ -1,991 +0,0 @@
-
---[[--------------------------------------------------------------------------
-
- This file is part of lunit 0.5.
-
- For Details about lunit look at: http://www.mroth.net/lunit/
-
- Author: Michael Roth
-
- Copyright (c) 2004, 2006-2009 Michael Roth
-
- 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.
-
---]]--------------------------------------------------------------------------
-
-
-require "lunit"
-
-
-local a_number = 123
-local a_string = "A string"
-local a_table = { }
-local a_function = function() end
-local a_thread = coroutine.create(function() end)
-
-local pcall = pcall
-local error = error
-local pairs = pairs
-local ipairs = ipairs
-
-local module = module
-
-
-
-module( "lunit-tests.interface", lunit.testcase )
-
-function test()
- local funcnames = {
- "main", "run", "runtest", "testcase", "testcases", "tests", "setupname",
- "teardownname", "loadrunner", "setrunner", "loadonly",
- "assert", "assert_true", "assert_false", "assert_equal", "assert_not_equal",
- "assert_match", "assert_not_match", "assert_nil", "assert_not_nil",
- "assert_boolean", "assert_not_boolean", "assert_number", "assert_not_number",
- "assert_string", "assert_not_string", "assert_table", "assert_not_table",
- "assert_function", "assert_not_function", "assert_thread", "assert_not_thread",
- "assert_userdata", "assert_not_userdata", "assert_pass", "assert_error",
- "assert_error_match", "fail", "clearstats",
- "is_nil", "is_boolean", "is_number", "is_string", "is_table", "is_function",
- "is_thread", "is_userdata"
- }
-
- for _, funcname in ipairs(funcnames) do
- assert_function( lunit[funcname], "Public function missing: "..funcname )
- end
-
- assert_table( lunit.stats, "Statistic table missing" )
-
- do
- local map = {}
- for _, name in ipairs(funcnames) do
- map[name] = true
- end
- for _, name in ipairs{"lunit", "_PACKAGE", "_M", "_NAME", "stats"} do
- map[name] = true
- end
- for name, _ in pairs(lunit) do
- assert( map[name], "Invalid public variable: lunit."..name )
- end
- end
-end
-
-
-
--- We must assume that errors thrown by test functions are detected. We use
--- the stdlib error() function to signal errors instead of fail().
-module( "lunit-tests.basics", lunit.testcase )
-
-function test_fail()
- local ok, errmsg
-
- ok, errmsg = pcall(function() fail() end)
- if ok then
- error("fail() doesn't fail!")
- end
-
- ok, errmsg = pcall(function() fail("A message") end)
- if ok then
- error("fail(\"A message\") doesn't fail!")
- end
-end
-
-function test_assert_error()
- local ok, errmsg
-
- ok, errmsg = pcall(function() assert_error(function() error("Error!") end) end)
- if not ok then
- error("assert_error( ) doesn't work!")
- end
-
- ok, errmsg = pcall(function() assert_error("A message", function() error("Error") end) end)
- if not ok then
- error("assert_error(\"A message\", ) doesn't work!")
- end
-
- ok, errmsg = pcall(function() assert_error(function() end) end)
- if ok then
- error("assert_error( ) doesn't fail!")
- end
-
- ok, errmsg = pcall(function() assert_error("A Message", function() end) end)
- if ok then
- error("assert_error(\"A message\", ) doesn't fail!")
- end
-end
-
-function test_assert_pass()
- local ok, errmsg
-
- ok, errmsg = pcall(function() assert_pass(function() error("Error!") end) end)
- if ok then
- error("assert_pass( ) doesn't fail!")
- end
-
- ok, errmsg = pcall(function() assert_pass("A message", function() error("Error") end) end)
- if ok then
- error("assert_pass(\"A message\", ) doesn't fail!")
- end
-
- ok, errmsg = pcall(function() assert_pass(function() end) end)
- if not ok then
- error("assert_pass( ) doesn't work!")
- end
-
- ok, errmsg = pcall(function() assert_pass("A Message", function() end) end)
- if not ok then
- error("assert_pass(\"A message\", ) doesn't work!")
- end
-end
-
-function test_assert_true()
- assert_pass("assert_true(true) doesn't work!", function() assert_true(true) end)
- assert_pass("assert_true(true, \"A message\" doesn't work!", function() assert_true(true, "A Message") end)
- assert_error("assert_true(false) doesn't fail!", function() assert_true(false) end)
- assert_error("assert_true(false, \"A message\" doesn't fail!", function() assert_true(false, "A Message") end)
-end
-
-function test_assert_false()
- assert_pass("assert_false(false) doesn't work!", function() assert_false(false) end)
- assert_pass("assert_false(false, \"A message\" doesn't work!", function() assert_false(false, "A Message") end)
- assert_error("assert_false(true) doesn't fail!", function() assert_false(true) end)
- assert_error("assert_false(true, \"A message\" doesn't fail!", function() assert_false(true, "A Message") end)
-end
-
-function test_assert()
- assert_pass("assert(true) doesn't work!", function() assert(true) end)
- assert_pass("assert(12345) doesn't work!", function() assert(12345) end)
- assert_pass("assert(\"A string\") doesn't work!", function() assert("A string") end)
- assert_pass("assert( {} ) doesn't work!", function() assert( {} ) end)
- assert_error("assert_(false) doesn't fail!", function() assert(false) end)
- assert_error("assert_(nil) doesn't fail!", function() assert(nil) end)
-end
-
-function test_assert_equal()
- assert_pass("assert_equal(\"A String\", \"A String\") doesn't work!", function()
- local a_string = assert_equal("A String", "A String")
- assert_true("A String" == a_string)
- end)
-
- assert_pass("assert_equal(\"A String\", \"A String\", \"A message\") doesn't work!", function()
- local a_string = assert_equal("A String", "A String", "A message")
- assert_true("A String" == a_string)
- end)
-
- assert_pass("assert_equal(12345, 12345) doesn't work!", function()
- local a_number = assert_equal(12345, 12345)
- assert_true(12345 == a_number)
- end)
-
- assert_pass("assert_equal(12345, 12345, \"A message\") doesn't work!", function()
- local a_number = assert_equal(12345, 12345, "A message")
- assert_true(12345 == a_number)
- end)
-
- assert_pass("assert_equal(nil, nil) doesn't work!", function()
- local a_nil = assert_equal(nil, nil)
- assert_true(nil == a_nil)
- end)
-
- assert_pass("assert_equal(12345, 12345, \"A message\") doesn't work!", function()
- local a_nil = assert_equal(nil, nil, "A message")
- assert_true(nil == a_nil)
- end)
-
- assert_pass("assert_equal(false, false) doesn't work!", function()
- local a_false = assert_equal(false, false)
- assert_true(false == a_false)
- end)
-
- assert_pass("assert_equal(false, false, \"A message\") doesn't work!", function()
- local a_false = assert_equal(false, false, "A message")
- assert_true(false == a_false)
- end)
-
- assert_pass("assert_equal(true, true) doesn't work!", function()
- local a_true = assert_equal(true, true)
- assert_true(true == a_true)
- end)
-
- assert_pass("assert_equal(true, true, \"A message\") doesn't work!", function()
- local a_true = assert_equal(true, true, "A message")
- assert_true(true == a_true)
- end)
-
- assert_error("assert_equal(\"A String\", \"Another String\") doesn't fail!", function()
- assert_equal("A String", "Another String")
- end)
-
- assert_error("assert_equal(\"A String\", \"Another String\", \"A message\") doesn't fail!", function()
- assert_equal("A String", "Another String", "A message")
- end)
-
- assert_error("assert_equal(123, 456) doesn't fail!", function()
- assert_equal(123, 456)
- end)
-
- assert_error("assert_equal(123, 456) \"A message\") doesn't fail!", function()
- assert_equal(123, 456, "A message")
- end)
-
- assert_error("assert_equal(true, false) doesn't fail!", function()
- assert_equal(true, false)
- end)
-
- assert_error("assert_equal(true, false) \"A message\") doesn't fail!", function()
- assert_equal(true, false, "A message")
- end)
-
- assert_error("assert_equal(true, nil) doesn't fail!", function()
- assert_equal(true, nil)
- end)
-
- assert_error("assert_equal(true, nil) \"A message\") doesn't fail!", function()
- assert_equal(true, nil, "A message")
- end)
-
- assert_error("assert_equal(false, true) doesn't fail!", function()
- assert_equal(false, true)
- end)
-
- assert_error("assert_equal(false, true, \"A message\") doesn't fail!", function()
- assert_equal(false, true, "A message")
- end)
-
- assert_error("assert_equal(false, nil) doesn't fail!", function()
- assert_equal(false, nil)
- end)
-
- assert_error("assert_equal(false, nil) \"A message\") doesn't fail!", function()
- assert_equal(false, nil, "A message")
- end)
-
- assert_error("assert_equal(nil, true) doesn't fail!", function()
- assert_equal(nil, true)
- end)
-
- assert_error("assert_equal(nil, true) \"A message\") doesn't fail!", function()
- assert_equal(nil, true, "A message")
- end)
-
- assert_error("assert_equal(nil, false) doesn't fail!", function()
- assert_equal(nil, false)
- end)
-
- assert_error("assert_equal(nil, false) \"A message\") doesn't fail!", function()
- assert_equal(nil, false, "A message")
- end)
-end
-
-
-function test_assert_not_equal()
- assert_pass("assert_not_equal(\"A String\", \"Another String\") doesn't work!", function()
- local a_string = assert_not_equal("A String", "Another String")
- assert_true("Another String" == a_string)
- end)
-
- assert_pass("assert_not_equal(\"A String\", \"Another String\", \"A message\") doesn't work!", function()
- local a_string = assert_not_equal("A String", "Another String", "A message")
- assert_true("Another String" == a_string)
- end)
-
- assert_pass("assert_not_equal(123, 456) doesn't work!", function()
- local a_number = assert_not_equal(123, 456)
- assert_true(456 == a_number)
- end)
-
- assert_pass("assert_not_equal(123, 456, \"A message\") doesn't work!", function()
- local a_number = assert_not_equal(123, 456, "A message")
- assert_true(456 == a_number)
- end)
-
- assert_pass("assert_not_equal(true, false) doesn't work!", function()
- local a_false = assert_not_equal(true, false)
- assert_true(false == a_false)
- end)
-
- assert_pass("assert_not_equal(true, false) \"A message\") doesn't work!", function()
- local a_false = assert_not_equal(true, false, "A message")
- assert_true(false == a_false)
- end)
-
- assert_pass("assert_not_equal(true, nil) doesn't work!", function()
- local a_nil = assert_not_equal(true, nil)
- assert_true(nil == a_nil)
- end)
-
- assert_pass("assert_not_equal(true, nil) \"A message\") doesn't work!", function()
- local a_nil = assert_not_equal(true, nil, "A message")
- assert_true(nil == a_nil)
- end)
-
- assert_pass("assert_not_equal(false, true) doesn't work!", function()
- local a_true = assert_not_equal(false, true)
- assert_true(true == a_true)
- end)
-
- assert_pass("assert_not_equal(false, true, \"A message\") doesn't work!", function()
- local a_true = assert_not_equal(false, true, "A message")
- assert_true(true == a_true)
- end)
-
- assert_pass("assert_not_equal(false, nil) doesn't work!", function()
- local a_nil = assert_not_equal(false, nil)
- assert_true(nil == a_nil)
- end)
-
- assert_pass("assert_not_equal(false, nil) \"A message\") doesn't work!", function()
- local a_nil = assert_not_equal(false, nil, "A message")
- assert_true(nil == a_nil)
- end)
-
- assert_pass("assert_not_equal(nil, true) doesn't work!", function()
- local a_true = assert_not_equal(nil, true)
- assert_true(true == a_true)
- end)
-
- assert_pass("assert_not_equal(nil, true) \"A message\") doesn't work!", function()
- local a_true = assert_not_equal(nil, true, "A message")
- assert_true(true == a_true)
- end)
-
- assert_pass("assert_not_equal(nil, false) doesn't work!", function()
- local a_false = assert_not_equal(nil, false)
- assert_true(false == a_false)
- end)
-
- assert_pass("assert_not_equal(nil, false) \"A message\") doesn't work!", function()
- local a_false = assert_not_equal(nil, false, "A message")
- assert_true(false == a_false)
- end)
-
- assert_error("assert_not_equal(\"A String\", \"A String\") doesn't work!", function()
- assert_not_equal("A String", "A String")
- end)
-
- assert_error("assert_not_equal(\"A String\", \"A String\", \"A message\") doesn't fail!", function()
- assert_not_equal("A String", "A String", "A message")
- end)
-
- assert_error("assert_not_equal(12345, 12345) doesn't fail!", function()
- assert_not_equal(12345, 12345)
- end)
-
- assert_error("assert_not_equal(12345, 12345, \"A message\") doesn't fail!", function()
- assert_not_equal(12345, 12345, "A message")
- end)
-
- assert_error("assert_not_equal(nil, nil) doesn't fail!", function()
- assert_not_equal(nil, nil)
- end)
-
- assert_error("assert_not_equal(nil, nil, \"A message\") doesn't fail!", function()
- assert_not_equal(nil, nil, "A message")
- end)
-
- assert_error("assert_not_equal(false, false) doesn't fail!", function()
- assert_not_equal(false, false)
- end)
-
- assert_error("assert_not_equal(false, false, \"A message\") doesn't fail!", function()
- assert_not_equal(false, false, "A message")
- end)
-
- assert_error("assert_not_equal(true, true) doesn't fail!", function()
- assert_not_equal(true, true)
- end)
-
- assert_error("assert_not_equal(true, true, \"A message\") doesn't fail!", function()
- assert_not_equal(true, true, "A message")
- end)
-end
-
-
-
-module( "lunit-tests.is_xyz", lunit.testcase )
-
-function test_is_nil()
- assert_true( is_nil(nil) )
- assert_false( is_nil(true) )
- assert_false( is_nil(false) )
- assert_false( is_nil(a_number) )
- assert_false( is_nil(a_string) )
- assert_false( is_nil(a_table) )
- assert_false( is_nil(a_function) )
- assert_false( is_nil(a_thread) )
-end
-
-function test_is_boolean()
- assert_true( is_boolean(false) )
- assert_true( is_boolean(true) )
- assert_false( is_boolean(nil) )
- assert_false( is_boolean(a_number) )
- assert_false( is_boolean(a_string) )
- assert_false( is_boolean(a_table) )
- assert_false( is_boolean(a_function) )
- assert_false( is_boolean(a_thread) )
-end
-
-function test_is_number()
- assert_true( is_number(a_number) )
- assert_false( is_number(nil) )
- assert_false( is_number(true) )
- assert_false( is_number(false) )
- assert_false( is_number(a_string) )
- assert_false( is_number(a_table) )
- assert_false( is_number(a_function) )
- assert_false( is_number(a_thread) )
-end
-
-function test_is_string()
- assert_true( is_string(a_string) )
- assert_false( is_string(nil) )
- assert_false( is_string(true) )
- assert_false( is_string(false) )
- assert_false( is_string(a_number) )
- assert_false( is_string(a_table) )
- assert_false( is_string(a_function) )
- assert_false( is_string(a_thread) )
-end
-
-function test_is_table()
- assert_true( is_table(a_table) )
- assert_false( is_table(nil) )
- assert_false( is_table(true) )
- assert_false( is_table(false) )
- assert_false( is_table(a_number) )
- assert_false( is_table(a_string) )
- assert_false( is_table(a_function) )
- assert_false( is_table(a_thread) )
-end
-
-function test_is_function()
- assert_true( is_function(a_function) )
- assert_false( is_function(nil) )
- assert_false( is_function(true) )
- assert_false( is_function(false) )
- assert_false( is_function(a_number) )
- assert_false( is_function(a_string) )
- assert_false( is_function(a_table) )
- assert_false( is_function(a_thread) )
-end
-
-function test_is_thread()
- assert_true( is_thread(a_thread) )
- assert_false( is_thread(nil) )
- assert_false( is_thread(true) )
- assert_false( is_thread(false) )
- assert_false( is_thread(a_number) )
- assert_false( is_thread(a_string) )
- assert_false( is_thread(a_table) )
- assert_false( is_thread(a_function) )
-end
-
-
-
-module( "lunit-tests.assert_not_xyz", lunit.testcase )
-
-function test_assert_not_nil()
- assert_not_nil( true )
- assert_not_nil( false )
- assert_not_nil( a_number )
- assert_not_nil( a_string )
- assert_not_nil( a_table )
- assert_not_nil( a_function )
- assert_not_nil( a_thread )
-
- assert_not_nil( true, "A message")
- assert_not_nil( false, "A message")
- assert_not_nil( a_number, "A message")
- assert_not_nil( a_string, "A message")
- assert_not_nil( a_table, "A message")
- assert_not_nil( a_function, "A message")
- assert_not_nil( a_thread, "A message")
-
- assert_error(function() assert_not_nil(nil) end)
- assert_error(function() assert_not_nil(nil, "A message") end)
-end
-
-function test_assert_not_boolean()
- assert_not_boolean( nil )
- assert_not_boolean( a_number )
- assert_not_boolean( a_string )
- assert_not_boolean( a_table )
- assert_not_boolean( a_function )
- assert_not_boolean( a_thread )
-
- assert_not_boolean( nil, "A message")
- assert_not_boolean( a_number, "A message")
- assert_not_boolean( a_string, "A message")
- assert_not_boolean( a_table, "A message")
- assert_not_boolean( a_function, "A message")
- assert_not_boolean( a_thread, "A message")
-
- assert_error(function() assert_not_boolean(true) end)
- assert_error(function() assert_not_boolean(true, "A message") end)
- assert_error(function() assert_not_boolean(false) end)
- assert_error(function() assert_not_boolean(false, "A message") end)
-end
-
-function test_assert_not_number()
- assert_not_number( nil )
- assert_not_number( true )
- assert_not_number( false )
- assert_not_number( a_string )
- assert_not_number( a_table )
- assert_not_number( a_function )
- assert_not_number( a_thread )
-
- assert_not_number( nil, "A message")
- assert_not_number( true, "A message")
- assert_not_number( false, "A message")
- assert_not_number( a_string, "A message")
- assert_not_number( a_table, "A message")
- assert_not_number( a_function, "A message")
- assert_not_number( a_thread, "A message")
-
- assert_error(function() assert_not_number(a_number) end)
- assert_error(function() assert_not_number(a_number, "A message") end)
-end
-
-function test_assert_not_string()
- assert_not_string( nil )
- assert_not_string( true )
- assert_not_string( false )
- assert_not_string( a_number )
- assert_not_string( a_table )
- assert_not_string( a_function )
- assert_not_string( a_thread )
-
- assert_not_string( nil, "A message")
- assert_not_string( true, "A message")
- assert_not_string( false, "A message")
- assert_not_string( a_number, "A message")
- assert_not_string( a_table, "A message")
- assert_not_string( a_function, "A message")
- assert_not_string( a_thread, "A message")
-
- assert_error(function() assert_not_string(a_string) end)
- assert_error(function() assert_not_string(a_string, "A message") end)
-end
-
-function test_assert_not_table()
- assert_not_table( nil )
- assert_not_table( true )
- assert_not_table( false )
- assert_not_table( a_number )
- assert_not_table( a_string )
- assert_not_table( a_function )
- assert_not_table( a_thread )
-
- assert_not_table( nil, "A message")
- assert_not_table( true, "A message")
- assert_not_table( false, "A message")
- assert_not_table( a_number, "A message")
- assert_not_table( a_string, "A message")
- assert_not_table( a_function, "A message")
- assert_not_table( a_thread, "A message")
-
- assert_error(function() assert_not_table(a_table) end)
- assert_error(function() assert_not_table(a_table, "A message") end)
-end
-
-function test_assert_not_function()
- assert_not_function( nil )
- assert_not_function( true )
- assert_not_function( false )
- assert_not_function( a_number )
- assert_not_function( a_string )
- assert_not_function( a_table )
- assert_not_function( a_thread )
-
- assert_not_function( nil, "A message")
- assert_not_function( true, "A message")
- assert_not_function( false, "A message")
- assert_not_function( a_number, "A message")
- assert_not_function( a_string, "A message")
- assert_not_function( a_table, "A message")
- assert_not_function( a_thread, "A message")
-
- assert_error(function() assert_not_function(a_function) end)
- assert_error(function() assert_not_function(a_function, "A message") end)
-end
-
-function test_assert_not_thread()
- assert_not_thread( nil )
- assert_not_thread( true )
- assert_not_thread( false )
- assert_not_thread( a_number )
- assert_not_thread( a_string )
- assert_not_thread( a_table )
- assert_not_thread( a_function )
-
- assert_not_thread( nil, "A message")
- assert_not_thread( true, "A message")
- assert_not_thread( false, "A message")
- assert_not_thread( a_number, "A message")
- assert_not_thread( a_string, "A message")
- assert_not_thread( a_table, "A message")
- assert_not_thread( a_function, "A message")
-
- assert_error(function() assert_not_thread(a_thread) end)
- assert_error(function() assert_not_thread(a_thread, "A message") end)
-end
-
-
-
-module( "lunit-tests.assert_xyz", lunit.testcase )
-
-function test_assert_nil()
- assert_nil( nil )
- assert_nil( nil, "A message" )
-
- assert_error( function() assert_nil( true ) end)
- assert_error( function() assert_nil( false ) end)
- assert_error( function() assert_nil( a_number ) end)
- assert_error( function() assert_nil( a_string ) end)
- assert_error( function() assert_nil( a_table ) end)
- assert_error( function() assert_nil( a_function ) end)
- assert_error( function() assert_nil( a_thread ) end)
-
- assert_error( function() assert_nil( true, "A message" ) end)
- assert_error( function() assert_nil( false, "A message" ) end)
- assert_error( function() assert_nil( a_number, "A message" ) end)
- assert_error( function() assert_nil( a_string, "A message" ) end)
- assert_error( function() assert_nil( a_table, "A message" ) end)
- assert_error( function() assert_nil( a_function, "A message" ) end)
- assert_error( function() assert_nil( a_thread, "A message" ) end)
-end
-
-function test_assert_boolean()
- assert_boolean( true )
- assert_boolean( false )
- assert_boolean( true, "A message" )
- assert_boolean( false, "A message" )
-
- assert_error( function() assert_boolean( nil ) end)
- assert_error( function() assert_boolean( a_number ) end)
- assert_error( function() assert_boolean( a_string ) end)
- assert_error( function() assert_boolean( a_table ) end)
- assert_error( function() assert_boolean( a_function ) end)
- assert_error( function() assert_boolean( a_thread ) end)
-
- assert_error( function() assert_boolean( nil, "A message" ) end)
- assert_error( function() assert_boolean( a_number, "A message" ) end)
- assert_error( function() assert_boolean( a_string, "A message" ) end)
- assert_error( function() assert_boolean( a_table, "A message" ) end)
- assert_error( function() assert_boolean( a_function, "A message" ) end)
- assert_error( function() assert_boolean( a_thread, "A message" ) end)
-end
-
-function test_assert_number()
- assert_number( a_number )
- assert_number( a_number, "A message" )
-
- assert_error( function() assert_number( nil ) end)
- assert_error( function() assert_number( true ) end)
- assert_error( function() assert_number( false ) end)
- assert_error( function() assert_number( a_string ) end)
- assert_error( function() assert_number( a_table ) end)
- assert_error( function() assert_number( a_function ) end)
- assert_error( function() assert_number( a_thread ) end)
-
- assert_error( function() assert_number( nil, "A message" ) end)
- assert_error( function() assert_number( true, "A message" ) end)
- assert_error( function() assert_number( false, "A message" ) end)
- assert_error( function() assert_number( a_string, "A message" ) end)
- assert_error( function() assert_number( a_table, "A message" ) end)
- assert_error( function() assert_number( a_function, "A message" ) end)
- assert_error( function() assert_number( a_thread, "A message" ) end)
-end
-
-function test_assert_string()
- assert_string( a_string )
- assert_string( a_string, "A message" )
-
- assert_error( function() assert_string( nil ) end)
- assert_error( function() assert_string( true ) end)
- assert_error( function() assert_string( false ) end)
- assert_error( function() assert_string( a_number ) end)
- assert_error( function() assert_string( a_table ) end)
- assert_error( function() assert_string( a_function ) end)
- assert_error( function() assert_string( a_thread ) end)
-
- assert_error( function() assert_string( nil, "A message" ) end)
- assert_error( function() assert_string( true, "A message" ) end)
- assert_error( function() assert_string( false, "A message" ) end)
- assert_error( function() assert_string( a_number, "A message" ) end)
- assert_error( function() assert_string( a_table, "A message" ) end)
- assert_error( function() assert_string( a_function, "A message" ) end)
- assert_error( function() assert_string( a_thread, "A message" ) end)
-end
-
-function test_assert_table()
- assert_table( a_table )
- assert_table( a_table, "A message" )
-
- assert_error( function() assert_table( nil ) end)
- assert_error( function() assert_table( true ) end)
- assert_error( function() assert_table( false ) end)
- assert_error( function() assert_table( a_number ) end)
- assert_error( function() assert_table( a_string ) end)
- assert_error( function() assert_table( a_function ) end)
- assert_error( function() assert_table( a_thread ) end)
-
- assert_error( function() assert_table( nil, "A message" ) end)
- assert_error( function() assert_table( true, "A message" ) end)
- assert_error( function() assert_table( false, "A message" ) end)
- assert_error( function() assert_table( a_number, "A message" ) end)
- assert_error( function() assert_table( a_string, "A message" ) end)
- assert_error( function() assert_table( a_function, "A message" ) end)
- assert_error( function() assert_table( a_thread, "A message" ) end)
-end
-
-function test_assert_function()
- assert_function( a_function )
- assert_function( a_function, "A message" )
-
- assert_error( function() assert_function( nil ) end)
- assert_error( function() assert_function( true ) end)
- assert_error( function() assert_function( false ) end)
- assert_error( function() assert_function( a_number ) end)
- assert_error( function() assert_function( a_string ) end)
- assert_error( function() assert_function( a_table ) end)
- assert_error( function() assert_function( a_thread ) end)
-
- assert_error( function() assert_function( nil, "A message" ) end)
- assert_error( function() assert_function( true, "A message" ) end)
- assert_error( function() assert_function( false, "A message" ) end)
- assert_error( function() assert_function( a_number, "A message" ) end)
- assert_error( function() assert_function( a_string, "A message" ) end)
- assert_error( function() assert_function( a_table, "A message" ) end)
- assert_error( function() assert_function( a_thread, "A message" ) end)
-end
-
-function test_assert_thread()
- assert_thread( a_thread )
- assert_thread( a_thread, "A message" )
-
- assert_error( function() assert_thread( nil ) end)
- assert_error( function() assert_thread( true ) end)
- assert_error( function() assert_thread( false ) end)
- assert_error( function() assert_thread( a_number ) end)
- assert_error( function() assert_thread( a_string ) end)
- assert_error( function() assert_thread( a_table ) end)
- assert_error( function() assert_thread( a_function ) end)
-
- assert_error( function() assert_thread( nil, "A message" ) end)
- assert_error( function() assert_thread( true, "A message" ) end)
- assert_error( function() assert_thread( false, "A message" ) end)
- assert_error( function() assert_thread( a_number, "A message" ) end)
- assert_error( function() assert_thread( a_string, "A message" ) end)
- assert_error( function() assert_thread( a_table, "A message" ) end)
- assert_error( function() assert_thread( a_function, "A message" ) end)
-end
-
-
-
-module( "lunit-tests.match", lunit.testcase )
-
-function test_assert_match()
- assert_pass("assert_match(\"^Hello\", \"Hello World\") doesn't work!", function()
- local a_string = assert_match("^Hello", "Hello World")
- assert_equal("Hello World", a_string)
- end)
-
- assert_pass("assert_match(\"^Hello\", \"Hello World\", \"A Message\") doesn't work!", function()
- local a_string = assert_match("^Hello", "Hello World", "A message")
- assert_equal("Hello World", a_string)
- end)
-
- assert_pass("assert_match(\"World$\", \"Hello World\") doesn't work!", function()
- local a_string = assert_match("World$", "Hello World")
- assert_equal("Hello World", a_string)
- end)
-
- assert_pass("assert_match(\"World$\", \"Hello World\", \"A Message\") doesn't work!", function()
- local a_string = assert_match("World$", "Hello World", "A message")
- assert_equal("Hello World", a_string)
- end)
-
- assert_error("assert_match(\"Hello$\", \"Hello World\") doesn't fail!", function()
- assert_match("Hello$", "Hello World")
- end)
-
- assert_error("assert_match(\"Hello$\", \"Hello World\", \"A Message\") doesn't fail!", function()
- assert_match("Hello$", "Hello World", "A message")
- end)
-
- assert_error("assert_match(\"^World\", \"Hello World\") doesn't fail!", function()
- assert_match("^World", "Hello World")
- end)
-
- assert_error("assert_match(\"^World\", \"Hello World\", \"A Message\") doesn't fail!", function()
- assert_match("^World", "Hello World", "A message")
- end)
-
- assert_error("assert_match(nil, \"Hello World\") doesn't fail!", function()
- assert_match(nil, "Hello World")
- end)
-
- assert_error("assert_match(nil, \"Hello World\", \"A Message\") doesn't fail!", function()
- assert_match(nil, "Hello World", "A message")
- end)
-
- assert_error("assert_match(\"^World\", nil) doesn't fail!", function()
- assert_match("^World", nil)
- end)
-
- assert_error("assert_match(\"^World\", nil, \"A Message\") doesn't fail!", function()
- assert_match("^World", nil, "A message")
- end)
-end
-
-function test_assert_not_match()
- assert_pass("assert_not_match(\"Hello$\", \"Hello World\") doesn't work!", function()
- local a_string = assert_not_match("Hello$", "Hello World")
- assert_equal("Hello World", a_string)
- end)
-
- assert_pass("assert_not_match(\"Hello$\", \"Hello World\", \"A Message\") doesn't work!", function()
- local a_string = assert_not_match("Hello$", "Hello World", "A message")
- assert_equal("Hello World", a_string)
- end)
-
- assert_pass("assert_not_match(\"^World\", \"Hello World\") doesn't work!", function()
- local a_string = assert_not_match("^World", "Hello World")
- assert_equal("Hello World", a_string)
- end)
-
- assert_pass("assert_not_match(\"^World\", \"Hello World\", \"A Message\") doesn't work!", function()
- local a_string = assert_not_match("^World", "Hello World", "A message")
- assert_equal("Hello World", a_string)
- end)
-
- assert_error("assert_not_match(\"^Hello\", \"Hello World\") doesn't fail!", function()
- assert_not_match("^Hello", "Hello World")
- end)
-
- assert_error("assert_not_match(\"^Hello\", \"Hello World\", \"A Message\") doesn't fail!", function()
- assert_not_match("^Hello", "Hello World", "A message")
- end)
-
- assert_error("assert_not_match(\"World$\", \"Hello World\") doesn't fail!", function()
- assert_not_match("World$", "Hello World")
- end)
-
- assert_error("assert_not_match(\"World$\", \"Hello World\", \"A Message\") doesn't fail!", function()
- assert_not_match("World$", "Hello World", "A message")
- end)
-
- assert_error("assert_not_match(nil, \"Hello World\") doesn't fail!", function()
- assert_not_match(nil, "Hello World")
- end)
-
- assert_error("assert_not_match(nil, \"Hello World\", \"A Message\") doesn't fail!", function()
- assert_not_match(nil, "Hello World", "A message")
- end)
-
- assert_error("assert_not_match(\"^World\", nil) doesn't fail!", function()
- assert_not_match("^World", nil)
- end)
-
- assert_error("assert_not_match(\"^World\", nil, \"A Message\") doesn't fail!", function()
- assert_not_match("^World", nil, "A message")
- end)
-end
-
-function test_assert_error_match()
- local ok, errobj, usrmsg
-
- local function errfunc()
- error("My Error!")
- end
-
- local errpattern = "Error!$"
- local wrongpattern = "^_foobar_$"
-
- local function goodfunc()
- -- NOP
- end
-
- ok = pcall(function() assert_error_match(errpattern, errfunc) end)
- assert_true(ok, "assert_error_match( , )")
-
- ok = pcall(function() assert_error_match("A message", errpattern, errfunc) end)
- assert_true(ok, "assert_error_match(\"A message\", , )")
-
- usrmsg = "assert_error_match( , )"
- ok, errobj = pcall(function() assert_error_match(wrongpattern, errfunc) end)
- assert_false(ok, usrmsg)
- assert_table(errobj, usrmsg)
- assert_match("expected error '.+: My Error!' to match pattern '"..wrongpattern.."' but doesn't$", errobj.msg, usrmsg)
-
- usrmsg = "assert_error_match(\"A message\", , )"
- ok, errobj = pcall(function() assert_error_match("A message", wrongpattern, errfunc) end)
- assert_false(ok, usrmsg)
- assert_table(errobj, usrmsg)
- assert_match("expected error '.+: My Error!' to match pattern '"..wrongpattern.."' but doesn't$", errobj.msg, usrmsg)
-
- usrmsg = "assert_error_match( , )"
- ok, errobj = pcall(function() assert_error_match(errpattern, goodfunc) end)
- assert_false(ok, usrmsg)
- assert_table(errobj, usrmsg)
- assert_match("error expected but no error occurred$", errobj.msg, usrmsg)
-
- usrmsg = "assert_error_match(\"A message\", , )"
- ok, errobj = pcall(function() assert_error_match("A Message", errpattern, goodfunc) end)
- assert_false(ok, usrmsg)
- assert_table(errobj, usrmsg)
- assert_match("error expected but no error occurred$", errobj.msg, usrmsg)
-end
-
-
-
-module( "lunit-tests.setup-teardown", lunit.testcase )
-
-local setup_called = 0
-local teardown_called = 0
-local helper_called = 0
-
-function setup()
- setup_called = setup_called + 1
-end
-
-function Teardown()
- teardown_called = teardown_called + 1
-end
-
-local function helper()
- helper_called = helper_called + 1
- assert(setup_called == helper_called, "setup() not called")
- assert(teardown_called == helper_called - 1, "teardown() not called")
-end
-
-function test1()
- helper()
-end
-
-function test2()
- helper()
-end
-
-function test3()
- helper()
-end
diff --git a/src/external/lunit/lunit.lua b/src/external/lunit/lunit.lua
deleted file mode 100644
index 52d45880a..000000000
--- a/src/external/lunit/lunit.lua
+++ /dev/null
@@ -1,670 +0,0 @@
-
---[[--------------------------------------------------------------------------
-
- This file is part of lunit 0.5.
-
- For Details about lunit look at: http://www.mroth.net/lunit/
-
- Author: Michael Roth
-
- Copyright (c) 2004, 2006-2009 Michael Roth
-
- 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.
-
---]]--------------------------------------------------------------------------
-
-
-
-
-local orig_assert = assert
-
-local pairs = pairs
-local ipairs = ipairs
-local next = next
-local type = type
-local error = error
-local tostring = tostring
-
-local string_sub = string.sub
-local string_format = string.format
-
-
-module("lunit", package.seeall) -- FIXME: Remove package.seeall
-
-local lunit = _M
-
-local __failure__ = {} -- Type tag for failed assertions
-
-local typenames = { "nil", "boolean", "number", "string", "table", "function", "thread", "userdata" }
-
-
-
-local traceback_hide -- Traceback function which hides lunit internals
-local mypcall -- Protected call to a function with own traceback
-do
- local _tb_hide = setmetatable( {}, {__mode="k"} )
-
- function traceback_hide(func)
- _tb_hide[func] = true
- end
-
- local function my_traceback(errobj)
- if is_table(errobj) and errobj.type == __failure__ then
- local info = debug.getinfo(5, "Sl") -- FIXME: Hardcoded integers are bad...
- errobj.where = string_format( "%s:%d", info.short_src, info.currentline)
- else
- errobj = { msg = tostring(errobj) }
- errobj.tb = {}
- local i = 2
- while true do
- local info = debug.getinfo(i, "Snlf")
- if not is_table(info) then
- break
- end
- if not _tb_hide[info.func] then
- local line = {} -- Ripped from ldblib.c...
- line[#line+1] = string_format("%s:", info.short_src)
- if info.currentline > 0 then
- line[#line+1] = string_format("%d:", info.currentline)
- end
- if info.namewhat ~= "" then
- line[#line+1] = string_format(" in function '%s'", info.name)
- else
- if info.what == "main" then
- line[#line+1] = " in main chunk"
- elseif info.what == "C" or info.what == "tail" then
- line[#line+1] = " ?"
- else
- line[#line+1] = string_format(" in function <%s:%d>", info.short_src, info.linedefined)
- end
- end
- errobj.tb[#errobj.tb+1] = table.concat(line)
- end
- i = i + 1
- end
- end
- return errobj
- end
-
- function mypcall(func)
- orig_assert( is_function(func) )
- local ok, errobj = xpcall(func, my_traceback)
- if not ok then
- return errobj
- end
- end
- traceback_hide(mypcall)
-end
-
-
--- Type check functions
-
-for _, typename in ipairs(typenames) do
- lunit["is_"..typename] = function(x)
- return type(x) == typename
- end
-end
-
-local is_nil = is_nil
-local is_boolean = is_boolean
-local is_number = is_number
-local is_string = is_string
-local is_table = is_table
-local is_function = is_function
-local is_thread = is_thread
-local is_userdata = is_userdata
-
-
-local function failure(name, usermsg, defaultmsg, ...)
- local errobj = {
- type = __failure__,
- name = name,
- msg = string_format(defaultmsg,...),
- usermsg = usermsg
- }
- error(errobj, 0)
-end
-traceback_hide( failure )
-
-
-local function format_arg(arg)
- local argtype = type(arg)
- if argtype == "string" then
- return "'"..arg.."'"
- elseif argtype == "number" or argtype == "boolean" or argtype == "nil" then
- return tostring(arg)
- else
- return "["..tostring(arg).."]"
- end
-end
-
-
-function fail(msg)
- stats.assertions = stats.assertions + 1
- failure( "fail", msg, "failure" )
-end
-traceback_hide( fail )
-
-
-function assert(assertion, msg)
- stats.assertions = stats.assertions + 1
- if not assertion then
- failure( "assert", msg, "assertion failed" )
- end
- return assertion
-end
-traceback_hide( assert )
-
-
-function assert_true(actual, msg)
- stats.assertions = stats.assertions + 1
- local actualtype = type(actual)
- if actualtype ~= "boolean" then
- failure( "assert_true", msg, "true expected but was a "..actualtype )
- end
- if actual ~= true then
- failure( "assert_true", msg, "true expected but was false" )
- end
- return actual
-end
-traceback_hide( assert_true )
-
-
-function assert_false(actual, msg)
- stats.assertions = stats.assertions + 1
- local actualtype = type(actual)
- if actualtype ~= "boolean" then
- failure( "assert_false", msg, "false expected but was a "..actualtype )
- end
- if actual ~= false then
- failure( "assert_false", msg, "false expected but was true" )
- end
- return actual
-end
-traceback_hide( assert_false )
-
-
-function assert_equal(expected, actual, msg)
- stats.assertions = stats.assertions + 1
- if expected ~= actual then
- failure( "assert_equal", msg, "expected %s but was %s", format_arg(expected), format_arg(actual) )
- end
- return actual
-end
-traceback_hide( assert_equal )
-
-
-function assert_not_equal(unexpected, actual, msg)
- stats.assertions = stats.assertions + 1
- if unexpected == actual then
- failure( "assert_not_equal", msg, "%s not expected but was one", format_arg(unexpected) )
- end
- return actual
-end
-traceback_hide( assert_not_equal )
-
-
-function assert_match(pattern, actual, msg)
- stats.assertions = stats.assertions + 1
- local patterntype = type(pattern)
- if patterntype ~= "string" then
- failure( "assert_match", msg, "expected the pattern as a string but was a "..patterntype )
- end
- local actualtype = type(actual)
- if actualtype ~= "string" then
- failure( "assert_match", msg, "expected a string to match pattern '%s' but was a %s", pattern, actualtype )
- end
- if not string.find(actual, pattern) then
- failure( "assert_match", msg, "expected '%s' to match pattern '%s' but doesn't", actual, pattern )
- end
- return actual
-end
-traceback_hide( assert_match )
-
-
-function assert_not_match(pattern, actual, msg)
- stats.assertions = stats.assertions + 1
- local patterntype = type(pattern)
- if patterntype ~= "string" then
- failure( "assert_not_match", msg, "expected the pattern as a string but was a "..patterntype )
- end
- local actualtype = type(actual)
- if actualtype ~= "string" then
- failure( "assert_not_match", msg, "expected a string to not match pattern '%s' but was a %s", pattern, actualtype )
- end
- if string.find(actual, pattern) then
- failure( "assert_not_match", msg, "expected '%s' to not match pattern '%s' but it does", actual, pattern )
- end
- return actual
-end
-traceback_hide( assert_not_match )
-
-
-function assert_error(msg, func)
- stats.assertions = stats.assertions + 1
- if func == nil then
- func, msg = msg, nil
- end
- local functype = type(func)
- if functype ~= "function" then
- failure( "assert_error", msg, "expected a function as last argument but was a "..functype )
- end
- local ok, errmsg = pcall(func)
- if ok then
- failure( "assert_error", msg, "error expected but no error occurred" )
- end
-end
-traceback_hide( assert_error )
-
-
-function assert_error_match(msg, pattern, func)
- stats.assertions = stats.assertions + 1
- if func == nil then
- msg, pattern, func = nil, msg, pattern
- end
- local patterntype = type(pattern)
- if patterntype ~= "string" then
- failure( "assert_error_match", msg, "expected the pattern as a string but was a "..patterntype )
- end
- local functype = type(func)
- if functype ~= "function" then
- failure( "assert_error_match", msg, "expected a function as last argument but was a "..functype )
- end
- local ok, errmsg = pcall(func)
- if ok then
- failure( "assert_error_match", msg, "error expected but no error occurred" )
- end
- local errmsgtype = type(errmsg)
- if errmsgtype ~= "string" then
- failure( "assert_error_match", msg, "error as string expected but was a "..errmsgtype )
- end
- if not string.find(errmsg, pattern) then
- failure( "assert_error_match", msg, "expected error '%s' to match pattern '%s' but doesn't", errmsg, pattern )
- end
-end
-traceback_hide( assert_error_match )
-
-
-function assert_pass(msg, func)
- stats.assertions = stats.assertions + 1
- if func == nil then
- func, msg = msg, nil
- end
- local functype = type(func)
- if functype ~= "function" then
- failure( "assert_pass", msg, "expected a function as last argument but was a %s", functype )
- end
- local ok, errmsg = pcall(func)
- if not ok then
- failure( "assert_pass", msg, "no error expected but error was: '%s'", errmsg )
- end
-end
-traceback_hide( assert_pass )
-
-
--- lunit.assert_typename functions
-
-for _, typename in ipairs(typenames) do
- local assert_typename = "assert_"..typename
- lunit[assert_typename] = function(actual, msg)
- stats.assertions = stats.assertions + 1
- local actualtype = type(actual)
- if actualtype ~= typename then
- failure( assert_typename, msg, typename.." expected but was a "..actualtype )
- end
- return actual
- end
- traceback_hide( lunit[assert_typename] )
-end
-
-
--- lunit.assert_not_typename functions
-
-for _, typename in ipairs(typenames) do
- local assert_not_typename = "assert_not_"..typename
- lunit[assert_not_typename] = function(actual, msg)
- stats.assertions = stats.assertions + 1
- if type(actual) == typename then
- failure( assert_not_typename, msg, typename.." not expected but was one" )
- end
- end
- traceback_hide( lunit[assert_not_typename] )
-end
-
-
-function lunit.clearstats()
- stats = {
- assertions = 0;
- passed = 0;
- failed = 0;
- errors = 0;
- }
-end
-
-
-local report, reporterrobj
-do
- local testrunner
-
- function lunit.setrunner(newrunner)
- if not ( is_table(newrunner) or is_nil(newrunner) ) then
- return error("lunit.setrunner: Invalid argument", 0)
- end
- local oldrunner = testrunner
- testrunner = newrunner
- return oldrunner
- end
-
- function lunit.loadrunner(name)
- if not is_string(name) then
- return error("lunit.loadrunner: Invalid argument", 0)
- end
- local ok, runner = pcall( require, name )
- if not ok then
- return error("lunit.loadrunner: Can't load test runner: "..runner, 0)
- end
- return setrunner(runner)
- end
-
- function report(event, ...)
- local f = testrunner and testrunner[event]
- if is_function(f) then
- pcall(f, ...)
- end
- end
-
- function reporterrobj(context, tcname, testname, errobj)
- local fullname = tcname .. "." .. testname
- if context == "setup" then
- fullname = fullname .. ":" .. setupname(tcname, testname)
- elseif context == "teardown" then
- fullname = fullname .. ":" .. teardownname(tcname, testname)
- end
- if errobj.type == __failure__ then
- stats.failed = stats.failed + 1
- report("fail", fullname, errobj.where, errobj.msg, errobj.usermsg)
- else
- stats.errors = stats.errors + 1
- report("err", fullname, errobj.msg, errobj.tb)
- end
- end
-end
-
-
-
-local function key_iter(t, k)
- return (next(t,k))
-end
-
-
-local testcase
-do
- -- Array with all registered testcases
- local _testcases = {}
-
- -- Marks a module as a testcase.
- -- Applied over a module from module("xyz", lunit.testcase).
- function lunit.testcase(m)
- orig_assert( is_table(m) )
- --orig_assert( m._M == m )
- orig_assert( is_string(m._NAME) )
- --orig_assert( is_string(m._PACKAGE) )
-
- -- Register the module as a testcase
- _testcases[m._NAME] = m
-
- -- Import lunit, fail, assert* and is_* function to the module/testcase
- m.lunit = lunit
- m.fail = lunit.fail
- for funcname, func in pairs(lunit) do
- if "assert" == string_sub(funcname, 1, 6) or "is_" == string_sub(funcname, 1, 3) then
- m[funcname] = func
- end
- end
- end
-
- -- Iterator (testcasename) over all Testcases
- function lunit.testcases()
- -- Make a copy of testcases to prevent confusing the iterator when
- -- new testcase are defined
- local _testcases2 = {}
- for k,v in pairs(_testcases) do
- _testcases2[k] = true
- end
- return key_iter, _testcases2, nil
- end
-
- function testcase(tcname)
- return _testcases[tcname]
- end
-end
-
-
-do
- -- Finds a function in a testcase case insensitive
- local function findfuncname(tcname, name)
- for key, value in pairs(testcase(tcname)) do
- if is_string(key) and is_function(value) and string.lower(key) == name then
- return key
- end
- end
- end
-
- function lunit.setupname(tcname)
- return findfuncname(tcname, "setup")
- end
-
- function lunit.teardownname(tcname)
- return findfuncname(tcname, "teardown")
- end
-
- -- Iterator over all test names in a testcase.
- -- Have to collect the names first in case one of the test
- -- functions creates a new global and throws off the iteration.
- function lunit.tests(tcname)
- local testnames = {}
- for key, value in pairs(testcase(tcname)) do
- if is_string(key) and is_function(value) then
- local lfn = string.lower(key)
- if string.sub(lfn, 1, 4) == "test" or string.sub(lfn, -4) == "test" then
- testnames[key] = true
- end
- end
- end
- return key_iter, testnames, nil
- end
-end
-
-
-
-
-function lunit.runtest(tcname, testname)
- orig_assert( is_string(tcname) )
- orig_assert( is_string(testname) )
-
- local function callit(context, func)
- if func then
- local err = mypcall(func)
- if err then
- reporterrobj(context, tcname, testname, err)
- return false
- end
- end
- return true
- end
- traceback_hide(callit)
-
- report("run", tcname, testname)
-
- local tc = testcase(tcname)
- local setup = tc[setupname(tcname)]
- local test = tc[testname]
- local teardown = tc[teardownname(tcname)]
-
- local setup_ok = callit( "setup", setup )
- local test_ok = setup_ok and callit( "test", test )
- local teardown_ok = setup_ok and callit( "teardown", teardown )
-
- if setup_ok and test_ok and teardown_ok then
- stats.passed = stats.passed + 1
- report("pass", tcname, testname)
- end
-end
-traceback_hide(runtest)
-
-
-
-function lunit.run()
- clearstats()
- report("begin")
- for testcasename in lunit.testcases() do
- -- Run tests in the testcases
- for testname in lunit.tests(testcasename) do
- runtest(testcasename, testname)
- end
- end
- report("done")
- return stats
-end
-traceback_hide(run)
-
-
-function lunit.loadonly()
- clearstats()
- report("begin")
- report("done")
- return stats
-end
-
-
-
-
-
-
-
-
-
-local lunitpat2luapat
-do
- local conv = {
- ["^"] = "%^",
- ["$"] = "%$",
- ["("] = "%(",
- [")"] = "%)",
- ["%"] = "%%",
- ["."] = "%.",
- ["["] = "%[",
- ["]"] = "%]",
- ["+"] = "%+",
- ["-"] = "%-",
- ["?"] = ".",
- ["*"] = ".*"
- }
- function lunitpat2luapat(str)
- return "^" .. string.gsub(str, "%W", conv) .. "$"
- end
-end
-
-
-
-local function in_patternmap(map, name)
- if map[name] == true then
- return true
- else
- for _, pat in ipairs(map) do
- if string.find(name, pat) then
- return true
- end
- end
- end
- return false
-end
-
-
-
-
-
-
-
-
--- Called from 'lunit' shell script.
-
-function main(argv)
- argv = argv or {}
-
- -- FIXME: Error handling and error messages aren't nice.
-
- local function checkarg(optname, arg)
- if not is_string(arg) then
- return error("lunit.main: option "..optname..": argument missing.", 0)
- end
- end
-
- local function loadtestcase(filename)
- if not is_string(filename) then
- return error("lunit.main: invalid argument")
- end
- local chunk, err = loadfile(filename)
- if err then
- return error(err)
- else
- chunk()
- end
- end
-
- local testpatterns = nil
- local doloadonly = false
- local runner = nil
-
- local i = 0
- while i < #argv do
- i = i + 1
- local arg = argv[i]
- if arg == "--loadonly" then
- doloadonly = true
- elseif arg == "--runner" or arg == "-r" then
- local optname = arg; i = i + 1; arg = argv[i]
- checkarg(optname, arg)
- runner = arg
- elseif arg == "--test" or arg == "-t" then
- local optname = arg; i = i + 1; arg = argv[i]
- checkarg(optname, arg)
- testpatterns = testpatterns or {}
- testpatterns[#testpatterns+1] = arg
- elseif arg == "--" then
- while i < #argv do
- i = i + 1; arg = argv[i]
- loadtestcase(arg)
- end
- else
- loadtestcase(arg)
- end
- end
-
- loadrunner(runner or "lunit-console")
-
- if doloadonly then
- return loadonly()
- else
- return run(testpatterns)
- end
-end
-
-clearstats()
diff --git a/src/external/md5.c b/src/external/md5.c
deleted file mode 100644
index c35d96c5e..000000000
--- a/src/external/md5.c
+++ /dev/null
@@ -1,381 +0,0 @@
-/*
- Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved.
-
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any damages
- arising from the use of this software.
-
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not
- claim that you wrote the original software. If you use this software
- in a product, an acknowledgment in the product documentation would be
- appreciated but is not required.
- 2. Altered source versions must be plainly marked as such, and must not be
- misrepresented as being the original software.
- 3. This notice may not be removed or altered from any source distribution.
-
- L. Peter Deutsch
- ghost@aladdin.com
-
- */
-/* $Id: md5.c,v 1.6 2002/04/13 19:20:28 lpd Exp $ */
-/*
- Independent implementation of MD5 (RFC 1321).
-
- This code implements the MD5 Algorithm defined in RFC 1321, whose
- text is available at
- http://www.ietf.org/rfc/rfc1321.txt
- The code is derived from the text of the RFC, including the test suite
- (section A.5) but excluding the rest of Appendix A. It does not include
- any code or documentation that is identified in the RFC as being
- copyrighted.
-
- The original and principal author of md5.c is L. Peter Deutsch
- . Other authors are noted in the change history
- that follows (in reverse chronological order):
-
- 2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order
- either statically or dynamically; added missing #include
- in library.
- 2002-03-11 lpd Corrected argument list for main(), and added int return
- type, in test program and T value program.
- 2002-02-21 lpd Added missing #include in test program.
- 2000-07-03 lpd Patched to eliminate warnings about "constant is
- unsigned in ANSI C, signed in traditional"; made test program
- self-checking.
- 1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
- 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
- 1999-05-03 lpd Original version.
- */
-
-#include "md5.h"
-#include
-
-#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
-#ifdef ARCH_IS_BIG_ENDIAN
-# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
-#else
-# define BYTE_ORDER 0
-#endif
-
-#define T_MASK ((md5_word_t)~0)
-#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
-#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
-#define T3 0x242070db
-#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
-#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
-#define T6 0x4787c62a
-#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
-#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
-#define T9 0x698098d8
-#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
-#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
-#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
-#define T13 0x6b901122
-#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
-#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
-#define T16 0x49b40821
-#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
-#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
-#define T19 0x265e5a51
-#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
-#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
-#define T22 0x02441453
-#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
-#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
-#define T25 0x21e1cde6
-#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
-#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
-#define T28 0x455a14ed
-#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
-#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
-#define T31 0x676f02d9
-#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
-#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
-#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
-#define T35 0x6d9d6122
-#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
-#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
-#define T38 0x4bdecfa9
-#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
-#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
-#define T41 0x289b7ec6
-#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
-#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
-#define T44 0x04881d05
-#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
-#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
-#define T47 0x1fa27cf8
-#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
-#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
-#define T50 0x432aff97
-#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
-#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
-#define T53 0x655b59c3
-#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
-#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
-#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
-#define T57 0x6fa87e4f
-#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
-#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
-#define T60 0x4e0811a1
-#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
-#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
-#define T63 0x2ad7d2bb
-#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
-
-
-static void
-md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
-{
- md5_word_t
- a = pms->abcd[0], b = pms->abcd[1],
- c = pms->abcd[2], d = pms->abcd[3];
- md5_word_t t;
-#if BYTE_ORDER > 0
- /* Define storage only for big-endian CPUs. */
- md5_word_t X[16];
-#else
- /* Define storage for little-endian or both types of CPUs. */
- md5_word_t xbuf[16];
- const md5_word_t *X;
-#endif
-
- {
-#if BYTE_ORDER == 0
- /*
- * Determine dynamically whether this is a big-endian or
- * little-endian machine, since we can use a more efficient
- * algorithm on the latter.
- */
- static const int w = 1;
-
- if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
-#endif
-#if BYTE_ORDER <= 0 /* little-endian */
- {
- /*
- * On little-endian machines, we can process properly aligned
- * data without copying it.
- */
- if (!((data - (const md5_byte_t *)0) & 3)) {
- /* data are properly aligned */
- X = (const md5_word_t *)data;
- } else {
- /* not aligned */
- memcpy(xbuf, data, 64);
- X = xbuf;
- }
- }
-#endif
-#if BYTE_ORDER == 0
- else /* dynamic big-endian */
-#endif
-#if BYTE_ORDER >= 0 /* big-endian */
- {
- /*
- * On big-endian machines, we must arrange the bytes in the
- * right order.
- */
- const md5_byte_t *xp = data;
- int i;
-
-# if BYTE_ORDER == 0
- X = xbuf; /* (dynamic only) */
-# else
-# define xbuf X /* (static only) */
-# endif
- for (i = 0; i < 16; ++i, xp += 4)
- xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
- }
-#endif
- }
-
-#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
-
- /* Round 1. */
- /* Let [abcd k s i] denote the operation
- a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
-#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
-#define SET(a, b, c, d, k, s, Ti)\
- t = a + F(b,c,d) + X[k] + Ti;\
- a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
- SET(a, b, c, d, 0, 7, T1);
- SET(d, a, b, c, 1, 12, T2);
- SET(c, d, a, b, 2, 17, T3);
- SET(b, c, d, a, 3, 22, T4);
- SET(a, b, c, d, 4, 7, T5);
- SET(d, a, b, c, 5, 12, T6);
- SET(c, d, a, b, 6, 17, T7);
- SET(b, c, d, a, 7, 22, T8);
- SET(a, b, c, d, 8, 7, T9);
- SET(d, a, b, c, 9, 12, T10);
- SET(c, d, a, b, 10, 17, T11);
- SET(b, c, d, a, 11, 22, T12);
- SET(a, b, c, d, 12, 7, T13);
- SET(d, a, b, c, 13, 12, T14);
- SET(c, d, a, b, 14, 17, T15);
- SET(b, c, d, a, 15, 22, T16);
-#undef SET
-
- /* Round 2. */
- /* Let [abcd k s i] denote the operation
- a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
-#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
-#define SET(a, b, c, d, k, s, Ti)\
- t = a + G(b,c,d) + X[k] + Ti;\
- a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
- SET(a, b, c, d, 1, 5, T17);
- SET(d, a, b, c, 6, 9, T18);
- SET(c, d, a, b, 11, 14, T19);
- SET(b, c, d, a, 0, 20, T20);
- SET(a, b, c, d, 5, 5, T21);
- SET(d, a, b, c, 10, 9, T22);
- SET(c, d, a, b, 15, 14, T23);
- SET(b, c, d, a, 4, 20, T24);
- SET(a, b, c, d, 9, 5, T25);
- SET(d, a, b, c, 14, 9, T26);
- SET(c, d, a, b, 3, 14, T27);
- SET(b, c, d, a, 8, 20, T28);
- SET(a, b, c, d, 13, 5, T29);
- SET(d, a, b, c, 2, 9, T30);
- SET(c, d, a, b, 7, 14, T31);
- SET(b, c, d, a, 12, 20, T32);
-#undef SET
-
- /* Round 3. */
- /* Let [abcd k s t] denote the operation
- a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
-#define H(x, y, z) ((x) ^ (y) ^ (z))
-#define SET(a, b, c, d, k, s, Ti)\
- t = a + H(b,c,d) + X[k] + Ti;\
- a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
- SET(a, b, c, d, 5, 4, T33);
- SET(d, a, b, c, 8, 11, T34);
- SET(c, d, a, b, 11, 16, T35);
- SET(b, c, d, a, 14, 23, T36);
- SET(a, b, c, d, 1, 4, T37);
- SET(d, a, b, c, 4, 11, T38);
- SET(c, d, a, b, 7, 16, T39);
- SET(b, c, d, a, 10, 23, T40);
- SET(a, b, c, d, 13, 4, T41);
- SET(d, a, b, c, 0, 11, T42);
- SET(c, d, a, b, 3, 16, T43);
- SET(b, c, d, a, 6, 23, T44);
- SET(a, b, c, d, 9, 4, T45);
- SET(d, a, b, c, 12, 11, T46);
- SET(c, d, a, b, 15, 16, T47);
- SET(b, c, d, a, 2, 23, T48);
-#undef SET
-
- /* Round 4. */
- /* Let [abcd k s t] denote the operation
- a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
-#define I(x, y, z) ((y) ^ ((x) | ~(z)))
-#define SET(a, b, c, d, k, s, Ti)\
- t = a + I(b,c,d) + X[k] + Ti;\
- a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
- SET(a, b, c, d, 0, 6, T49);
- SET(d, a, b, c, 7, 10, T50);
- SET(c, d, a, b, 14, 15, T51);
- SET(b, c, d, a, 5, 21, T52);
- SET(a, b, c, d, 12, 6, T53);
- SET(d, a, b, c, 3, 10, T54);
- SET(c, d, a, b, 10, 15, T55);
- SET(b, c, d, a, 1, 21, T56);
- SET(a, b, c, d, 8, 6, T57);
- SET(d, a, b, c, 15, 10, T58);
- SET(c, d, a, b, 6, 15, T59);
- SET(b, c, d, a, 13, 21, T60);
- SET(a, b, c, d, 4, 6, T61);
- SET(d, a, b, c, 11, 10, T62);
- SET(c, d, a, b, 2, 15, T63);
- SET(b, c, d, a, 9, 21, T64);
-#undef SET
-
- /* Then perform the following additions. (That is increment each
- of the four registers by the value it had before this block
- was started.) */
- pms->abcd[0] += a;
- pms->abcd[1] += b;
- pms->abcd[2] += c;
- pms->abcd[3] += d;
-}
-
-void
-md5_init(md5_state_t *pms)
-{
- pms->count[0] = pms->count[1] = 0;
- pms->abcd[0] = 0x67452301;
- pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
- pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
- pms->abcd[3] = 0x10325476;
-}
-
-void
-md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes)
-{
- const md5_byte_t *p = data;
- int left = nbytes;
- int offset = (pms->count[0] >> 3) & 63;
- md5_word_t nbits = (md5_word_t)(nbytes << 3);
-
- if (nbytes <= 0)
- return;
-
- /* Update the message length. */
- pms->count[1] += nbytes >> 29;
- pms->count[0] += nbits;
- if (pms->count[0] < nbits)
- pms->count[1]++;
-
- /* Process an initial partial block. */
- if (offset) {
- int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
-
- memcpy(pms->buf + offset, p, copy);
- if (offset + copy < 64)
- return;
- p += copy;
- left -= copy;
- md5_process(pms, pms->buf);
- }
-
- /* Process full blocks. */
- for (; left >= 64; p += 64, left -= 64)
- md5_process(pms, p);
-
- /* Process a final partial block. */
- if (left)
- memcpy(pms->buf, p, left);
-}
-
-void
-md5_finish(md5_state_t *pms, md5_byte_t digest[16])
-{
- static const md5_byte_t pad[64] = {
- 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
- };
- md5_byte_t data[8];
- int i;
-
- /* Save the length before padding. */
- for (i = 0; i < 8; ++i)
- data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
- /* Pad to 56 bytes mod 64. */
- md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
- /* Append the length. */
- md5_append(pms, data, 8);
- for (i = 0; i < 16; ++i)
- digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
-}
diff --git a/src/external/md5.h b/src/external/md5.h
deleted file mode 100644
index 698c995d8..000000000
--- a/src/external/md5.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- Copyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved.
-
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any damages
- arising from the use of this software.
-
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not
- claim that you wrote the original software. If you use this software
- in a product, an acknowledgment in the product documentation would be
- appreciated but is not required.
- 2. Altered source versions must be plainly marked as such, and must not be
- misrepresented as being the original software.
- 3. This notice may not be removed or altered from any source distribution.
-
- L. Peter Deutsch
- ghost@aladdin.com
-
- */
-/* $Id: md5.h,v 1.4 2002/04/13 19:20:28 lpd Exp $ */
-/*
- Independent implementation of MD5 (RFC 1321).
-
- This code implements the MD5 Algorithm defined in RFC 1321, whose
- text is available at
- http://www.ietf.org/rfc/rfc1321.txt
- The code is derived from the text of the RFC, including the test suite
- (section A.5) but excluding the rest of Appendix A. It does not include
- any code or documentation that is identified in the RFC as being
- copyrighted.
-
- The original and principal author of md5.h is L. Peter Deutsch
- . Other authors are noted in the change history
- that follows (in reverse chronological order):
-
- 2002-04-13 lpd Removed support for non-ANSI compilers; removed
- references to Ghostscript; clarified derivation from RFC 1321;
- now handles byte order either statically or dynamically.
- 1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
- 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
- added conditionalization for C++ compilation from Martin
- Purschke .
- 1999-05-03 lpd Original version.
- */
-
-#ifndef md5_INCLUDED
-# define md5_INCLUDED
-
-/*
- * This package supports both compile-time and run-time determination of CPU
- * byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be
- * compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is
- * defined as non-zero, the code will be compiled to run only on big-endian
- * CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to
- * run on either big- or little-endian CPUs, but will run slightly less
- * efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined.
- */
-
-typedef unsigned char md5_byte_t; /* 8-bit byte */
-typedef unsigned int md5_word_t; /* 32-bit word */
-
-/* Define the state of the MD5 Algorithm. */
-typedef struct md5_state_s {
- md5_word_t count[2]; /* message length in bits, lsw first */
- md5_word_t abcd[4]; /* digest buffer */
- md5_byte_t buf[64]; /* accumulate block */
-} md5_state_t;
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/* Initialize the algorithm. */
-void md5_init(md5_state_t *pms);
-
-/* Append a string to the message. */
-void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes);
-
-/* Finish the message and return the digest. */
-void md5_finish(md5_state_t *pms, md5_byte_t digest[16]);
-
-#ifdef __cplusplus
-} /* end extern "C" */
-#endif
-
-#endif /* md5_INCLUDED */
diff --git a/src/external/md5main.c b/src/external/md5main.c
deleted file mode 100644
index 625a6198e..000000000
--- a/src/external/md5main.c
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- Copyright (C) 2002 Aladdin Enterprises. All rights reserved.
-
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any damages
- arising from the use of this software.
-
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not
- claim that you wrote the original software. If you use this software
- in a product, an acknowledgment in the product documentation would be
- appreciated but is not required.
- 2. Altered source versions must be plainly marked as such, and must not be
- misrepresented as being the original software.
- 3. This notice may not be removed or altered from any source distribution.
-
- L. Peter Deutsch
- ghost@aladdin.com
-
- */
-/* $Id: md5main.c,v 1.1 2002/04/13 19:20:28 lpd Exp $ */
-/*
- Independent implementation of MD5 (RFC 1321).
-
- This code implements the MD5 Algorithm defined in RFC 1321, whose
- text is available at
- http://www.ietf.org/rfc/rfc1321.txt
- The code is derived from the text of the RFC, including the test suite
- (section A.5) but excluding the rest of Appendix A. It does not include
- any code or documentation that is identified in the RFC as being
- copyrighted.
-
- The original and principal author of md5.c is L. Peter Deutsch
- . Other authors are noted in the change history
- that follows (in reverse chronological order):
-
- 2002-04-13 lpd Splits off main program into a separate file, md5main.c.
- */
-
-#include "md5.h"
-#include
-#include
-#include
-
-/*
- * This file builds an executable that performs various functions related
- * to the MD5 library. Typical compilation:
- * gcc -o md5main -lm md5main.c md5.c
- */
-static const char *const usage = "\
-Usage:\n\
- md5main --test # run the self-test (A.5 of RFC 1321)\n\
- md5main --t-values # print the T values for the library\n\
- md5main --version # print the version of the package\n\
-";
-static const char *const version = "2002-04-13";
-
-/* Run the self-test. */
-static int
-do_test(void)
-{
- static const char *const test[7*2] = {
- "", "d41d8cd98f00b204e9800998ecf8427e",
- "a", "0cc175b9c0f1b6a831c399e269772661",
- "abc", "900150983cd24fb0d6963f7d28e17f72",
- "message digest", "f96b697d7cb7938d525a2f31aaf161d0",
- "abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b",
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
- "d174ab98d277d9f5a5611c2c9f419d9f",
- "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "57edf4a22be3c955ac49da2e2107b67a"
- };
- int i;
- int status = 0;
-
- for (i = 0; i < 7*2; i += 2) {
- md5_state_t state;
- md5_byte_t digest[16];
- char hex_output[16*2 + 1];
- int di;
-
- md5_init(&state);
- md5_append(&state, (const md5_byte_t *)test[i], strlen(test[i]));
- md5_finish(&state, digest);
- for (di = 0; di < 16; ++di)
- sprintf(hex_output + di * 2, "%02x", digest[di]);
- if (strcmp(hex_output, test[i + 1])) {
- printf("MD5 (\"%s\") = ", test[i]);
- puts(hex_output);
- printf("**** ERROR, should be: %s\n", test[i + 1]);
- status = 1;
- }
- }
- if (status == 0)
- puts("md5 self-test completed successfully.");
- return status;
-}
-
-/* Print the T values. */
-static int
-do_t_values(void)
-{
- int i;
- for (i = 1; i <= 64; ++i) {
- unsigned long v = (unsigned long)(4294967296.0 * fabs(sin((double)i)));
-
- /*
- * The following nonsense is only to avoid compiler warnings about
- * "integer constant is unsigned in ANSI C, signed with -traditional".
- */
- if (v >> 31) {
- printf("#define T%d /* 0x%08lx */ (T_MASK ^ 0x%08lx)\n", i,
- v, (unsigned long)(unsigned int)(~v));
- } else {
- printf("#define T%d 0x%08lx\n", i, v);
- }
- }
- return 0;
-}
-
-/* Main program */
-int
-main(int argc, char *argv[])
-{
- if (argc == 2) {
- if (!strcmp(argv[1], "--test"))
- return do_test();
- if (!strcmp(argv[1], "--t-values"))
- return do_t_values();
- if (!strcmp(argv[1], "--version")) {
- puts(version);
- return 0;
- }
- }
- puts(usage);
- return 0;
-}
diff --git a/src/external/mt19937ar.c b/src/external/mt19937ar.c
deleted file mode 100644
index 4fbd3f70d..000000000
--- a/src/external/mt19937ar.c
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- A C-program for MT19937, with initialization improved 2002/1/26.
- Coded by Takuji Nishimura and Makoto Matsumoto.
-
- Before using, initialize the state by using init_genrand(seed)
- or init_by_array(init_key, key_length).
-
- Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
- 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. The names of its contributors may not be used to endorse or promote
- products derived from this software without specific prior written
- permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-
- Any feedback is very welcome.
- http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
- email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
-*/
-
-#include
-
-/* Period parameters */
-#define N 624
-#define M 397
-#define MATRIX_A 0x9908b0dfUL /* constant vector a */
-#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
-#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
-
-static unsigned long mt[N]; /* the array for the state vector */
-static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
-
-/* initializes mt[N] with a seed */
-void init_genrand(unsigned long s)
-{
- mt[0]= s & 0xffffffffUL;
- for (mti=1; mti> 30)) + mti);
- /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
- /* In the previous versions, MSBs of the seed affect */
- /* only MSBs of the array mt[]. */
- /* 2002/01/09 modified by Makoto Matsumoto */
- mt[mti] &= 0xffffffffUL;
- /* for >32 bit machines */
- }
-}
-
-/* initialize by an array with array-length */
-/* init_key is the array for initializing keys */
-/* key_length is its length */
-/* slight change for C++, 2004/2/26 */
-void init_by_array(unsigned long init_key[], int key_length)
-{
- int i, j, k;
- init_genrand(19650218UL);
- i=1; j=0;
- k = (N>key_length ? N : key_length);
- for (; k; k--) {
- mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
- + init_key[j] + j; /* non linear */
- mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
- i++; j++;
- if (i>=N) { mt[0] = mt[N-1]; i=1; }
- if (j>=key_length) j=0;
- }
- for (k=N-1; k; k--) {
- mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
- - i; /* non linear */
- mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
- i++;
- if (i>=N) { mt[0] = mt[N-1]; i=1; }
- }
-
- mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
-}
-
-/* generates a random number on [0,0xffffffff]-interval */
-unsigned long genrand_int32(void)
-{
- unsigned long y;
- static unsigned long mag01[2]={0x0UL, MATRIX_A};
- /* mag01[x] = x * MATRIX_A for x=0,1 */
-
- if (mti >= N) { /* generate N words at one time */
- int kk;
-
- if (mti == N+1) /* if init_genrand() has not been called, */
- init_genrand(5489UL); /* a default initial seed is used */
-
- for (kk=0;kk> 1) ^ mag01[y & 0x1UL];
- }
- for (;kk> 1) ^ mag01[y & 0x1UL];
- }
- y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
- mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
-
- mti = 0;
- }
-
- y = mt[mti++];
-
- /* Tempering */
- y ^= (y >> 11);
- y ^= (y << 7) & 0x9d2c5680UL;
- y ^= (y << 15) & 0xefc60000UL;
- y ^= (y >> 18);
-
- return y;
-}
-
-/* generates a random number on [0,0x7fffffff]-interval */
-long genrand_int31(void)
-{
- return (long)(genrand_int32()>>1);
-}
-
-/* generates a random number on [0,1]-real-interval */
-double genrand_real1(void)
-{
- return genrand_int32()*(1.0/4294967295.0);
- /* divided by 2^32-1 */
-}
-
-/* generates a random number on [0,1)-real-interval */
-double genrand_real2(void)
-{
- return genrand_int32()*(1.0/4294967296.0);
- /* divided by 2^32 */
-}
-
-/* generates a random number on (0,1)-real-interval */
-double genrand_real3(void)
-{
- return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0);
- /* divided by 2^32 */
-}
-
-/* generates a random number on [0,1) with 53-bit resolution*/
-double genrand_res53(void)
-{
- unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;
- return(a*67108864.0+b)*(1.0/9007199254740992.0);
-}
-/* These real versions are due to Isaku Wada, 2002/01/09 added */
diff --git a/src/external/sqlite3.c b/src/external/sqlite3.c
deleted file mode 100644
index 3eab0e651..000000000
--- a/src/external/sqlite3.c
+++ /dev/null
@@ -1,110860 +0,0 @@
-/******************************************************************************
-** This file is an amalgamation of many separate C source files from SQLite
-** version 3.6.22. By combining all the individual C code files into this
-** single large file, the entire code can be compiled as a one translation
-** unit. This allows many compilers to do optimizations that would not be
-** possible if the files were compiled separately. Performance improvements
-** of 5% are more are commonly seen when SQLite is compiled as a single
-** translation unit.
-**
-** This file is all you need to compile SQLite. To use SQLite in other
-** programs, you need this file and the "sqlite3.h" header file that defines
-** the programming interface to the SQLite library. (If you do not have
-** the "sqlite3.h" header file at hand, you will find a copy embedded within
-** the text of this file. Search for "Begin file sqlite3.h" to find the start
-** of the embedded sqlite3.h header file.) Additional code files may be needed
-** if you want a wrapper to interface SQLite with your choice of programming
-** language. The code for the "sqlite3" command-line shell is also in a
-** separate file. This file contains only code for the core SQLite library.
-*/
-#define SQLITE_CORE 1
-#define SQLITE_AMALGAMATION 1
-#ifndef SQLITE_PRIVATE
-# define SQLITE_PRIVATE static
-#endif
-#ifndef SQLITE_API
-# define SQLITE_API
-#endif
-/************** Begin file sqliteInt.h ***************************************/
-/*
-** 2001 September 15
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** Internal interface definitions for SQLite.
-**
-*/
-#ifndef _SQLITEINT_H_
-#define _SQLITEINT_H_
-
-/*
-** These #defines should enable >2GB file support on POSIX if the
-** underlying operating system supports it. If the OS lacks
-** large file support, or if the OS is windows, these should be no-ops.
-**
-** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
-** system #includes. Hence, this block of code must be the very first
-** code in all source files.
-**
-** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
-** on the compiler command line. This is necessary if you are compiling
-** on a recent machine (ex: Red Hat 7.2) but you want your code to work
-** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
-** without this option, LFS is enable. But LFS does not exist in the kernel
-** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
-** portability you should omit LFS.
-**
-** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
-*/
-#ifndef SQLITE_DISABLE_LFS
-# define _LARGE_FILE 1
-# ifndef _FILE_OFFSET_BITS
-# define _FILE_OFFSET_BITS 64
-# endif
-# define _LARGEFILE_SOURCE 1
-#endif
-
-/*
-** Include the configuration header output by 'configure' if we're using the
-** autoconf-based build
-*/
-#ifdef _HAVE_SQLITE_CONFIG_H
-#include "platform.h"
-#endif
-
-/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
-/************** Begin file sqliteLimit.h *************************************/
-/*
-** 2007 May 7
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-**
-** This file defines various limits of what SQLite can process.
-*/
-
-/*
-** The maximum length of a TEXT or BLOB in bytes. This also
-** limits the size of a row in a table or index.
-**
-** The hard limit is the ability of a 32-bit signed integer
-** to count the size: 2^31-1 or 2147483647.
-*/
-#ifndef SQLITE_MAX_LENGTH
-# define SQLITE_MAX_LENGTH 1000000000
-#endif
-
-/*
-** This is the maximum number of
-**
-** * Columns in a table
-** * Columns in an index
-** * Columns in a view
-** * Terms in the SET clause of an UPDATE statement
-** * Terms in the result set of a SELECT statement
-** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
-** * Terms in the VALUES clause of an INSERT statement
-**
-** The hard upper limit here is 32676. Most database people will
-** tell you that in a well-normalized database, you usually should
-** not have more than a dozen or so columns in any table. And if
-** that is the case, there is no point in having more than a few
-** dozen values in any of the other situations described above.
-*/
-#ifndef SQLITE_MAX_COLUMN
-# define SQLITE_MAX_COLUMN 2000
-#endif
-
-/*
-** The maximum length of a single SQL statement in bytes.
-**
-** It used to be the case that setting this value to zero would
-** turn the limit off. That is no longer true. It is not possible
-** to turn this limit off.
-*/
-#ifndef SQLITE_MAX_SQL_LENGTH
-# define SQLITE_MAX_SQL_LENGTH 1000000000
-#endif
-
-/*
-** The maximum depth of an expression tree. This is limited to
-** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
-** want to place more severe limits on the complexity of an
-** expression.
-**
-** A value of 0 used to mean that the limit was not enforced.
-** But that is no longer true. The limit is now strictly enforced
-** at all times.
-*/
-#ifndef SQLITE_MAX_EXPR_DEPTH
-# define SQLITE_MAX_EXPR_DEPTH 1000
-#endif
-
-/*
-** The maximum number of terms in a compound SELECT statement.
-** The code generator for compound SELECT statements does one
-** level of recursion for each term. A stack overflow can result
-** if the number of terms is too large. In practice, most SQL
-** never has more than 3 or 4 terms. Use a value of 0 to disable
-** any limit on the number of terms in a compount SELECT.
-*/
-#ifndef SQLITE_MAX_COMPOUND_SELECT
-# define SQLITE_MAX_COMPOUND_SELECT 500
-#endif
-
-/*
-** The maximum number of opcodes in a VDBE program.
-** Not currently enforced.
-*/
-#ifndef SQLITE_MAX_VDBE_OP
-# define SQLITE_MAX_VDBE_OP 25000
-#endif
-
-/*
-** The maximum number of arguments to an SQL function.
-*/
-#ifndef SQLITE_MAX_FUNCTION_ARG
-# define SQLITE_MAX_FUNCTION_ARG 127
-#endif
-
-/*
-** The maximum number of in-memory pages to use for the main database
-** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
-*/
-#ifndef SQLITE_DEFAULT_CACHE_SIZE
-# define SQLITE_DEFAULT_CACHE_SIZE 2000
-#endif
-#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
-# define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
-#endif
-
-/*
-** The maximum number of attached databases. This must be between 0
-** and 30. The upper bound on 30 is because a 32-bit integer bitmap
-** is used internally to track attached databases.
-*/
-#ifndef SQLITE_MAX_ATTACHED
-# define SQLITE_MAX_ATTACHED 10
-#endif
-
-
-/*
-** The maximum value of a ?nnn wildcard that the parser will accept.
-*/
-#ifndef SQLITE_MAX_VARIABLE_NUMBER
-# define SQLITE_MAX_VARIABLE_NUMBER 999
-#endif
-
-/* Maximum page size. The upper bound on this value is 32768. This a limit
-** imposed by the necessity of storing the value in a 2-byte unsigned integer
-** and the fact that the page size must be a power of 2.
-**
-** If this limit is changed, then the compiled library is technically
-** incompatible with an SQLite library compiled with a different limit. If
-** a process operating on a database with a page-size of 65536 bytes
-** crashes, then an instance of SQLite compiled with the default page-size
-** limit will not be able to rollback the aborted transaction. This could
-** lead to database corruption.
-*/
-#ifndef SQLITE_MAX_PAGE_SIZE
-# define SQLITE_MAX_PAGE_SIZE 32768
-#endif
-
-
-/*
-** The default size of a database page.
-*/
-#ifndef SQLITE_DEFAULT_PAGE_SIZE
-# define SQLITE_DEFAULT_PAGE_SIZE 1024
-#endif
-#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
-# undef SQLITE_DEFAULT_PAGE_SIZE
-# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
-#endif
-
-/*
-** Ordinarily, if no value is explicitly provided, SQLite creates databases
-** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
-** device characteristics (sector-size and atomic write() support),
-** SQLite may choose a larger value. This constant is the maximum value
-** SQLite will choose on its own.
-*/
-#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
-# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
-#endif
-#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
-# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
-# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
-#endif
-
-
-/*
-** Maximum number of pages in one database file.
-**
-** This is really just the default value for the max_page_count pragma.
-** This value can be lowered (or raised) at run-time using that the
-** max_page_count macro.
-*/
-#ifndef SQLITE_MAX_PAGE_COUNT
-# define SQLITE_MAX_PAGE_COUNT 1073741823
-#endif
-
-/*
-** Maximum length (in bytes) of the pattern in a LIKE or GLOB
-** operator.
-*/
-#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
-# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
-#endif
-
-/*
-** Maximum depth of recursion for triggers.
-**
-** A value of 1 means that a trigger program will not be able to itself
-** fire any triggers. A value of 0 means that no trigger programs at all
-** may be executed.
-*/
-#ifndef SQLITE_MAX_TRIGGER_DEPTH
-# define SQLITE_MAX_TRIGGER_DEPTH 1000
-#endif
-
-/************** End of sqliteLimit.h *****************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-
-/* Disable nuisance warnings on Borland compilers */
-#if defined(__BORLANDC__)
-#pragma warn -rch /* unreachable code */
-#pragma warn -ccc /* Condition is always true or false */
-#pragma warn -aus /* Assigned value is never used */
-#pragma warn -csu /* Comparing signed and unsigned */
-#pragma warn -spa /* Suspicious pointer arithmetic */
-#endif
-
-/* Needed for various definitions... */
-#ifndef _GNU_SOURCE
-# define _GNU_SOURCE
-#endif
-
-/*
-** Include standard header files as necessary
-*/
-#ifdef HAVE_STDINT_H
-#include
-#endif
-#ifdef HAVE_INTTYPES_H
-#include
-#endif
-
-#define SQLITE_INDEX_SAMPLES 10
-
-/*
-** This macro is used to "hide" some ugliness in casting an int
-** value to a ptr value under the MSVC 64-bit compiler. Casting
-** non 64-bit values to ptr types results in a "hard" error with
-** the MSVC 64-bit compiler which this attempts to avoid.
-**
-** A simple compiler pragma or casting sequence could not be found
-** to correct this in all situations, so this macro was introduced.
-**
-** It could be argued that the intptr_t type could be used in this
-** case, but that type is not available on all compilers, or
-** requires the #include of specific headers which differs between
-** platforms.
-**
-** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
-** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
-** So we have to define the macros in different ways depending on the
-** compiler.
-*/
-#if defined(__GNUC__)
-# if defined(HAVE_STDINT_H)
-# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
-# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
-# else
-# define SQLITE_INT_TO_PTR(X) ((void*)(X))
-# define SQLITE_PTR_TO_INT(X) ((int)(X))
-# endif
-#else
-# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
-# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
-#endif
-
-
-/*
-** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
-** Older versions of SQLite used an optional THREADSAFE macro.
-** We support that for legacy
-*/
-#if !defined(SQLITE_THREADSAFE)
-#if defined(THREADSAFE)
-# define SQLITE_THREADSAFE THREADSAFE
-#else
-# define SQLITE_THREADSAFE 1
-#endif
-#endif
-
-/*
-** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
-** It determines whether or not the features related to
-** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
-** be overridden at runtime using the sqlite3_config() API.
-*/
-#if !defined(SQLITE_DEFAULT_MEMSTATUS)
-# define SQLITE_DEFAULT_MEMSTATUS 1
-#endif
-
-/*
-** Exactly one of the following macros must be defined in order to
-** specify which memory allocation subsystem to use.
-**
-** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
-** SQLITE_MEMDEBUG // Debugging version of system malloc()
-** SQLITE_MEMORY_SIZE // internal allocator #1
-** SQLITE_MMAP_HEAP_SIZE // internal mmap() allocator
-** SQLITE_POW2_MEMORY_SIZE // internal power-of-two allocator
-**
-** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
-** the default.
-*/
-#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
- defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
- defined(SQLITE_POW2_MEMORY_SIZE)>1
-# error "At most one of the following compile-time configuration options\
- is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
- SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
-#endif
-#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
- defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
- defined(SQLITE_POW2_MEMORY_SIZE)==0
-# define SQLITE_SYSTEM_MALLOC 1
-#endif
-
-/*
-** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
-** sizes of memory allocations below this value where possible.
-*/
-#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
-# define SQLITE_MALLOC_SOFT_LIMIT 1024
-#endif
-
-/*
-** We need to define _XOPEN_SOURCE as follows in order to enable
-** recursive mutexes on most Unix systems. But Mac OS X is different.
-** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
-** so it is omitted there. See ticket #2673.
-**
-** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
-** implemented on some systems. So we avoid defining it at all
-** if it is already defined or if it is unneeded because we are
-** not doing a threadsafe build. Ticket #2681.
-**
-** See also ticket #2741.
-*/
-#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
-# define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */
-#endif
-
-/*
-** The TCL headers are only needed when compiling the TCL bindings.
-*/
-#if defined(SQLITE_TCL) || defined(TCLSH)
-# include
-#endif
-
-/*
-** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
-** Setting NDEBUG makes the code smaller and run faster. So the following
-** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
-** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out
-** feature.
-*/
-#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
-# define NDEBUG 1
-#endif
-
-/*
-** The testcase() macro is used to aid in coverage testing. When
-** doing coverage testing, the condition inside the argument to
-** testcase() must be evaluated both true and false in order to
-** get full branch coverage. The testcase() macro is inserted
-** to help ensure adequate test coverage in places where simple
-** condition/decision coverage is inadequate. For example, testcase()
-** can be used to make sure boundary values are tested. For
-** bitmask tests, testcase() can be used to make sure each bit
-** is significant and used at least once. On switch statements
-** where multiple cases go to the same block of code, testcase()
-** can insure that all cases are evaluated.
-**
-*/
-#ifdef SQLITE_COVERAGE_TEST
-SQLITE_PRIVATE void sqlite3Coverage(int);
-# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
-#else
-# define testcase(X)
-#endif
-
-/*
-** The TESTONLY macro is used to enclose variable declarations or
-** other bits of code that are needed to support the arguments
-** within testcase() and assert() macros.
-*/
-#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
-# define TESTONLY(X) X
-#else
-# define TESTONLY(X)
-#endif
-
-/*
-** Sometimes we need a small amount of code such as a variable initialization
-** to setup for a later assert() statement. We do not want this code to
-** appear when assert() is disabled. The following macro is therefore
-** used to contain that setup code. The "VVA" acronym stands for
-** "Verification, Validation, and Accreditation". In other words, the
-** code within VVA_ONLY() will only run during verification processes.
-*/
-#ifndef NDEBUG
-# define VVA_ONLY(X) X
-#else
-# define VVA_ONLY(X)
-#endif
-
-/*
-** The ALWAYS and NEVER macros surround boolean expressions which
-** are intended to always be true or false, respectively. Such
-** expressions could be omitted from the code completely. But they
-** are included in a few cases in order to enhance the resilience
-** of SQLite to unexpected behavior - to make the code "self-healing"
-** or "ductile" rather than being "brittle" and crashing at the first
-** hint of unplanned behavior.
-**
-** In other words, ALWAYS and NEVER are added for defensive code.
-**
-** When doing coverage testing ALWAYS and NEVER are hard-coded to
-** be true and false so that the unreachable code then specify will
-** not be counted as untested code.
-*/
-#if defined(SQLITE_COVERAGE_TEST)
-# define ALWAYS(X) (1)
-# define NEVER(X) (0)
-#elif !defined(NDEBUG)
-# define ALWAYS(X) ((X)?1:(assert(0),0))
-# define NEVER(X) ((X)?(assert(0),1):0)
-#else
-# define ALWAYS(X) (X)
-# define NEVER(X) (X)
-#endif
-
-/*
-** The macro unlikely() is a hint that surrounds a boolean
-** expression that is usually false. Macro likely() surrounds
-** a boolean expression that is usually true. GCC is able to
-** use these hints to generate better code, sometimes.
-*/
-#if defined(__GNUC__) && 0
-# define likely(X) __builtin_expect((X),1)
-# define unlikely(X) __builtin_expect((X),0)
-#else
-# define likely(X) !!(X)
-# define unlikely(X) !!(X)
-#endif
-
-/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
-/************** Begin file sqlite3.h *****************************************/
-/*
-** 2001 September 15
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This header file defines the interface that the SQLite library
-** presents to client programs. If a C-function, structure, datatype,
-** or constant definition does not appear in this file, then it is
-** not a published API of SQLite, is subject to change without
-** notice, and should not be referenced by programs that use SQLite.
-**
-** Some of the definitions that are in this file are marked as
-** "experimental". Experimental interfaces are normally new
-** features recently added to SQLite. We do not anticipate changes
-** to experimental interfaces but reserve the right to make minor changes
-** if experience from use "in the wild" suggest such changes are prudent.
-**
-** The official C-language API documentation for SQLite is derived
-** from comments in this file. This file is the authoritative source
-** on how SQLite interfaces are suppose to operate.
-**
-** The name of this file under configuration management is "sqlite.h.in".
-** The makefile makes some minor changes to this file (such as inserting
-** the version number) and changes its name to "sqlite3.h" as
-** part of the build process.
-*/
-#ifndef _SQLITE3_H_
-#define _SQLITE3_H_
-#include /* Needed for the definition of va_list */
-
-/*
-** Make sure we can call this stuff from C++.
-*/
-#if 0
-extern "C" {
-#endif
-
-
-/*
-** Add the ability to override 'extern'
-*/
-#ifndef SQLITE_EXTERN
-# define SQLITE_EXTERN extern
-#endif
-
-#ifndef SQLITE_API
-# define SQLITE_API
-#endif
-
-
-/*
-** These no-op macros are used in front of interfaces to mark those
-** interfaces as either deprecated or experimental. New applications
-** should not use deprecated interfaces - they are support for backwards
-** compatibility only. Application writers should be aware that
-** experimental interfaces are subject to change in point releases.
-**
-** These macros used to resolve to various kinds of compiler magic that
-** would generate warning messages when they were used. But that
-** compiler magic ended up generating such a flurry of bug reports
-** that we have taken it all out and gone back to using simple
-** noop macros.
-*/
-#define SQLITE_DEPRECATED
-#define SQLITE_EXPERIMENTAL
-
-/*
-** Ensure these symbols were not defined by some previous header file.
-*/
-#ifdef SQLITE_VERSION
-# undef SQLITE_VERSION
-#endif
-#ifdef SQLITE_VERSION_NUMBER
-# undef SQLITE_VERSION_NUMBER
-#endif
-
-/*
-** CAPI3REF: Compile-Time Library Version Numbers
-**
-** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
-** evaluates to a string literal that is the SQLite version in the
-** format "X.Y.Z" where X is the major version number (always 3 for
-** SQLite3) and Y is the minor version number and Z is the release number.)^
-** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
-** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
-** numbers used in [SQLITE_VERSION].)^
-** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
-** be larger than the release from which it is derived. Either Y will
-** be held constant and Z will be incremented or else Y will be incremented
-** and Z will be reset to zero.
-**
-** Since version 3.6.18, SQLite source code has been stored in the
-** Fossil configuration management
-** system. ^The SQLITE_SOURCE_ID macro evalutes to
-** a string which identifies a particular check-in of SQLite
-** within its configuration management system. ^The SQLITE_SOURCE_ID
-** string contains the date and time of the check-in (UTC) and an SHA1
-** hash of the entire source tree.
-**
-** See also: [sqlite3_libversion()],
-** [sqlite3_libversion_number()], [sqlite3_sourceid()],
-** [sqlite_version()] and [sqlite_source_id()].
-*/
-#define SQLITE_VERSION "3.6.22"
-#define SQLITE_VERSION_NUMBER 3006022
-#define SQLITE_SOURCE_ID "2010-01-05 15:30:36 28d0d7710761114a44a1a3a425a6883c661f06e7"
-
-/*
-** CAPI3REF: Run-Time Library Version Numbers
-** KEYWORDS: sqlite3_version
-**
-** These interfaces provide the same information as the [SQLITE_VERSION],
-** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
-** but are associated with the library instead of the header file. ^(Cautious
-** programmers might include assert() statements in their application to
-** verify that values returned by these interfaces match the macros in
-** the header, and thus insure that the application is
-** compiled with matching library and header files.
-**
-**
)^
-**
-** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
-** macro. ^The sqlite3_libversion() function returns a pointer to the
-** to the sqlite3_version[] string constant. The sqlite3_libversion()
-** function is provided for use in DLLs since DLL users usually do not have
-** direct access to string constants within the DLL. ^The
-** sqlite3_libversion_number() function returns an integer equal to
-** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function a pointer
-** to a string constant whose value is the same as the [SQLITE_SOURCE_ID]
-** C preprocessor macro.
-**
-** See also: [sqlite_version()] and [sqlite_source_id()].
-*/
-SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
-SQLITE_API const char *sqlite3_libversion(void);
-SQLITE_API const char *sqlite3_sourceid(void);
-SQLITE_API int sqlite3_libversion_number(void);
-
-/*
-** CAPI3REF: Test To See If The Library Is Threadsafe
-**
-** ^The sqlite3_threadsafe() function returns zero if and only if
-** SQLite was compiled mutexing code omitted due to the
-** [SQLITE_THREADSAFE] compile-time option being set to 0.
-**
-** SQLite can be compiled with or without mutexes. When
-** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
-** are enabled and SQLite is threadsafe. When the
-** [SQLITE_THREADSAFE] macro is 0,
-** the mutexes are omitted. Without the mutexes, it is not safe
-** to use SQLite concurrently from more than one thread.
-**
-** Enabling mutexes incurs a measurable performance penalty.
-** So if speed is of utmost importance, it makes sense to disable
-** the mutexes. But for maximum safety, mutexes should be enabled.
-** ^The default behavior is for mutexes to be enabled.
-**
-** This interface can be used by an application to make sure that the
-** version of SQLite that it is linking against was compiled with
-** the desired setting of the [SQLITE_THREADSAFE] macro.
-**
-** This interface only reports on the compile-time mutex setting
-** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
-** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
-** can be fully or partially disabled using a call to [sqlite3_config()]
-** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
-** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
-** sqlite3_threadsafe() function shows only the compile-time setting of
-** thread safety, not any run-time changes to that setting made by
-** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
-** is unchanged by calls to sqlite3_config().)^
-**
-** See the [threading mode] documentation for additional information.
-*/
-SQLITE_API int sqlite3_threadsafe(void);
-
-/*
-** CAPI3REF: Database Connection Handle
-** KEYWORDS: {database connection} {database connections}
-**
-** Each open SQLite database is represented by a pointer to an instance of
-** the opaque structure named "sqlite3". It is useful to think of an sqlite3
-** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
-** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
-** is its destructor. There are many other interfaces (such as
-** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
-** [sqlite3_busy_timeout()] to name but three) that are methods on an
-** sqlite3 object.
-*/
-typedef struct sqlite3 sqlite3;
-
-/*
-** CAPI3REF: 64-Bit Integer Types
-** KEYWORDS: sqlite_int64 sqlite_uint64
-**
-** Because there is no cross-platform way to specify 64-bit integer types
-** SQLite includes typedefs for 64-bit signed and unsigned integers.
-**
-** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
-** The sqlite_int64 and sqlite_uint64 types are supported for backwards
-** compatibility only.
-**
-** ^The sqlite3_int64 and sqlite_int64 types can store integer values
-** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
-** sqlite3_uint64 and sqlite_uint64 types can store integer values
-** between 0 and +18446744073709551615 inclusive.
-*/
-#ifdef SQLITE_INT64_TYPE
- typedef SQLITE_INT64_TYPE sqlite_int64;
- typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
-#elif defined(_MSC_VER) || defined(__BORLANDC__)
- typedef __int64 sqlite_int64;
- typedef unsigned __int64 sqlite_uint64;
-#else
- typedef long long int sqlite_int64;
- typedef unsigned long long int sqlite_uint64;
-#endif
-typedef sqlite_int64 sqlite3_int64;
-typedef sqlite_uint64 sqlite3_uint64;
-
-/*
-** If compiling for a processor that lacks floating point support,
-** substitute integer for floating-point.
-*/
-#ifdef SQLITE_OMIT_FLOATING_POINT
-# define double sqlite3_int64
-#endif
-
-/*
-** CAPI3REF: Closing A Database Connection
-**
-** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
-** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
-** successfullly destroyed and all associated resources are deallocated.
-**
-** Applications must [sqlite3_finalize | finalize] all [prepared statements]
-** and [sqlite3_blob_close | close] all [BLOB handles] associated with
-** the [sqlite3] object prior to attempting to close the object. ^If
-** sqlite3_close() is called on a [database connection] that still has
-** outstanding [prepared statements] or [BLOB handles], then it returns
-** SQLITE_BUSY.
-**
-** ^If [sqlite3_close()] is invoked while a transaction is open,
-** the transaction is automatically rolled back.
-**
-** The C parameter to [sqlite3_close(C)] must be either a NULL
-** pointer or an [sqlite3] object pointer obtained
-** from [sqlite3_open()], [sqlite3_open16()], or
-** [sqlite3_open_v2()], and not previously closed.
-** ^Calling sqlite3_close() with a NULL pointer argument is a
-** harmless no-op.
-*/
-SQLITE_API int sqlite3_close(sqlite3 *);
-
-/*
-** The type for a callback function.
-** This is legacy and deprecated. It is included for historical
-** compatibility and is not documented.
-*/
-typedef int (*sqlite3_callback)(void*,int,char**, char**);
-
-/*
-** CAPI3REF: One-Step Query Execution Interface
-**
-** The sqlite3_exec() interface is a convenience wrapper around
-** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
-** that allows an application to run multiple statements of SQL
-** without having to use a lot of C code.
-**
-** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
-** semicolon-separate SQL statements passed into its 2nd argument,
-** in the context of the [database connection] passed in as its 1st
-** argument. ^If the callback function of the 3rd argument to
-** sqlite3_exec() is not NULL, then it is invoked for each result row
-** coming out of the evaluated SQL statements. ^The 4th argument to
-** to sqlite3_exec() is relayed through to the 1st argument of each
-** callback invocation. ^If the callback pointer to sqlite3_exec()
-** is NULL, then no callback is ever invoked and result rows are
-** ignored.
-**
-** ^If an error occurs while evaluating the SQL statements passed into
-** sqlite3_exec(), then execution of the current statement stops and
-** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
-** is not NULL then any error message is written into memory obtained
-** from [sqlite3_malloc()] and passed back through the 5th parameter.
-** To avoid memory leaks, the application should invoke [sqlite3_free()]
-** on error message strings returned through the 5th parameter of
-** of sqlite3_exec() after the error message string is no longer needed.
-** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
-** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
-** NULL before returning.
-**
-** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
-** routine returns SQLITE_ABORT without invoking the callback again and
-** without running any subsequent SQL statements.
-**
-** ^The 2nd argument to the sqlite3_exec() callback function is the
-** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
-** callback is an array of pointers to strings obtained as if from
-** [sqlite3_column_text()], one for each column. ^If an element of a
-** result row is NULL then the corresponding string pointer for the
-** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
-** sqlite3_exec() callback is an array of pointers to strings where each
-** entry represents the name of corresponding result column as obtained
-** from [sqlite3_column_name()].
-**
-** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
-** to an empty string, or a pointer that contains only whitespace and/or
-** SQL comments, then no SQL statements are evaluated and the database
-** is not changed.
-**
-** Restrictions:
-**
-**
-**
The application must insure that the 1st parameter to sqlite3_exec()
-** is a valid and open [database connection].
-**
The application must not close [database connection] specified by
-** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
-**
The application must not modify the SQL statement text passed into
-** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
-**
-*/
-SQLITE_API int sqlite3_exec(
- sqlite3*, /* An open database */
- const char *sql, /* SQL to be evaluated */
- int (*callback)(void*,int,char**,char**), /* Callback function */
- void *, /* 1st argument to callback */
- char **errmsg /* Error msg written here */
-);
-
-/*
-** CAPI3REF: Result Codes
-** KEYWORDS: SQLITE_OK {error code} {error codes}
-** KEYWORDS: {result code} {result codes}
-**
-** Many SQLite functions return an integer result code from the set shown
-** here in order to indicates success or failure.
-**
-** New error codes may be added in future versions of SQLite.
-**
-** See also: [SQLITE_IOERR_READ | extended result codes]
-*/
-#define SQLITE_OK 0 /* Successful result */
-/* beginning-of-error-codes */
-#define SQLITE_ERROR 1 /* SQL error or missing database */
-#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
-#define SQLITE_PERM 3 /* Access permission denied */
-#define SQLITE_ABORT 4 /* Callback routine requested an abort */
-#define SQLITE_BUSY 5 /* The database file is locked */
-#define SQLITE_LOCKED 6 /* A table in the database is locked */
-#define SQLITE_NOMEM 7 /* A malloc() failed */
-#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
-#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
-#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
-#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
-#define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */
-#define SQLITE_FULL 13 /* Insertion failed because database is full */
-#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
-#define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */
-#define SQLITE_EMPTY 16 /* Database is empty */
-#define SQLITE_SCHEMA 17 /* The database schema changed */
-#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
-#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
-#define SQLITE_MISMATCH 20 /* Data type mismatch */
-#define SQLITE_MISUSE 21 /* Library used incorrectly */
-#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
-#define SQLITE_AUTH 23 /* Authorization denied */
-#define SQLITE_FORMAT 24 /* Auxiliary database format error */
-#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
-#define SQLITE_NOTADB 26 /* File opened that is not a database file */
-#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
-#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
-/* end-of-error-codes */
-
-/*
-** CAPI3REF: Extended Result Codes
-** KEYWORDS: {extended error code} {extended error codes}
-** KEYWORDS: {extended result code} {extended result codes}
-**
-** In its default configuration, SQLite API routines return one of 26 integer
-** [SQLITE_OK | result codes]. However, experience has shown that many of
-** these result codes are too coarse-grained. They do not provide as
-** much information about problems as programmers might like. In an effort to
-** address this, newer versions of SQLite (version 3.3.8 and later) include
-** support for additional result codes that provide more detailed information
-** about errors. The extended result codes are enabled or disabled
-** on a per database connection basis using the
-** [sqlite3_extended_result_codes()] API.
-**
-** Some of the available extended result codes are listed here.
-** One may expect the number of extended result codes will be expand
-** over time. Software that uses extended result codes should expect
-** to see new result codes in future releases of SQLite.
-**
-** The SQLITE_OK result code will never be extended. It will always
-** be exactly zero.
-*/
-#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
-#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
-#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
-#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
-#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
-#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
-#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
-#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
-#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
-#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
-#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
-#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
-#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
-#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
-#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
-#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
-#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
-#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8) )
-
-/*
-** CAPI3REF: Flags For File Open Operations
-**
-** These bit values are intended for use in the
-** 3rd parameter to the [sqlite3_open_v2()] interface and
-** in the 4th parameter to the xOpen method of the
-** [sqlite3_vfs] object.
-*/
-#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
-#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
-#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
-#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
-#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
-#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
-#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
-#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
-#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
-#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
-#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
-#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
-#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
-#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
-#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
-#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
-
-/*
-** CAPI3REF: Device Characteristics
-**
-** The xDeviceCapabilities method of the [sqlite3_io_methods]
-** object returns an integer which is a vector of the these
-** bit values expressing I/O characteristics of the mass storage
-** device that holds the file that the [sqlite3_io_methods]
-** refers to.
-**
-** The SQLITE_IOCAP_ATOMIC property means that all writes of
-** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
-** mean that writes of blocks that are nnn bytes in size and
-** are aligned to an address which is an integer multiple of
-** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
-** that when data is appended to a file, the data is appended
-** first then the size of the file is extended, never the other
-** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
-** information is written to disk in the same order as calls
-** to xWrite().
-*/
-#define SQLITE_IOCAP_ATOMIC 0x00000001
-#define SQLITE_IOCAP_ATOMIC512 0x00000002
-#define SQLITE_IOCAP_ATOMIC1K 0x00000004
-#define SQLITE_IOCAP_ATOMIC2K 0x00000008
-#define SQLITE_IOCAP_ATOMIC4K 0x00000010
-#define SQLITE_IOCAP_ATOMIC8K 0x00000020
-#define SQLITE_IOCAP_ATOMIC16K 0x00000040
-#define SQLITE_IOCAP_ATOMIC32K 0x00000080
-#define SQLITE_IOCAP_ATOMIC64K 0x00000100
-#define SQLITE_IOCAP_SAFE_APPEND 0x00000200
-#define SQLITE_IOCAP_SEQUENTIAL 0x00000400
-
-/*
-** CAPI3REF: File Locking Levels
-**
-** SQLite uses one of these integer values as the second
-** argument to calls it makes to the xLock() and xUnlock() methods
-** of an [sqlite3_io_methods] object.
-*/
-#define SQLITE_LOCK_NONE 0
-#define SQLITE_LOCK_SHARED 1
-#define SQLITE_LOCK_RESERVED 2
-#define SQLITE_LOCK_PENDING 3
-#define SQLITE_LOCK_EXCLUSIVE 4
-
-/*
-** CAPI3REF: Synchronization Type Flags
-**
-** When SQLite invokes the xSync() method of an
-** [sqlite3_io_methods] object it uses a combination of
-** these integer values as the second argument.
-**
-** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
-** sync operation only needs to flush data to mass storage. Inode
-** information need not be flushed. If the lower four bits of the flag
-** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
-** If the lower four bits equal SQLITE_SYNC_FULL, that means
-** to use Mac OS X style fullsync instead of fsync().
-*/
-#define SQLITE_SYNC_NORMAL 0x00002
-#define SQLITE_SYNC_FULL 0x00003
-#define SQLITE_SYNC_DATAONLY 0x00010
-
-/*
-** CAPI3REF: OS Interface Open File Handle
-**
-** An [sqlite3_file] object represents an open file in the
-** [sqlite3_vfs | OS interface layer]. Individual OS interface
-** implementations will
-** want to subclass this object by appending additional fields
-** for their own use. The pMethods entry is a pointer to an
-** [sqlite3_io_methods] object that defines methods for performing
-** I/O operations on the open file.
-*/
-typedef struct sqlite3_file sqlite3_file;
-struct sqlite3_file {
- const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
-};
-
-/*
-** CAPI3REF: OS Interface File Virtual Methods Object
-**
-** Every file opened by the [sqlite3_vfs] xOpen method populates an
-** [sqlite3_file] object (or, more commonly, a subclass of the
-** [sqlite3_file] object) with a pointer to an instance of this object.
-** This object defines the methods used to perform various operations
-** against the open file represented by the [sqlite3_file] object.
-**
-** If the xOpen method sets the sqlite3_file.pMethods element
-** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
-** may be invoked even if the xOpen reported that it failed. The
-** only way to prevent a call to xClose following a failed xOpen
-** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
-**
-** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
-** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
-** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
-** flag may be ORed in to indicate that only the data of the file
-** and not its inode needs to be synced.
-**
-** The integer values to xLock() and xUnlock() are one of
-**
-**
[SQLITE_LOCK_NONE],
-**
[SQLITE_LOCK_SHARED],
-**
[SQLITE_LOCK_RESERVED],
-**
[SQLITE_LOCK_PENDING], or
-**
[SQLITE_LOCK_EXCLUSIVE].
-**
-** xLock() increases the lock. xUnlock() decreases the lock.
-** The xCheckReservedLock() method checks whether any database connection,
-** either in this process or in some other process, is holding a RESERVED,
-** PENDING, or EXCLUSIVE lock on the file. It returns true
-** if such a lock exists and false otherwise.
-**
-** The xFileControl() method is a generic interface that allows custom
-** VFS implementations to directly control an open file using the
-** [sqlite3_file_control()] interface. The second "op" argument is an
-** integer opcode. The third argument is a generic pointer intended to
-** point to a structure that may contain arguments or space in which to
-** write return values. Potential uses for xFileControl() might be
-** functions to enable blocking locks with timeouts, to change the
-** locking strategy (for example to use dot-file locks), to inquire
-** about the status of a lock, or to break stale locks. The SQLite
-** core reserves all opcodes less than 100 for its own use.
-** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
-** Applications that define a custom xFileControl method should use opcodes
-** greater than 100 to avoid conflicts.
-**
-** The xSectorSize() method returns the sector size of the
-** device that underlies the file. The sector size is the
-** minimum write that can be performed without disturbing
-** other bytes in the file. The xDeviceCharacteristics()
-** method returns a bit vector describing behaviors of the
-** underlying device:
-**
-**
-**
[SQLITE_IOCAP_ATOMIC]
-**
[SQLITE_IOCAP_ATOMIC512]
-**
[SQLITE_IOCAP_ATOMIC1K]
-**
[SQLITE_IOCAP_ATOMIC2K]
-**
[SQLITE_IOCAP_ATOMIC4K]
-**
[SQLITE_IOCAP_ATOMIC8K]
-**
[SQLITE_IOCAP_ATOMIC16K]
-**
[SQLITE_IOCAP_ATOMIC32K]
-**
[SQLITE_IOCAP_ATOMIC64K]
-**
[SQLITE_IOCAP_SAFE_APPEND]
-**
[SQLITE_IOCAP_SEQUENTIAL]
-**
-**
-** The SQLITE_IOCAP_ATOMIC property means that all writes of
-** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
-** mean that writes of blocks that are nnn bytes in size and
-** are aligned to an address which is an integer multiple of
-** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
-** that when data is appended to a file, the data is appended
-** first then the size of the file is extended, never the other
-** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
-** information is written to disk in the same order as calls
-** to xWrite().
-**
-** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
-** in the unread portions of the buffer with zeros. A VFS that
-** fails to zero-fill short reads might seem to work. However,
-** failure to zero-fill short reads will eventually lead to
-** database corruption.
-*/
-typedef struct sqlite3_io_methods sqlite3_io_methods;
-struct sqlite3_io_methods {
- int iVersion;
- int (*xClose)(sqlite3_file*);
- int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
- int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
- int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
- int (*xSync)(sqlite3_file*, int flags);
- int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
- int (*xLock)(sqlite3_file*, int);
- int (*xUnlock)(sqlite3_file*, int);
- int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
- int (*xFileControl)(sqlite3_file*, int op, void *pArg);
- int (*xSectorSize)(sqlite3_file*);
- int (*xDeviceCharacteristics)(sqlite3_file*);
- /* Additional methods may be added in future releases */
-};
-
-/*
-** CAPI3REF: Standard File Control Opcodes
-**
-** These integer constants are opcodes for the xFileControl method
-** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
-** interface.
-**
-** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
-** opcode causes the xFileControl method to write the current state of
-** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
-** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
-** into an integer that the pArg argument points to. This capability
-** is used during testing and only needs to be supported when SQLITE_TEST
-** is defined.
-*/
-#define SQLITE_FCNTL_LOCKSTATE 1
-#define SQLITE_GET_LOCKPROXYFILE 2
-#define SQLITE_SET_LOCKPROXYFILE 3
-#define SQLITE_LAST_ERRNO 4
-
-/*
-** CAPI3REF: Mutex Handle
-**
-** The mutex module within SQLite defines [sqlite3_mutex] to be an
-** abstract type for a mutex object. The SQLite core never looks
-** at the internal representation of an [sqlite3_mutex]. It only
-** deals with pointers to the [sqlite3_mutex] object.
-**
-** Mutexes are created using [sqlite3_mutex_alloc()].
-*/
-typedef struct sqlite3_mutex sqlite3_mutex;
-
-/*
-** CAPI3REF: OS Interface Object
-**
-** An instance of the sqlite3_vfs object defines the interface between
-** the SQLite core and the underlying operating system. The "vfs"
-** in the name of the object stands for "virtual file system".
-**
-** The value of the iVersion field is initially 1 but may be larger in
-** future versions of SQLite. Additional fields may be appended to this
-** object when the iVersion value is increased. Note that the structure
-** of the sqlite3_vfs object changes in the transaction between
-** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
-** modified.
-**
-** The szOsFile field is the size of the subclassed [sqlite3_file]
-** structure used by this VFS. mxPathname is the maximum length of
-** a pathname in this VFS.
-**
-** Registered sqlite3_vfs objects are kept on a linked list formed by
-** the pNext pointer. The [sqlite3_vfs_register()]
-** and [sqlite3_vfs_unregister()] interfaces manage this list
-** in a thread-safe way. The [sqlite3_vfs_find()] interface
-** searches the list. Neither the application code nor the VFS
-** implementation should use the pNext pointer.
-**
-** The pNext field is the only field in the sqlite3_vfs
-** structure that SQLite will ever modify. SQLite will only access
-** or modify this field while holding a particular static mutex.
-** The application should never modify anything within the sqlite3_vfs
-** object once the object has been registered.
-**
-** The zName field holds the name of the VFS module. The name must
-** be unique across all VFS modules.
-**
-** SQLite will guarantee that the zFilename parameter to xOpen
-** is either a NULL pointer or string obtained
-** from xFullPathname(). SQLite further guarantees that
-** the string will be valid and unchanged until xClose() is
-** called. Because of the previous sentence,
-** the [sqlite3_file] can safely store a pointer to the
-** filename if it needs to remember the filename for some reason.
-** If the zFilename parameter is xOpen is a NULL pointer then xOpen
-** must invent its own temporary name for the file. Whenever the
-** xFilename parameter is NULL it will also be the case that the
-** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
-**
-** The flags argument to xOpen() includes all bits set in
-** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
-** or [sqlite3_open16()] is used, then flags includes at least
-** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
-** If xOpen() opens a file read-only then it sets *pOutFlags to
-** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
-**
-** SQLite will also add one of the following flags to the xOpen()
-** call, depending on the object being opened:
-**
-**
-**
[SQLITE_OPEN_MAIN_DB]
-**
[SQLITE_OPEN_MAIN_JOURNAL]
-**
[SQLITE_OPEN_TEMP_DB]
-**
[SQLITE_OPEN_TEMP_JOURNAL]
-**
[SQLITE_OPEN_TRANSIENT_DB]
-**
[SQLITE_OPEN_SUBJOURNAL]
-**
[SQLITE_OPEN_MASTER_JOURNAL]
-**
-**
-** The file I/O implementation can use the object type flags to
-** change the way it deals with files. For example, an application
-** that does not care about crash recovery or rollback might make
-** the open of a journal file a no-op. Writes to this journal would
-** also be no-ops, and any attempt to read the journal would return
-** SQLITE_IOERR. Or the implementation might recognize that a database
-** file will be doing page-aligned sector reads and writes in a random
-** order and set up its I/O subsystem accordingly.
-**
-** SQLite might also add one of the following flags to the xOpen method:
-**
-**
-**
[SQLITE_OPEN_DELETEONCLOSE]
-**
[SQLITE_OPEN_EXCLUSIVE]
-**
-**
-** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
-** deleted when it is closed. The [SQLITE_OPEN_DELETEONCLOSE]
-** will be set for TEMP databases, journals and for subjournals.
-**
-** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
-** with the [SQLITE_OPEN_CREATE] flag, which are both directly
-** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
-** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
-** SQLITE_OPEN_CREATE, is used to indicate that file should always
-** be created, and that it is an error if it already exists.
-** It is not used to indicate the file should be opened
-** for exclusive access.
-**
-** At least szOsFile bytes of memory are allocated by SQLite
-** to hold the [sqlite3_file] structure passed as the third
-** argument to xOpen. The xOpen method does not have to
-** allocate the structure; it should just fill it in. Note that
-** the xOpen method must set the sqlite3_file.pMethods to either
-** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
-** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
-** element will be valid after xOpen returns regardless of the success
-** or failure of the xOpen call.
-**
-** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
-** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
-** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
-** to test whether a file is at least readable. The file can be a
-** directory.
-**
-** SQLite will always allocate at least mxPathname+1 bytes for the
-** output buffer xFullPathname. The exact size of the output buffer
-** is also passed as a parameter to both methods. If the output buffer
-** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
-** handled as a fatal error by SQLite, vfs implementations should endeavor
-** to prevent this by setting mxPathname to a sufficiently large value.
-**
-** The xRandomness(), xSleep(), and xCurrentTime() interfaces
-** are not strictly a part of the filesystem, but they are
-** included in the VFS structure for completeness.
-** The xRandomness() function attempts to return nBytes bytes
-** of good-quality randomness into zOut. The return value is
-** the actual number of bytes of randomness obtained.
-** The xSleep() method causes the calling thread to sleep for at
-** least the number of microseconds given. The xCurrentTime()
-** method returns a Julian Day Number for the current date and time.
-**
-*/
-typedef struct sqlite3_vfs sqlite3_vfs;
-struct sqlite3_vfs {
- int iVersion; /* Structure version number */
- int szOsFile; /* Size of subclassed sqlite3_file */
- int mxPathname; /* Maximum file pathname length */
- sqlite3_vfs *pNext; /* Next registered VFS */
- const char *zName; /* Name of this virtual file system */
- void *pAppData; /* Pointer to application-specific data */
- int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
- int flags, int *pOutFlags);
- int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
- int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
- int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
- void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
- void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
- void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
- void (*xDlClose)(sqlite3_vfs*, void*);
- int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
- int (*xSleep)(sqlite3_vfs*, int microseconds);
- int (*xCurrentTime)(sqlite3_vfs*, double*);
- int (*xGetLastError)(sqlite3_vfs*, int, char *);
- /* New fields may be appended in figure versions. The iVersion
- ** value will increment whenever this happens. */
-};
-
-/*
-** CAPI3REF: Flags for the xAccess VFS method
-**
-** These integer constants can be used as the third parameter to
-** the xAccess method of an [sqlite3_vfs] object. They determine
-** what kind of permissions the xAccess method is looking for.
-** With SQLITE_ACCESS_EXISTS, the xAccess method
-** simply checks whether the file exists.
-** With SQLITE_ACCESS_READWRITE, the xAccess method
-** checks whether the file is both readable and writable.
-** With SQLITE_ACCESS_READ, the xAccess method
-** checks whether the file is readable.
-*/
-#define SQLITE_ACCESS_EXISTS 0
-#define SQLITE_ACCESS_READWRITE 1
-#define SQLITE_ACCESS_READ 2
-
-/*
-** CAPI3REF: Initialize The SQLite Library
-**
-** ^The sqlite3_initialize() routine initializes the
-** SQLite library. ^The sqlite3_shutdown() routine
-** deallocates any resources that were allocated by sqlite3_initialize().
-** These routines are designed to aid in process initialization and
-** shutdown on embedded systems. Workstation applications using
-** SQLite normally do not need to invoke either of these routines.
-**
-** A call to sqlite3_initialize() is an "effective" call if it is
-** the first time sqlite3_initialize() is invoked during the lifetime of
-** the process, or if it is the first time sqlite3_initialize() is invoked
-** following a call to sqlite3_shutdown(). ^(Only an effective call
-** of sqlite3_initialize() does any initialization. All other calls
-** are harmless no-ops.)^
-**
-** A call to sqlite3_shutdown() is an "effective" call if it is the first
-** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
-** an effective call to sqlite3_shutdown() does any deinitialization.
-** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
-**
-** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
-** is not. The sqlite3_shutdown() interface must only be called from a
-** single thread. All open [database connections] must be closed and all
-** other SQLite resources must be deallocated prior to invoking
-** sqlite3_shutdown().
-**
-** Among other things, ^sqlite3_initialize() will invoke
-** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
-** will invoke sqlite3_os_end().
-**
-** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
-** ^If for some reason, sqlite3_initialize() is unable to initialize
-** the library (perhaps it is unable to allocate a needed resource such
-** as a mutex) it returns an [error code] other than [SQLITE_OK].
-**
-** ^The sqlite3_initialize() routine is called internally by many other
-** SQLite interfaces so that an application usually does not need to
-** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
-** calls sqlite3_initialize() so the SQLite library will be automatically
-** initialized when [sqlite3_open()] is called if it has not be initialized
-** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
-** compile-time option, then the automatic calls to sqlite3_initialize()
-** are omitted and the application must call sqlite3_initialize() directly
-** prior to using any other SQLite interface. For maximum portability,
-** it is recommended that applications always invoke sqlite3_initialize()
-** directly prior to using any other SQLite interface. Future releases
-** of SQLite may require this. In other words, the behavior exhibited
-** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
-** default behavior in some future release of SQLite.
-**
-** The sqlite3_os_init() routine does operating-system specific
-** initialization of the SQLite library. The sqlite3_os_end()
-** routine undoes the effect of sqlite3_os_init(). Typical tasks
-** performed by these routines include allocation or deallocation
-** of static resources, initialization of global variables,
-** setting up a default [sqlite3_vfs] module, or setting up
-** a default configuration using [sqlite3_config()].
-**
-** The application should never invoke either sqlite3_os_init()
-** or sqlite3_os_end() directly. The application should only invoke
-** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
-** interface is called automatically by sqlite3_initialize() and
-** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
-** implementations for sqlite3_os_init() and sqlite3_os_end()
-** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
-** When [custom builds | built for other platforms]
-** (using the [SQLITE_OS_OTHER=1] compile-time
-** option) the application must supply a suitable implementation for
-** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
-** implementation of sqlite3_os_init() or sqlite3_os_end()
-** must return [SQLITE_OK] on success and some other [error code] upon
-** failure.
-*/
-SQLITE_API int sqlite3_initialize(void);
-SQLITE_API int sqlite3_shutdown(void);
-SQLITE_API int sqlite3_os_init(void);
-SQLITE_API int sqlite3_os_end(void);
-
-/*
-** CAPI3REF: Configuring The SQLite Library
-** EXPERIMENTAL
-**
-** The sqlite3_config() interface is used to make global configuration
-** changes to SQLite in order to tune SQLite to the specific needs of
-** the application. The default configuration is recommended for most
-** applications and so this routine is usually not necessary. It is
-** provided to support rare applications with unusual needs.
-**
-** The sqlite3_config() interface is not threadsafe. The application
-** must insure that no other SQLite interfaces are invoked by other
-** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
-** may only be invoked prior to library initialization using
-** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
-** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
-** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
-** Note, however, that ^sqlite3_config() can be called as part of the
-** implementation of an application-defined [sqlite3_os_init()].
-**
-** The first argument to sqlite3_config() is an integer
-** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
-** what property of SQLite is to be configured. Subsequent arguments
-** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
-** in the first argument.
-**
-** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
-** ^If the option is unknown or SQLite is unable to set the option
-** then this routine returns a non-zero [error code].
-*/
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
-
-/*
-** CAPI3REF: Configure database connections
-** EXPERIMENTAL
-**
-** The sqlite3_db_config() interface is used to make configuration
-** changes to a [database connection]. The interface is similar to
-** [sqlite3_config()] except that the changes apply to a single
-** [database connection] (specified in the first argument). The
-** sqlite3_db_config() interface should only be used immediately after
-** the database connection is created using [sqlite3_open()],
-** [sqlite3_open16()], or [sqlite3_open_v2()].
-**
-** The second argument to sqlite3_db_config(D,V,...) is the
-** configuration verb - an integer code that indicates what
-** aspect of the [database connection] is being configured.
-** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
-** New verbs are likely to be added in future releases of SQLite.
-** Additional arguments depend on the verb.
-**
-** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
-** the call is considered successful.
-*/
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
-
-/*
-** CAPI3REF: Memory Allocation Routines
-** EXPERIMENTAL
-**
-** An instance of this object defines the interface between SQLite
-** and low-level memory allocation routines.
-**
-** This object is used in only one place in the SQLite interface.
-** A pointer to an instance of this object is the argument to
-** [sqlite3_config()] when the configuration option is
-** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
-** By creating an instance of this object
-** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
-** during configuration, an application can specify an alternative
-** memory allocation subsystem for SQLite to use for all of its
-** dynamic memory needs.
-**
-** Note that SQLite comes with several [built-in memory allocators]
-** that are perfectly adequate for the overwhelming majority of applications
-** and that this object is only useful to a tiny minority of applications
-** with specialized memory allocation requirements. This object is
-** also used during testing of SQLite in order to specify an alternative
-** memory allocator that simulates memory out-of-memory conditions in
-** order to verify that SQLite recovers gracefully from such
-** conditions.
-**
-** The xMalloc and xFree methods must work like the
-** malloc() and free() functions from the standard C library.
-** The xRealloc method must work like realloc() from the standard C library
-** with the exception that if the second argument to xRealloc is zero,
-** xRealloc must be a no-op - it must not perform any allocation or
-** deallocation. ^SQLite guarantees that the second argument to
-** xRealloc is always a value returned by a prior call to xRoundup.
-** And so in cases where xRoundup always returns a positive number,
-** xRealloc can perform exactly as the standard library realloc() and
-** still be in compliance with this specification.
-**
-** xSize should return the allocated size of a memory allocation
-** previously obtained from xMalloc or xRealloc. The allocated size
-** is always at least as big as the requested size but may be larger.
-**
-** The xRoundup method returns what would be the allocated size of
-** a memory allocation given a particular requested size. Most memory
-** allocators round up memory allocations at least to the next multiple
-** of 8. Some allocators round up to a larger multiple or to a power of 2.
-** Every memory allocation request coming in through [sqlite3_malloc()]
-** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
-** that causes the corresponding memory allocation to fail.
-**
-** The xInit method initializes the memory allocator. (For example,
-** it might allocate any require mutexes or initialize internal data
-** structures. The xShutdown method is invoked (indirectly) by
-** [sqlite3_shutdown()] and should deallocate any resources acquired
-** by xInit. The pAppData pointer is used as the only parameter to
-** xInit and xShutdown.
-**
-** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
-** the xInit method, so the xInit method need not be threadsafe. The
-** xShutdown method is only called from [sqlite3_shutdown()] so it does
-** not need to be threadsafe either. For all other methods, SQLite
-** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
-** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
-** it is by default) and so the methods are automatically serialized.
-** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
-** methods must be threadsafe or else make their own arrangements for
-** serialization.
-**
-** SQLite will never invoke xInit() more than once without an intervening
-** call to xShutdown().
-*/
-typedef struct sqlite3_mem_methods sqlite3_mem_methods;
-struct sqlite3_mem_methods {
- void *(*xMalloc)(int); /* Memory allocation function */
- void (*xFree)(void*); /* Free a prior allocation */
- void *(*xRealloc)(void*,int); /* Resize an allocation */
- int (*xSize)(void*); /* Return the size of an allocation */
- int (*xRoundup)(int); /* Round up request size to allocation size */
- int (*xInit)(void*); /* Initialize the memory allocator */
- void (*xShutdown)(void*); /* Deinitialize the memory allocator */
- void *pAppData; /* Argument to xInit() and xShutdown() */
-};
-
-/*
-** CAPI3REF: Configuration Options
-** EXPERIMENTAL
-**
-** These constants are the available integer configuration options that
-** can be passed as the first argument to the [sqlite3_config()] interface.
-**
-** New configuration options may be added in future releases of SQLite.
-** Existing configuration options might be discontinued. Applications
-** should check the return code from [sqlite3_config()] to make sure that
-** the call worked. The [sqlite3_config()] interface will return a
-** non-zero [error code] if a discontinued or unsupported configuration option
-** is invoked.
-**
-**
-**
SQLITE_CONFIG_SINGLETHREAD
-**
There are no arguments to this option. ^This option sets the
-** [threading mode] to Single-thread. In other words, it disables
-** all mutexing and puts SQLite into a mode where it can only be used
-** by a single thread. ^If SQLite is compiled with
-** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
-** it is not possible to change the [threading mode] from its default
-** value of Single-thread and so [sqlite3_config()] will return
-** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
-** configuration option.
-**
-**
SQLITE_CONFIG_MULTITHREAD
-**
There are no arguments to this option. ^This option sets the
-** [threading mode] to Multi-thread. In other words, it disables
-** mutexing on [database connection] and [prepared statement] objects.
-** The application is responsible for serializing access to
-** [database connections] and [prepared statements]. But other mutexes
-** are enabled so that SQLite will be safe to use in a multi-threaded
-** environment as long as no two threads attempt to use the same
-** [database connection] at the same time. ^If SQLite is compiled with
-** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
-** it is not possible to set the Multi-thread [threading mode] and
-** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
-** SQLITE_CONFIG_MULTITHREAD configuration option.
-**
-**
SQLITE_CONFIG_SERIALIZED
-**
There are no arguments to this option. ^This option sets the
-** [threading mode] to Serialized. In other words, this option enables
-** all mutexes including the recursive
-** mutexes on [database connection] and [prepared statement] objects.
-** In this mode (which is the default when SQLite is compiled with
-** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
-** to [database connections] and [prepared statements] so that the
-** application is free to use the same [database connection] or the
-** same [prepared statement] in different threads at the same time.
-** ^If SQLite is compiled with
-** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
-** it is not possible to set the Serialized [threading mode] and
-** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
-** SQLITE_CONFIG_SERIALIZED configuration option.
-**
-**
SQLITE_CONFIG_MALLOC
-**
^(This option takes a single argument which is a pointer to an
-** instance of the [sqlite3_mem_methods] structure. The argument specifies
-** alternative low-level memory allocation routines to be used in place of
-** the memory allocation routines built into SQLite.)^ ^SQLite makes
-** its own private copy of the content of the [sqlite3_mem_methods] structure
-** before the [sqlite3_config()] call returns.
-**
-**
SQLITE_CONFIG_GETMALLOC
-**
^(This option takes a single argument which is a pointer to an
-** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
-** structure is filled with the currently defined memory allocation routines.)^
-** This option can be used to overload the default memory allocation
-** routines with a wrapper that simulations memory allocation failure or
-** tracks memory usage, for example.
-**
-**
SQLITE_CONFIG_MEMSTATUS
-**
^This option takes single argument of type int, interpreted as a
-** boolean, which enables or disables the collection of memory allocation
-** statistics. ^(When memory allocation statistics are disabled, the
-** following SQLite interfaces become non-operational:
-**
-**
[sqlite3_memory_used()]
-**
[sqlite3_memory_highwater()]
-**
[sqlite3_soft_heap_limit()]
-**
[sqlite3_status()]
-**
)^
-** ^Memory allocation statistics are enabled by default unless SQLite is
-** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
-** allocation statistics are disabled by default.
-**
-**
-**
SQLITE_CONFIG_SCRATCH
-**
^This option specifies a static memory buffer that SQLite can use for
-** scratch memory. There are three arguments: A pointer an 8-byte
-** aligned memory buffer from which the scrach allocations will be
-** drawn, the size of each scratch allocation (sz),
-** and the maximum number of scratch allocations (N). The sz
-** argument must be a multiple of 16. The sz parameter should be a few bytes
-** larger than the actual scratch space required due to internal overhead.
-** The first argument must be a pointer to an 8-byte aligned buffer
-** of at least sz*N bytes of memory.
-** ^SQLite will use no more than one scratch buffer per thread. So
-** N should be set to the expected maximum number of threads. ^SQLite will
-** never require a scratch buffer that is more than 6 times the database
-** page size. ^If SQLite needs needs additional scratch memory beyond
-** what is provided by this configuration option, then
-** [sqlite3_malloc()] will be used to obtain the memory needed.
-**
-**
SQLITE_CONFIG_PAGECACHE
-**
^This option specifies a static memory buffer that SQLite can use for
-** the database page cache with the default page cache implemenation.
-** This configuration should not be used if an application-define page
-** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
-** There are three arguments to this option: A pointer to 8-byte aligned
-** memory, the size of each page buffer (sz), and the number of pages (N).
-** The sz argument should be the size of the largest database page
-** (a power of two between 512 and 32768) plus a little extra for each
-** page header. ^The page header size is 20 to 40 bytes depending on
-** the host architecture. ^It is harmless, apart from the wasted memory,
-** to make sz a little too large. The first
-** argument should point to an allocation of at least sz*N bytes of memory.
-** ^SQLite will use the memory provided by the first argument to satisfy its
-** memory needs for the first N pages that it adds to cache. ^If additional
-** page cache memory is needed beyond what is provided by this option, then
-** SQLite goes to [sqlite3_malloc()] for the additional storage space.
-** ^The implementation might use one or more of the N buffers to hold
-** memory accounting information. The pointer in the first argument must
-** be aligned to an 8-byte boundary or subsequent behavior of SQLite
-** will be undefined.
-**
-**
SQLITE_CONFIG_HEAP
-**
^This option specifies a static memory buffer that SQLite will use
-** for all of its dynamic memory allocation needs beyond those provided
-** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
-** There are three arguments: An 8-byte aligned pointer to the memory,
-** the number of bytes in the memory buffer, and the minimum allocation size.
-** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
-** to using its default memory allocator (the system malloc() implementation),
-** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
-** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
-** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
-** allocator is engaged to handle all of SQLites memory allocation needs.
-** The first pointer (the memory pointer) must be aligned to an 8-byte
-** boundary or subsequent behavior of SQLite will be undefined.
-**
-**
SQLITE_CONFIG_MUTEX
-**
^(This option takes a single argument which is a pointer to an
-** instance of the [sqlite3_mutex_methods] structure. The argument specifies
-** alternative low-level mutex routines to be used in place
-** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
-** content of the [sqlite3_mutex_methods] structure before the call to
-** [sqlite3_config()] returns. ^If SQLite is compiled with
-** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
-** the entire mutexing subsystem is omitted from the build and hence calls to
-** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
-** return [SQLITE_ERROR].
-**
-**
SQLITE_CONFIG_GETMUTEX
-**
^(This option takes a single argument which is a pointer to an
-** instance of the [sqlite3_mutex_methods] structure. The
-** [sqlite3_mutex_methods]
-** structure is filled with the currently defined mutex routines.)^
-** This option can be used to overload the default mutex allocation
-** routines with a wrapper used to track mutex usage for performance
-** profiling or testing, for example. ^If SQLite is compiled with
-** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
-** the entire mutexing subsystem is omitted from the build and hence calls to
-** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
-** return [SQLITE_ERROR].
-**
-**
SQLITE_CONFIG_LOOKASIDE
-**
^(This option takes two arguments that determine the default
-** memory allocation for the lookaside memory allocator on each
-** [database connection]. The first argument is the
-** size of each lookaside buffer slot and the second is the number of
-** slots allocated to each database connection.)^ ^(This option sets the
-** default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
-** verb to [sqlite3_db_config()] can be used to change the lookaside
-** configuration on individual connections.)^
-**
-**
SQLITE_CONFIG_PCACHE
-**
^(This option takes a single argument which is a pointer to
-** an [sqlite3_pcache_methods] object. This object specifies the interface
-** to a custom page cache implementation.)^ ^SQLite makes a copy of the
-** object and uses it for page cache memory allocations.
-**
-**
SQLITE_CONFIG_GETPCACHE
-**
^(This option takes a single argument which is a pointer to an
-** [sqlite3_pcache_methods] object. SQLite copies of the current
-** page cache implementation into that object.)^
-**
-**
-*/
-#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
-#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
-#define SQLITE_CONFIG_SERIALIZED 3 /* nil */
-#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
-#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
-#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
-#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
-#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
-#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
-#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
-#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
-/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
-#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
-#define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */
-#define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */
-
-/*
-** CAPI3REF: Configuration Options
-** EXPERIMENTAL
-**
-** These constants are the available integer configuration options that
-** can be passed as the second argument to the [sqlite3_db_config()] interface.
-**
-** New configuration options may be added in future releases of SQLite.
-** Existing configuration options might be discontinued. Applications
-** should check the return code from [sqlite3_db_config()] to make sure that
-** the call worked. ^The [sqlite3_db_config()] interface will return a
-** non-zero [error code] if a discontinued or unsupported configuration option
-** is invoked.
-**
-**
-**
SQLITE_DBCONFIG_LOOKASIDE
-**
^This option takes three additional arguments that determine the
-** [lookaside memory allocator] configuration for the [database connection].
-** ^The first argument (the third parameter to [sqlite3_db_config()] is a
-** pointer to an memory buffer to use for lookaside memory.
-** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
-** may be NULL in which case SQLite will allocate the
-** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
-** size of each lookaside buffer slot. ^The third argument is the number of
-** slots. The size of the buffer in the first argument must be greater than
-** or equal to the product of the second and third arguments. The buffer
-** must be aligned to an 8-byte boundary. ^If the second argument to
-** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
-** rounded down to the next smaller
-** multiple of 8. See also: [SQLITE_CONFIG_LOOKASIDE]
-**
-**
-*/
-#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
-
-
-/*
-** CAPI3REF: Enable Or Disable Extended Result Codes
-**
-** ^The sqlite3_extended_result_codes() routine enables or disables the
-** [extended result codes] feature of SQLite. ^The extended result
-** codes are disabled by default for historical compatibility.
-*/
-SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
-
-/*
-** CAPI3REF: Last Insert Rowid
-**
-** ^Each entry in an SQLite table has a unique 64-bit signed
-** integer key called the [ROWID | "rowid"]. ^The rowid is always available
-** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
-** names are not also used by explicitly declared columns. ^If
-** the table has a column of type [INTEGER PRIMARY KEY] then that column
-** is another alias for the rowid.
-**
-** ^This routine returns the [rowid] of the most recent
-** successful [INSERT] into the database from the [database connection]
-** in the first argument. ^If no successful [INSERT]s
-** have ever occurred on that database connection, zero is returned.
-**
-** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
-** row is returned by this routine as long as the trigger is running.
-** But once the trigger terminates, the value returned by this routine
-** reverts to the last value inserted before the trigger fired.)^
-**
-** ^An [INSERT] that fails due to a constraint violation is not a
-** successful [INSERT] and does not change the value returned by this
-** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
-** and INSERT OR ABORT make no changes to the return value of this
-** routine when their insertion fails. ^(When INSERT OR REPLACE
-** encounters a constraint violation, it does not fail. The
-** INSERT continues to completion after deleting rows that caused
-** the constraint problem so INSERT OR REPLACE will always change
-** the return value of this interface.)^
-**
-** ^For the purposes of this routine, an [INSERT] is considered to
-** be successful even if it is subsequently rolled back.
-**
-** This function is accessible to SQL statements via the
-** [last_insert_rowid() SQL function].
-**
-** If a separate thread performs a new [INSERT] on the same
-** database connection while the [sqlite3_last_insert_rowid()]
-** function is running and thus changes the last insert [rowid],
-** then the value returned by [sqlite3_last_insert_rowid()] is
-** unpredictable and might not equal either the old or the new
-** last insert [rowid].
-*/
-SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
-
-/*
-** CAPI3REF: Count The Number Of Rows Modified
-**
-** ^This function returns the number of database rows that were changed
-** or inserted or deleted by the most recently completed SQL statement
-** on the [database connection] specified by the first parameter.
-** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
-** or [DELETE] statement are counted. Auxiliary changes caused by
-** triggers or [foreign key actions] are not counted.)^ Use the
-** [sqlite3_total_changes()] function to find the total number of changes
-** including changes caused by triggers and foreign key actions.
-**
-** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
-** are not counted. Only real table changes are counted.
-**
-** ^(A "row change" is a change to a single row of a single table
-** caused by an INSERT, DELETE, or UPDATE statement. Rows that
-** are changed as side effects of [REPLACE] constraint resolution,
-** rollback, ABORT processing, [DROP TABLE], or by any other
-** mechanisms do not count as direct row changes.)^
-**
-** A "trigger context" is a scope of execution that begins and
-** ends with the script of a [CREATE TRIGGER | trigger].
-** Most SQL statements are
-** evaluated outside of any trigger. This is the "top level"
-** trigger context. If a trigger fires from the top level, a
-** new trigger context is entered for the duration of that one
-** trigger. Subtriggers create subcontexts for their duration.
-**
-** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
-** not create a new trigger context.
-**
-** ^This function returns the number of direct row changes in the
-** most recent INSERT, UPDATE, or DELETE statement within the same
-** trigger context.
-**
-** ^Thus, when called from the top level, this function returns the
-** number of changes in the most recent INSERT, UPDATE, or DELETE
-** that also occurred at the top level. ^(Within the body of a trigger,
-** the sqlite3_changes() interface can be called to find the number of
-** changes in the most recently completed INSERT, UPDATE, or DELETE
-** statement within the body of the same trigger.
-** However, the number returned does not include changes
-** caused by subtriggers since those have their own context.)^
-**
-** See also the [sqlite3_total_changes()] interface, the
-** [count_changes pragma], and the [changes() SQL function].
-**
-** If a separate thread makes changes on the same database connection
-** while [sqlite3_changes()] is running then the value returned
-** is unpredictable and not meaningful.
-*/
-SQLITE_API int sqlite3_changes(sqlite3*);
-
-/*
-** CAPI3REF: Total Number Of Rows Modified
-**
-** ^This function returns the number of row changes caused by [INSERT],
-** [UPDATE] or [DELETE] statements since the [database connection] was opened.
-** ^(The count returned by sqlite3_total_changes() includes all changes
-** from all [CREATE TRIGGER | trigger] contexts and changes made by
-** [foreign key actions]. However,
-** the count does not include changes used to implement [REPLACE] constraints,
-** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
-** count does not include rows of views that fire an [INSTEAD OF trigger],
-** though if the INSTEAD OF trigger makes changes of its own, those changes
-** are counted.)^
-** ^The sqlite3_total_changes() function counts the changes as soon as
-** the statement that makes them is completed (when the statement handle
-** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
-**
-** See also the [sqlite3_changes()] interface, the
-** [count_changes pragma], and the [total_changes() SQL function].
-**
-** If a separate thread makes changes on the same database connection
-** while [sqlite3_total_changes()] is running then the value
-** returned is unpredictable and not meaningful.
-*/
-SQLITE_API int sqlite3_total_changes(sqlite3*);
-
-/*
-** CAPI3REF: Interrupt A Long-Running Query
-**
-** ^This function causes any pending database operation to abort and
-** return at its earliest opportunity. This routine is typically
-** called in response to a user action such as pressing "Cancel"
-** or Ctrl-C where the user wants a long query operation to halt
-** immediately.
-**
-** ^It is safe to call this routine from a thread different from the
-** thread that is currently running the database operation. But it
-** is not safe to call this routine with a [database connection] that
-** is closed or might close before sqlite3_interrupt() returns.
-**
-** ^If an SQL operation is very nearly finished at the time when
-** sqlite3_interrupt() is called, then it might not have an opportunity
-** to be interrupted and might continue to completion.
-**
-** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
-** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
-** that is inside an explicit transaction, then the entire transaction
-** will be rolled back automatically.
-**
-** ^The sqlite3_interrupt(D) call is in effect until all currently running
-** SQL statements on [database connection] D complete. ^Any new SQL statements
-** that are started after the sqlite3_interrupt() call and before the
-** running statements reaches zero are interrupted as if they had been
-** running prior to the sqlite3_interrupt() call. ^New SQL statements
-** that are started after the running statement count reaches zero are
-** not effected by the sqlite3_interrupt().
-** ^A call to sqlite3_interrupt(D) that occurs when there are no running
-** SQL statements is a no-op and has no effect on SQL statements
-** that are started after the sqlite3_interrupt() call returns.
-**
-** If the database connection closes while [sqlite3_interrupt()]
-** is running then bad things will likely happen.
-*/
-SQLITE_API void sqlite3_interrupt(sqlite3*);
-
-/*
-** CAPI3REF: Determine If An SQL Statement Is Complete
-**
-** These routines are useful during command-line input to determine if the
-** currently entered text seems to form a complete SQL statement or
-** if additional input is needed before sending the text into
-** SQLite for parsing. ^These routines return 1 if the input string
-** appears to be a complete SQL statement. ^A statement is judged to be
-** complete if it ends with a semicolon token and is not a prefix of a
-** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
-** string literals or quoted identifier names or comments are not
-** independent tokens (they are part of the token in which they are
-** embedded) and thus do not count as a statement terminator. ^Whitespace
-** and comments that follow the final semicolon are ignored.
-**
-** ^These routines return 0 if the statement is incomplete. ^If a
-** memory allocation fails, then SQLITE_NOMEM is returned.
-**
-** ^These routines do not parse the SQL statements thus
-** will not detect syntactically incorrect SQL.
-**
-** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
-** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
-** automatically by sqlite3_complete16(). If that initialization fails,
-** then the return value from sqlite3_complete16() will be non-zero
-** regardless of whether or not the input SQL is complete.)^
-**
-** The input to [sqlite3_complete()] must be a zero-terminated
-** UTF-8 string.
-**
-** The input to [sqlite3_complete16()] must be a zero-terminated
-** UTF-16 string in native byte order.
-*/
-SQLITE_API int sqlite3_complete(const char *sql);
-SQLITE_API int sqlite3_complete16(const void *sql);
-
-/*
-** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
-**
-** ^This routine sets a callback function that might be invoked whenever
-** an attempt is made to open a database table that another thread
-** or process has locked.
-**
-** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
-** is returned immediately upon encountering the lock. ^If the busy callback
-** is not NULL, then the callback might be invoked with two arguments.
-**
-** ^The first argument to the busy handler is a copy of the void* pointer which
-** is the third argument to sqlite3_busy_handler(). ^The second argument to
-** the busy handler callback is the number of times that the busy handler has
-** been invoked for this locking event. ^If the
-** busy callback returns 0, then no additional attempts are made to
-** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
-** ^If the callback returns non-zero, then another attempt
-** is made to open the database for reading and the cycle repeats.
-**
-** The presence of a busy handler does not guarantee that it will be invoked
-** when there is lock contention. ^If SQLite determines that invoking the busy
-** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
-** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
-** Consider a scenario where one process is holding a read lock that
-** it is trying to promote to a reserved lock and
-** a second process is holding a reserved lock that it is trying
-** to promote to an exclusive lock. The first process cannot proceed
-** because it is blocked by the second and the second process cannot
-** proceed because it is blocked by the first. If both processes
-** invoke the busy handlers, neither will make any progress. Therefore,
-** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
-** will induce the first process to release its read lock and allow
-** the second process to proceed.
-**
-** ^The default busy callback is NULL.
-**
-** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
-** when SQLite is in the middle of a large transaction where all the
-** changes will not fit into the in-memory cache. SQLite will
-** already hold a RESERVED lock on the database file, but it needs
-** to promote this lock to EXCLUSIVE so that it can spill cache
-** pages into the database file without harm to concurrent
-** readers. ^If it is unable to promote the lock, then the in-memory
-** cache will be left in an inconsistent state and so the error
-** code is promoted from the relatively benign [SQLITE_BUSY] to
-** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion
-** forces an automatic rollback of the changes. See the
-**
-** CorruptionFollowingBusyError wiki page for a discussion of why
-** this is important.
-**
-** ^(There can only be a single busy handler defined for each
-** [database connection]. Setting a new busy handler clears any
-** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
-** will also set or clear the busy handler.
-**
-** The busy callback should not take any actions which modify the
-** database connection that invoked the busy handler. Any such actions
-** result in undefined behavior.
-**
-** A busy handler must not close the database connection
-** or [prepared statement] that invoked the busy handler.
-*/
-SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
-
-/*
-** CAPI3REF: Set A Busy Timeout
-**
-** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
-** for a specified amount of time when a table is locked. ^The handler
-** will sleep multiple times until at least "ms" milliseconds of sleeping
-** have accumulated. ^After at least "ms" milliseconds of sleeping,
-** the handler returns 0 which causes [sqlite3_step()] to return
-** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
-**
-** ^Calling this routine with an argument less than or equal to zero
-** turns off all busy handlers.
-**
-** ^(There can only be a single busy handler for a particular
-** [database connection] any any given moment. If another busy handler
-** was defined (using [sqlite3_busy_handler()]) prior to calling
-** this routine, that other busy handler is cleared.)^
-*/
-SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
-
-/*
-** CAPI3REF: Convenience Routines For Running Queries
-**
-** Definition: A result table is memory data structure created by the
-** [sqlite3_get_table()] interface. A result table records the
-** complete query results from one or more queries.
-**
-** The table conceptually has a number of rows and columns. But
-** these numbers are not part of the result table itself. These
-** numbers are obtained separately. Let N be the number of rows
-** and M be the number of columns.
-**
-** A result table is an array of pointers to zero-terminated UTF-8 strings.
-** There are (N+1)*M elements in the array. The first M pointers point
-** to zero-terminated strings that contain the names of the columns.
-** The remaining entries all point to query results. NULL values result
-** in NULL pointers. All other values are in their UTF-8 zero-terminated
-** string representation as returned by [sqlite3_column_text()].
-**
-** A result table might consist of one or more memory allocations.
-** It is not safe to pass a result table directly to [sqlite3_free()].
-** A result table should be deallocated using [sqlite3_free_table()].
-**
-** As an example of the result table format, suppose a query result
-** is as follows:
-**
-**
-** Name | Age
-** -----------------------
-** Alice | 43
-** Bob | 28
-** Cindy | 21
-**
-**
-** There are two column (M==2) and three rows (N==3). Thus the
-** result table has 8 entries. Suppose the result table is stored
-** in an array names azResult. Then azResult holds this content:
-**
-**
-**
-** ^The sqlite3_get_table() function evaluates one or more
-** semicolon-separated SQL statements in the zero-terminated UTF-8
-** string of its 2nd parameter and returns a result table to the
-** pointer given in its 3rd parameter.
-**
-** After the application has finished with the result from sqlite3_get_table(),
-** it should pass the result table pointer to sqlite3_free_table() in order to
-** release the memory that was malloced. Because of the way the
-** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
-** function must not try to call [sqlite3_free()] directly. Only
-** [sqlite3_free_table()] is able to release the memory properly and safely.
-**
-** ^(The sqlite3_get_table() interface is implemented as a wrapper around
-** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
-** to any internal data structures of SQLite. It uses only the public
-** interface defined here. As a consequence, errors that occur in the
-** wrapper layer outside of the internal [sqlite3_exec()] call are not
-** reflected in subsequent calls to [sqlite3_errcode()] or
-** [sqlite3_errmsg()].)^
-*/
-SQLITE_API int sqlite3_get_table(
- sqlite3 *db, /* An open database */
- const char *zSql, /* SQL to be evaluated */
- char ***pazResult, /* Results of the query */
- int *pnRow, /* Number of result rows written here */
- int *pnColumn, /* Number of result columns written here */
- char **pzErrmsg /* Error msg written here */
-);
-SQLITE_API void sqlite3_free_table(char **result);
-
-/*
-** CAPI3REF: Formatted String Printing Functions
-**
-** These routines are work-alikes of the "printf()" family of functions
-** from the standard C library.
-**
-** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
-** results into memory obtained from [sqlite3_malloc()].
-** The strings returned by these two routines should be
-** released by [sqlite3_free()]. ^Both routines return a
-** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
-** memory to hold the resulting string.
-**
-** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
-** the standard C library. The result is written into the
-** buffer supplied as the second parameter whose size is given by
-** the first parameter. Note that the order of the
-** first two parameters is reversed from snprintf().)^ This is an
-** historical accident that cannot be fixed without breaking
-** backwards compatibility. ^(Note also that sqlite3_snprintf()
-** returns a pointer to its buffer instead of the number of
-** characters actually written into the buffer.)^ We admit that
-** the number of characters written would be a more useful return
-** value but we cannot change the implementation of sqlite3_snprintf()
-** now without breaking compatibility.
-**
-** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
-** guarantees that the buffer is always zero-terminated. ^The first
-** parameter "n" is the total size of the buffer, including space for
-** the zero terminator. So the longest string that can be completely
-** written will be n-1 characters.
-**
-** These routines all implement some additional formatting
-** options that are useful for constructing SQL statements.
-** All of the usual printf() formatting options apply. In addition, there
-** is are "%q", "%Q", and "%z" options.
-**
-** ^(The %q option works like %s in that it substitutes a null-terminated
-** string from the argument list. But %q also doubles every '\'' character.
-** %q is designed for use inside a string literal.)^ By doubling each '\''
-** character it escapes that character and allows it to be inserted into
-** the string.
-**
-** For example, assume the string variable zText contains text as follows:
-**
-**
-** char *zText = "It's a happy day!";
-**
-**
-** One can use this text in an SQL statement as follows:
-**
-**
-**
-** Because the %q format string is used, the '\'' character in zText
-** is escaped and the SQL generated is as follows:
-**
-**
-** INSERT INTO table1 VALUES('It''s a happy day!')
-**
-**
-** This is correct. Had we used %s instead of %q, the generated SQL
-** would have looked like this:
-**
-**
-** INSERT INTO table1 VALUES('It's a happy day!');
-**
-**
-** This second example is an SQL syntax error. As a general rule you should
-** always use %q instead of %s when inserting text into a string literal.
-**
-** ^(The %Q option works like %q except it also adds single quotes around
-** the outside of the total string. Additionally, if the parameter in the
-** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
-** single quotes).)^ So, for example, one could say:
-**
-**
-**
-** The code above will render a correct SQL statement in the zSQL
-** variable even if the zText variable is a NULL pointer.
-**
-** ^(The "%z" formatting option works like "%s" but with the
-** addition that after the string has been read and copied into
-** the result, [sqlite3_free()] is called on the input string.)^
-*/
-SQLITE_API char *sqlite3_mprintf(const char*,...);
-SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
-SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
-
-/*
-** CAPI3REF: Memory Allocation Subsystem
-**
-** The SQLite core uses these three routines for all of its own
-** internal memory allocation needs. "Core" in the previous sentence
-** does not include operating-system specific VFS implementation. The
-** Windows VFS uses native malloc() and free() for some operations.
-**
-** ^The sqlite3_malloc() routine returns a pointer to a block
-** of memory at least N bytes in length, where N is the parameter.
-** ^If sqlite3_malloc() is unable to obtain sufficient free
-** memory, it returns a NULL pointer. ^If the parameter N to
-** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
-** a NULL pointer.
-**
-** ^Calling sqlite3_free() with a pointer previously returned
-** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
-** that it might be reused. ^The sqlite3_free() routine is
-** a no-op if is called with a NULL pointer. Passing a NULL pointer
-** to sqlite3_free() is harmless. After being freed, memory
-** should neither be read nor written. Even reading previously freed
-** memory might result in a segmentation fault or other severe error.
-** Memory corruption, a segmentation fault, or other severe error
-** might result if sqlite3_free() is called with a non-NULL pointer that
-** was not obtained from sqlite3_malloc() or sqlite3_realloc().
-**
-** ^(The sqlite3_realloc() interface attempts to resize a
-** prior memory allocation to be at least N bytes, where N is the
-** second parameter. The memory allocation to be resized is the first
-** parameter.)^ ^ If the first parameter to sqlite3_realloc()
-** is a NULL pointer then its behavior is identical to calling
-** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
-** ^If the second parameter to sqlite3_realloc() is zero or
-** negative then the behavior is exactly the same as calling
-** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
-** ^sqlite3_realloc() returns a pointer to a memory allocation
-** of at least N bytes in size or NULL if sufficient memory is unavailable.
-** ^If M is the size of the prior allocation, then min(N,M) bytes
-** of the prior allocation are copied into the beginning of buffer returned
-** by sqlite3_realloc() and the prior allocation is freed.
-** ^If sqlite3_realloc() returns NULL, then the prior allocation
-** is not freed.
-**
-** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
-** is always aligned to at least an 8 byte boundary.
-**
-** In SQLite version 3.5.0 and 3.5.1, it was possible to define
-** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
-** implementation of these routines to be omitted. That capability
-** is no longer provided. Only built-in memory allocators can be used.
-**
-** The Windows OS interface layer calls
-** the system malloc() and free() directly when converting
-** filenames between the UTF-8 encoding used by SQLite
-** and whatever filename encoding is used by the particular Windows
-** installation. Memory allocation errors are detected, but
-** they are reported back as [SQLITE_CANTOPEN] or
-** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
-**
-** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
-** must be either NULL or else pointers obtained from a prior
-** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
-** not yet been released.
-**
-** The application must not read or write any part of
-** a block of memory after it has been released using
-** [sqlite3_free()] or [sqlite3_realloc()].
-*/
-SQLITE_API void *sqlite3_malloc(int);
-SQLITE_API void *sqlite3_realloc(void*, int);
-SQLITE_API void sqlite3_free(void*);
-
-/*
-** CAPI3REF: Memory Allocator Statistics
-**
-** SQLite provides these two interfaces for reporting on the status
-** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
-** routines, which form the built-in memory allocation subsystem.
-**
-** ^The [sqlite3_memory_used()] routine returns the number of bytes
-** of memory currently outstanding (malloced but not freed).
-** ^The [sqlite3_memory_highwater()] routine returns the maximum
-** value of [sqlite3_memory_used()] since the high-water mark
-** was last reset. ^The values returned by [sqlite3_memory_used()] and
-** [sqlite3_memory_highwater()] include any overhead
-** added by SQLite in its implementation of [sqlite3_malloc()],
-** but not overhead added by the any underlying system library
-** routines that [sqlite3_malloc()] may call.
-**
-** ^The memory high-water mark is reset to the current value of
-** [sqlite3_memory_used()] if and only if the parameter to
-** [sqlite3_memory_highwater()] is true. ^The value returned
-** by [sqlite3_memory_highwater(1)] is the high-water mark
-** prior to the reset.
-*/
-SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
-SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
-
-/*
-** CAPI3REF: Pseudo-Random Number Generator
-**
-** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
-** select random [ROWID | ROWIDs] when inserting new records into a table that
-** already uses the largest possible [ROWID]. The PRNG is also used for
-** the build-in random() and randomblob() SQL functions. This interface allows
-** applications to access the same PRNG for other purposes.
-**
-** ^A call to this routine stores N bytes of randomness into buffer P.
-**
-** ^The first time this routine is invoked (either internally or by
-** the application) the PRNG is seeded using randomness obtained
-** from the xRandomness method of the default [sqlite3_vfs] object.
-** ^On all subsequent invocations, the pseudo-randomness is generated
-** internally and without recourse to the [sqlite3_vfs] xRandomness
-** method.
-*/
-SQLITE_API void sqlite3_randomness(int N, void *P);
-
-/*
-** CAPI3REF: Compile-Time Authorization Callbacks
-**
-** ^This routine registers a authorizer callback with a particular
-** [database connection], supplied in the first argument.
-** ^The authorizer callback is invoked as SQL statements are being compiled
-** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
-** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
-** points during the compilation process, as logic is being created
-** to perform various actions, the authorizer callback is invoked to
-** see if those actions are allowed. ^The authorizer callback should
-** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
-** specific action but allow the SQL statement to continue to be
-** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
-** rejected with an error. ^If the authorizer callback returns
-** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
-** then the [sqlite3_prepare_v2()] or equivalent call that triggered
-** the authorizer will fail with an error message.
-**
-** When the callback returns [SQLITE_OK], that means the operation
-** requested is ok. ^When the callback returns [SQLITE_DENY], the
-** [sqlite3_prepare_v2()] or equivalent call that triggered the
-** authorizer will fail with an error message explaining that
-** access is denied.
-**
-** ^The first parameter to the authorizer callback is a copy of the third
-** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
-** to the callback is an integer [SQLITE_COPY | action code] that specifies
-** the particular action to be authorized. ^The third through sixth parameters
-** to the callback are zero-terminated strings that contain additional
-** details about the action to be authorized.
-**
-** ^If the action code is [SQLITE_READ]
-** and the callback returns [SQLITE_IGNORE] then the
-** [prepared statement] statement is constructed to substitute
-** a NULL value in place of the table column that would have
-** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
-** return can be used to deny an untrusted user access to individual
-** columns of a table.
-** ^If the action code is [SQLITE_DELETE] and the callback returns
-** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
-** [truncate optimization] is disabled and all rows are deleted individually.
-**
-** An authorizer is used when [sqlite3_prepare | preparing]
-** SQL statements from an untrusted source, to ensure that the SQL statements
-** do not try to access data they are not allowed to see, or that they do not
-** try to execute malicious statements that damage the database. For
-** example, an application may allow a user to enter arbitrary
-** SQL queries for evaluation by a database. But the application does
-** not want the user to be able to make arbitrary changes to the
-** database. An authorizer could then be put in place while the
-** user-entered SQL is being [sqlite3_prepare | prepared] that
-** disallows everything except [SELECT] statements.
-**
-** Applications that need to process SQL from untrusted sources
-** might also consider lowering resource limits using [sqlite3_limit()]
-** and limiting database size using the [max_page_count] [PRAGMA]
-** in addition to using an authorizer.
-**
-** ^(Only a single authorizer can be in place on a database connection
-** at a time. Each call to sqlite3_set_authorizer overrides the
-** previous call.)^ ^Disable the authorizer by installing a NULL callback.
-** The authorizer is disabled by default.
-**
-** The authorizer callback must not do anything that will modify
-** the database connection that invoked the authorizer callback.
-** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
-** database connections for the meaning of "modify" in this paragraph.
-**
-** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
-** statement might be re-prepared during [sqlite3_step()] due to a
-** schema change. Hence, the application should ensure that the
-** correct authorizer callback remains in place during the [sqlite3_step()].
-**
-** ^Note that the authorizer callback is invoked only during
-** [sqlite3_prepare()] or its variants. Authorization is not
-** performed during statement evaluation in [sqlite3_step()], unless
-** as stated in the previous paragraph, sqlite3_step() invokes
-** sqlite3_prepare_v2() to reprepare a statement after a schema change.
-*/
-SQLITE_API int sqlite3_set_authorizer(
- sqlite3*,
- int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
- void *pUserData
-);
-
-/*
-** CAPI3REF: Authorizer Return Codes
-**
-** The [sqlite3_set_authorizer | authorizer callback function] must
-** return either [SQLITE_OK] or one of these two constants in order
-** to signal SQLite whether or not the action is permitted. See the
-** [sqlite3_set_authorizer | authorizer documentation] for additional
-** information.
-*/
-#define SQLITE_DENY 1 /* Abort the SQL statement with an error */
-#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
-
-/*
-** CAPI3REF: Authorizer Action Codes
-**
-** The [sqlite3_set_authorizer()] interface registers a callback function
-** that is invoked to authorize certain SQL statement actions. The
-** second parameter to the callback is an integer code that specifies
-** what action is being authorized. These are the integer action codes that
-** the authorizer callback may be passed.
-**
-** These action code values signify what kind of operation is to be
-** authorized. The 3rd and 4th parameters to the authorization
-** callback function will be parameters or NULL depending on which of these
-** codes is used as the second parameter. ^(The 5th parameter to the
-** authorizer callback is the name of the database ("main", "temp",
-** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
-** is the name of the inner-most trigger or view that is responsible for
-** the access attempt or NULL if this access attempt is directly from
-** top-level SQL code.
-*/
-/******************************************* 3rd ************ 4th ***********/
-#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
-#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
-#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
-#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
-#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
-#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
-#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
-#define SQLITE_CREATE_VIEW 8 /* View Name NULL */
-#define SQLITE_DELETE 9 /* Table Name NULL */
-#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
-#define SQLITE_DROP_TABLE 11 /* Table Name NULL */
-#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
-#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
-#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
-#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
-#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
-#define SQLITE_DROP_VIEW 17 /* View Name NULL */
-#define SQLITE_INSERT 18 /* Table Name NULL */
-#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
-#define SQLITE_READ 20 /* Table Name Column Name */
-#define SQLITE_SELECT 21 /* NULL NULL */
-#define SQLITE_TRANSACTION 22 /* Operation NULL */
-#define SQLITE_UPDATE 23 /* Table Name Column Name */
-#define SQLITE_ATTACH 24 /* Filename NULL */
-#define SQLITE_DETACH 25 /* Database Name NULL */
-#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
-#define SQLITE_REINDEX 27 /* Index Name NULL */
-#define SQLITE_ANALYZE 28 /* Table Name NULL */
-#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
-#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
-#define SQLITE_FUNCTION 31 /* NULL Function Name */
-#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
-#define SQLITE_COPY 0 /* No longer used */
-
-/*
-** CAPI3REF: Tracing And Profiling Functions
-** EXPERIMENTAL
-**
-** These routines register callback functions that can be used for
-** tracing and profiling the execution of SQL statements.
-**
-** ^The callback function registered by sqlite3_trace() is invoked at
-** various times when an SQL statement is being run by [sqlite3_step()].
-** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
-** SQL statement text as the statement first begins executing.
-** ^(Additional sqlite3_trace() callbacks might occur
-** as each triggered subprogram is entered. The callbacks for triggers
-** contain a UTF-8 SQL comment that identifies the trigger.)^
-**
-** ^The callback function registered by sqlite3_profile() is invoked
-** as each SQL statement finishes. ^The profile callback contains
-** the original statement text and an estimate of wall-clock time
-** of how long that statement took to run.
-*/
-SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
-SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
- void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
-
-/*
-** CAPI3REF: Query Progress Callbacks
-**
-** ^This routine configures a callback function - the
-** progress callback - that is invoked periodically during long
-** running calls to [sqlite3_exec()], [sqlite3_step()] and
-** [sqlite3_get_table()]. An example use for this
-** interface is to keep a GUI updated during a large query.
-**
-** ^If the progress callback returns non-zero, the operation is
-** interrupted. This feature can be used to implement a
-** "Cancel" button on a GUI progress dialog box.
-**
-** The progress handler must not do anything that will modify
-** the database connection that invoked the progress handler.
-** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
-** database connections for the meaning of "modify" in this paragraph.
-**
-*/
-SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
-
-/*
-** CAPI3REF: Opening A New Database Connection
-**
-** ^These routines open an SQLite database file whose name is given by the
-** filename argument. ^The filename argument is interpreted as UTF-8 for
-** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
-** order for sqlite3_open16(). ^(A [database connection] handle is usually
-** returned in *ppDb, even if an error occurs. The only exception is that
-** if SQLite is unable to allocate memory to hold the [sqlite3] object,
-** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
-** object.)^ ^(If the database is opened (and/or created) successfully, then
-** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
-** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
-** an English language description of the error following a failure of any
-** of the sqlite3_open() routines.
-**
-** ^The default encoding for the database will be UTF-8 if
-** sqlite3_open() or sqlite3_open_v2() is called and
-** UTF-16 in the native byte order if sqlite3_open16() is used.
-**
-** Whether or not an error occurs when it is opened, resources
-** associated with the [database connection] handle should be released by
-** passing it to [sqlite3_close()] when it is no longer required.
-**
-** The sqlite3_open_v2() interface works like sqlite3_open()
-** except that it accepts two additional parameters for additional control
-** over the new database connection. ^(The flags parameter to
-** sqlite3_open_v2() can take one of
-** the following three values, optionally combined with the
-** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
-** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
-**
-**
-** ^(
[SQLITE_OPEN_READONLY]
-**
The database is opened in read-only mode. If the database does not
-** already exist, an error is returned.
)^
-**
-** ^(
[SQLITE_OPEN_READWRITE]
-**
The database is opened for reading and writing if possible, or reading
-** only if the file is write protected by the operating system. In either
-** case the database must already exist, otherwise an error is returned.
)^
-**
-** ^(
[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
-**
The database is opened for reading and writing, and is creates it if
-** it does not already exist. This is the behavior that is always used for
-** sqlite3_open() and sqlite3_open16().
)^
-**
-**
-** If the 3rd parameter to sqlite3_open_v2() is not one of the
-** combinations shown above or one of the combinations shown above combined
-** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
-** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
-** then the behavior is undefined.
-**
-** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
-** opens in the multi-thread [threading mode] as long as the single-thread
-** mode has not been set at compile-time or start-time. ^If the
-** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
-** in the serialized [threading mode] unless single-thread was
-** previously selected at compile-time or start-time.
-** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
-** eligible to use [shared cache mode], regardless of whether or not shared
-** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
-** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
-** participate in [shared cache mode] even if it is enabled.
-**
-** ^If the filename is ":memory:", then a private, temporary in-memory database
-** is created for the connection. ^This in-memory database will vanish when
-** the database connection is closed. Future versions of SQLite might
-** make use of additional special filenames that begin with the ":" character.
-** It is recommended that when a database filename actually does begin with
-** a ":" character you should prefix the filename with a pathname such as
-** "./" to avoid ambiguity.
-**
-** ^If the filename is an empty string, then a private, temporary
-** on-disk database will be created. ^This private database will be
-** automatically deleted as soon as the database connection is closed.
-**
-** ^The fourth parameter to sqlite3_open_v2() is the name of the
-** [sqlite3_vfs] object that defines the operating system interface that
-** the new database connection should use. ^If the fourth parameter is
-** a NULL pointer then the default [sqlite3_vfs] object is used.
-**
-** Note to Windows users: The encoding used for the filename argument
-** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
-** codepage is currently defined. Filenames containing international
-** characters must be converted to UTF-8 prior to passing them into
-** sqlite3_open() or sqlite3_open_v2().
-*/
-SQLITE_API int sqlite3_open(
- const char *filename, /* Database filename (UTF-8) */
- sqlite3 **ppDb /* OUT: SQLite db handle */
-);
-SQLITE_API int sqlite3_open16(
- const void *filename, /* Database filename (UTF-16) */
- sqlite3 **ppDb /* OUT: SQLite db handle */
-);
-SQLITE_API int sqlite3_open_v2(
- const char *filename, /* Database filename (UTF-8) */
- sqlite3 **ppDb, /* OUT: SQLite db handle */
- int flags, /* Flags */
- const char *zVfs /* Name of VFS module to use */
-);
-
-/*
-** CAPI3REF: Error Codes And Messages
-**
-** ^The sqlite3_errcode() interface returns the numeric [result code] or
-** [extended result code] for the most recent failed sqlite3_* API call
-** associated with a [database connection]. If a prior API call failed
-** but the most recent API call succeeded, the return value from
-** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
-** interface is the same except that it always returns the
-** [extended result code] even when extended result codes are
-** disabled.
-**
-** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
-** text that describes the error, as either UTF-8 or UTF-16 respectively.
-** ^(Memory to hold the error message string is managed internally.
-** The application does not need to worry about freeing the result.
-** However, the error string might be overwritten or deallocated by
-** subsequent calls to other SQLite interface functions.)^
-**
-** When the serialized [threading mode] is in use, it might be the
-** case that a second error occurs on a separate thread in between
-** the time of the first error and the call to these interfaces.
-** When that happens, the second error will be reported since these
-** interfaces always report the most recent result. To avoid
-** this, each thread can obtain exclusive use of the [database connection] D
-** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
-** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
-** all calls to the interfaces listed here are completed.
-**
-** If an interface fails with SQLITE_MISUSE, that means the interface
-** was invoked incorrectly by the application. In that case, the
-** error code and message may or may not be set.
-*/
-SQLITE_API int sqlite3_errcode(sqlite3 *db);
-SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
-SQLITE_API const char *sqlite3_errmsg(sqlite3*);
-SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
-
-/*
-** CAPI3REF: SQL Statement Object
-** KEYWORDS: {prepared statement} {prepared statements}
-**
-** An instance of this object represents a single SQL statement.
-** This object is variously known as a "prepared statement" or a
-** "compiled SQL statement" or simply as a "statement".
-**
-** The life of a statement object goes something like this:
-**
-**
-**
Create the object using [sqlite3_prepare_v2()] or a related
-** function.
-**
Bind values to [host parameters] using the sqlite3_bind_*()
-** interfaces.
-**
Run the SQL by calling [sqlite3_step()] one or more times.
-**
Reset the statement using [sqlite3_reset()] then go back
-** to step 2. Do this zero or more times.
-**
Destroy the object using [sqlite3_finalize()].
-**
-**
-** Refer to documentation on individual methods above for additional
-** information.
-*/
-typedef struct sqlite3_stmt sqlite3_stmt;
-
-/*
-** CAPI3REF: Run-time Limits
-**
-** ^(This interface allows the size of various constructs to be limited
-** on a connection by connection basis. The first parameter is the
-** [database connection] whose limit is to be set or queried. The
-** second parameter is one of the [limit categories] that define a
-** class of constructs to be size limited. The third parameter is the
-** new limit for that construct. The function returns the old limit.)^
-**
-** ^If the new limit is a negative number, the limit is unchanged.
-** ^(For the limit category of SQLITE_LIMIT_XYZ there is a
-** [limits | hard upper bound]
-** set by a compile-time C preprocessor macro named
-** [limits | SQLITE_MAX_XYZ].
-** (The "_LIMIT_" in the name is changed to "_MAX_".))^
-** ^Attempts to increase a limit above its hard upper bound are
-** silently truncated to the hard upper bound.
-**
-** Run-time limits are intended for use in applications that manage
-** both their own internal database and also databases that are controlled
-** by untrusted external sources. An example application might be a
-** web browser that has its own databases for storing history and
-** separate databases controlled by JavaScript applications downloaded
-** off the Internet. The internal databases can be given the
-** large, default limits. Databases managed by external sources can
-** be given much smaller limits designed to prevent a denial of service
-** attack. Developers might also want to use the [sqlite3_set_authorizer()]
-** interface to further control untrusted SQL. The size of the database
-** created by an untrusted script can be contained using the
-** [max_page_count] [PRAGMA].
-**
-** New run-time limit categories may be added in future releases.
-*/
-SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
-
-/*
-** CAPI3REF: Run-Time Limit Categories
-** KEYWORDS: {limit category} {*limit categories}
-**
-** These constants define various performance limits
-** that can be lowered at run-time using [sqlite3_limit()].
-** The synopsis of the meanings of the various limits is shown below.
-** Additional information is available at [limits | Limits in SQLite].
-**
-**
-** ^(
SQLITE_LIMIT_LENGTH
-**
The maximum size of any string or BLOB or table row.
)^
-**
-** ^(
SQLITE_LIMIT_SQL_LENGTH
-**
The maximum length of an SQL statement, in bytes.
)^
-**
-** ^(
SQLITE_LIMIT_COLUMN
-**
The maximum number of columns in a table definition or in the
-** result set of a [SELECT] or the maximum number of columns in an index
-** or in an ORDER BY or GROUP BY clause.
)^
-**
-** ^(
SQLITE_LIMIT_EXPR_DEPTH
-**
The maximum depth of the parse tree on any expression.
)^
-**
-** ^(
SQLITE_LIMIT_COMPOUND_SELECT
-**
The maximum number of terms in a compound SELECT statement.
)^
-**
-** ^(
SQLITE_LIMIT_VDBE_OP
-**
The maximum number of instructions in a virtual machine program
-** used to implement an SQL statement.
)^
-**
-** ^(
SQLITE_LIMIT_FUNCTION_ARG
-**
The maximum number of arguments on a function.
)^
-**
-** ^(
SQLITE_LIMIT_ATTACHED
-**
The maximum number of [ATTACH | attached databases].)^
-**
-** ^(
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
-**
The maximum length of the pattern argument to the [LIKE] or
-** [GLOB] operators.
)^
-**
-** ^(
SQLITE_LIMIT_VARIABLE_NUMBER
-**
The maximum number of variables in an SQL statement that can
-** be bound.
)^
-**
-** ^(
SQLITE_LIMIT_TRIGGER_DEPTH
-**
The maximum depth of recursion for triggers.
)^
-**
-*/
-#define SQLITE_LIMIT_LENGTH 0
-#define SQLITE_LIMIT_SQL_LENGTH 1
-#define SQLITE_LIMIT_COLUMN 2
-#define SQLITE_LIMIT_EXPR_DEPTH 3
-#define SQLITE_LIMIT_COMPOUND_SELECT 4
-#define SQLITE_LIMIT_VDBE_OP 5
-#define SQLITE_LIMIT_FUNCTION_ARG 6
-#define SQLITE_LIMIT_ATTACHED 7
-#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
-#define SQLITE_LIMIT_VARIABLE_NUMBER 9
-#define SQLITE_LIMIT_TRIGGER_DEPTH 10
-
-/*
-** CAPI3REF: Compiling An SQL Statement
-** KEYWORDS: {SQL statement compiler}
-**
-** To execute an SQL query, it must first be compiled into a byte-code
-** program using one of these routines.
-**
-** The first argument, "db", is a [database connection] obtained from a
-** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
-** [sqlite3_open16()]. The database connection must not have been closed.
-**
-** The second argument, "zSql", is the statement to be compiled, encoded
-** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
-** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
-** use UTF-16.
-**
-** ^If the nByte argument is less than zero, then zSql is read up to the
-** first zero terminator. ^If nByte is non-negative, then it is the maximum
-** number of bytes read from zSql. ^When nByte is non-negative, the
-** zSql string ends at either the first '\000' or '\u0000' character or
-** the nByte-th byte, whichever comes first. If the caller knows
-** that the supplied string is nul-terminated, then there is a small
-** performance advantage to be gained by passing an nByte parameter that
-** is equal to the number of bytes in the input string including
-** the nul-terminator bytes.
-**
-** ^If pzTail is not NULL then *pzTail is made to point to the first byte
-** past the end of the first SQL statement in zSql. These routines only
-** compile the first statement in zSql, so *pzTail is left pointing to
-** what remains uncompiled.
-**
-** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
-** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
-** to NULL. ^If the input text contains no SQL (if the input is an empty
-** string or a comment) then *ppStmt is set to NULL.
-** The calling procedure is responsible for deleting the compiled
-** SQL statement using [sqlite3_finalize()] after it has finished with it.
-** ppStmt may not be NULL.
-**
-** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
-** otherwise an [error code] is returned.
-**
-** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
-** recommended for all new programs. The two older interfaces are retained
-** for backwards compatibility, but their use is discouraged.
-** ^In the "v2" interfaces, the prepared statement
-** that is returned (the [sqlite3_stmt] object) contains a copy of the
-** original SQL text. This causes the [sqlite3_step()] interface to
-** behave differently in three ways:
-**
-**
-**
-** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
-** always used to do, [sqlite3_step()] will automatically recompile the SQL
-** statement and try to run it again. ^If the schema has changed in
-** a way that makes the statement no longer valid, [sqlite3_step()] will still
-** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is
-** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the
-** error go away. Note: use [sqlite3_errmsg()] to find the text
-** of the parsing error that results in an [SQLITE_SCHEMA] return.
-**
-**
-**
-** ^When an error occurs, [sqlite3_step()] will return one of the detailed
-** [error codes] or [extended error codes]. ^The legacy behavior was that
-** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
-** and the application would have to make a second call to [sqlite3_reset()]
-** in order to find the underlying cause of the problem. With the "v2" prepare
-** interfaces, the underlying reason for the error is returned immediately.
-**
-**
-**
-** ^If the value of a [parameter | host parameter] in the WHERE clause might
-** change the query plan for a statement, then the statement may be
-** automatically recompiled (as if there had been a schema change) on the first
-** [sqlite3_step()] call following any change to the
-** [sqlite3_bind_text | bindings] of the [parameter].
-**
-**
-*/
-SQLITE_API int sqlite3_prepare(
- sqlite3 *db, /* Database handle */
- const char *zSql, /* SQL statement, UTF-8 encoded */
- int nByte, /* Maximum length of zSql in bytes. */
- sqlite3_stmt **ppStmt, /* OUT: Statement handle */
- const char **pzTail /* OUT: Pointer to unused portion of zSql */
-);
-SQLITE_API int sqlite3_prepare_v2(
- sqlite3 *db, /* Database handle */
- const char *zSql, /* SQL statement, UTF-8 encoded */
- int nByte, /* Maximum length of zSql in bytes. */
- sqlite3_stmt **ppStmt, /* OUT: Statement handle */
- const char **pzTail /* OUT: Pointer to unused portion of zSql */
-);
-SQLITE_API int sqlite3_prepare16(
- sqlite3 *db, /* Database handle */
- const void *zSql, /* SQL statement, UTF-16 encoded */
- int nByte, /* Maximum length of zSql in bytes. */
- sqlite3_stmt **ppStmt, /* OUT: Statement handle */
- const void **pzTail /* OUT: Pointer to unused portion of zSql */
-);
-SQLITE_API int sqlite3_prepare16_v2(
- sqlite3 *db, /* Database handle */
- const void *zSql, /* SQL statement, UTF-16 encoded */
- int nByte, /* Maximum length of zSql in bytes. */
- sqlite3_stmt **ppStmt, /* OUT: Statement handle */
- const void **pzTail /* OUT: Pointer to unused portion of zSql */
-);
-
-/*
-** CAPI3REF: Retrieving Statement SQL
-**
-** ^This interface can be used to retrieve a saved copy of the original
-** SQL text used to create a [prepared statement] if that statement was
-** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
-*/
-SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
-
-/*
-** CAPI3REF: Dynamically Typed Value Object
-** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
-**
-** SQLite uses the sqlite3_value object to represent all values
-** that can be stored in a database table. SQLite uses dynamic typing
-** for the values it stores. ^Values stored in sqlite3_value objects
-** can be integers, floating point values, strings, BLOBs, or NULL.
-**
-** An sqlite3_value object may be either "protected" or "unprotected".
-** Some interfaces require a protected sqlite3_value. Other interfaces
-** will accept either a protected or an unprotected sqlite3_value.
-** Every interface that accepts sqlite3_value arguments specifies
-** whether or not it requires a protected sqlite3_value.
-**
-** The terms "protected" and "unprotected" refer to whether or not
-** a mutex is held. A internal mutex is held for a protected
-** sqlite3_value object but no mutex is held for an unprotected
-** sqlite3_value object. If SQLite is compiled to be single-threaded
-** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
-** or if SQLite is run in one of reduced mutex modes
-** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
-** then there is no distinction between protected and unprotected
-** sqlite3_value objects and they can be used interchangeably. However,
-** for maximum code portability it is recommended that applications
-** still make the distinction between between protected and unprotected
-** sqlite3_value objects even when not strictly required.
-**
-** ^The sqlite3_value objects that are passed as parameters into the
-** implementation of [application-defined SQL functions] are protected.
-** ^The sqlite3_value object returned by
-** [sqlite3_column_value()] is unprotected.
-** Unprotected sqlite3_value objects may only be used with
-** [sqlite3_result_value()] and [sqlite3_bind_value()].
-** The [sqlite3_value_blob | sqlite3_value_type()] family of
-** interfaces require protected sqlite3_value objects.
-*/
-typedef struct Mem sqlite3_value;
-
-/*
-** CAPI3REF: SQL Function Context Object
-**
-** The context in which an SQL function executes is stored in an
-** sqlite3_context object. ^A pointer to an sqlite3_context object
-** is always first parameter to [application-defined SQL functions].
-** The application-defined SQL function implementation will pass this
-** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
-** [sqlite3_aggregate_context()], [sqlite3_user_data()],
-** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
-** and/or [sqlite3_set_auxdata()].
-*/
-typedef struct sqlite3_context sqlite3_context;
-
-/*
-** CAPI3REF: Binding Values To Prepared Statements
-** KEYWORDS: {host parameter} {host parameters} {host parameter name}
-** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
-**
-** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
-** literals may be replaced by a [parameter] that matches one of following
-** templates:
-**
-**
-**
?
-**
?NNN
-**
:VVV
-**
@VVV
-**
$VVV
-**
-**
-** In the templates above, NNN represents an integer literal,
-** and VVV represents an alphanumeric identifer.)^ ^The values of these
-** parameters (also called "host parameter names" or "SQL parameters")
-** can be set using the sqlite3_bind_*() routines defined here.
-**
-** ^The first argument to the sqlite3_bind_*() routines is always
-** a pointer to the [sqlite3_stmt] object returned from
-** [sqlite3_prepare_v2()] or its variants.
-**
-** ^The second argument is the index of the SQL parameter to be set.
-** ^The leftmost SQL parameter has an index of 1. ^When the same named
-** SQL parameter is used more than once, second and subsequent
-** occurrences have the same index as the first occurrence.
-** ^The index for named parameters can be looked up using the
-** [sqlite3_bind_parameter_index()] API if desired. ^The index
-** for "?NNN" parameters is the value of NNN.
-** ^The NNN value must be between 1 and the [sqlite3_limit()]
-** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
-**
-** ^The third argument is the value to bind to the parameter.
-**
-** ^(In those routines that have a fourth argument, its value is the
-** number of bytes in the parameter. To be clear: the value is the
-** number of bytes in the value, not the number of characters.)^
-** ^If the fourth parameter is negative, the length of the string is
-** the number of bytes up to the first zero terminator.
-**
-** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
-** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
-** string after SQLite has finished with it. ^If the fifth argument is
-** the special value [SQLITE_STATIC], then SQLite assumes that the
-** information is in static, unmanaged space and does not need to be freed.
-** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
-** SQLite makes its own private copy of the data immediately, before
-** the sqlite3_bind_*() routine returns.
-**
-** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
-** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
-** (just an integer to hold its size) while it is being processed.
-** Zeroblobs are intended to serve as placeholders for BLOBs whose
-** content is later written using
-** [sqlite3_blob_open | incremental BLOB I/O] routines.
-** ^A negative value for the zeroblob results in a zero-length BLOB.
-**
-** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
-** for the [prepared statement] or with a prepared statement for which
-** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
-** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
-** routine is passed a [prepared statement] that has been finalized, the
-** result is undefined and probably harmful.
-**
-** ^Bindings are not cleared by the [sqlite3_reset()] routine.
-** ^Unbound parameters are interpreted as NULL.
-**
-** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
-** [error code] if anything goes wrong.
-** ^[SQLITE_RANGE] is returned if the parameter
-** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
-**
-** See also: [sqlite3_bind_parameter_count()],
-** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
-*/
-SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
-SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
-SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
-SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
-SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
-SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
-SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
-SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
-SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
-
-/*
-** CAPI3REF: Number Of SQL Parameters
-**
-** ^This routine can be used to find the number of [SQL parameters]
-** in a [prepared statement]. SQL parameters are tokens of the
-** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
-** placeholders for values that are [sqlite3_bind_blob | bound]
-** to the parameters at a later time.
-**
-** ^(This routine actually returns the index of the largest (rightmost)
-** parameter. For all forms except ?NNN, this will correspond to the
-** number of unique parameters. If parameters of the ?NNN form are used,
-** there may be gaps in the list.)^
-**
-** See also: [sqlite3_bind_blob|sqlite3_bind()],
-** [sqlite3_bind_parameter_name()], and
-** [sqlite3_bind_parameter_index()].
-*/
-SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
-
-/*
-** CAPI3REF: Name Of A Host Parameter
-**
-** ^The sqlite3_bind_parameter_name(P,N) interface returns
-** the name of the N-th [SQL parameter] in the [prepared statement] P.
-** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
-** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
-** respectively.
-** In other words, the initial ":" or "$" or "@" or "?"
-** is included as part of the name.)^
-** ^Parameters of the form "?" without a following integer have no name
-** and are referred to as "nameless" or "anonymous parameters".
-**
-** ^The first host parameter has an index of 1, not 0.
-**
-** ^If the value N is out of range or if the N-th parameter is
-** nameless, then NULL is returned. ^The returned string is
-** always in UTF-8 encoding even if the named parameter was
-** originally specified as UTF-16 in [sqlite3_prepare16()] or
-** [sqlite3_prepare16_v2()].
-**
-** See also: [sqlite3_bind_blob|sqlite3_bind()],
-** [sqlite3_bind_parameter_count()], and
-** [sqlite3_bind_parameter_index()].
-*/
-SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
-
-/*
-** CAPI3REF: Index Of A Parameter With A Given Name
-**
-** ^Return the index of an SQL parameter given its name. ^The
-** index value returned is suitable for use as the second
-** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
-** is returned if no matching parameter is found. ^The parameter
-** name must be given in UTF-8 even if the original statement
-** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
-**
-** See also: [sqlite3_bind_blob|sqlite3_bind()],
-** [sqlite3_bind_parameter_count()], and
-** [sqlite3_bind_parameter_index()].
-*/
-SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
-
-/*
-** CAPI3REF: Reset All Bindings On A Prepared Statement
-**
-** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
-** the [sqlite3_bind_blob | bindings] on a [prepared statement].
-** ^Use this routine to reset all host parameters to NULL.
-*/
-SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
-
-/*
-** CAPI3REF: Number Of Columns In A Result Set
-**
-** ^Return the number of columns in the result set returned by the
-** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
-** statement that does not return data (for example an [UPDATE]).
-*/
-SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
-
-/*
-** CAPI3REF: Column Names In A Result Set
-**
-** ^These routines return the name assigned to a particular column
-** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
-** interface returns a pointer to a zero-terminated UTF-8 string
-** and sqlite3_column_name16() returns a pointer to a zero-terminated
-** UTF-16 string. ^The first parameter is the [prepared statement]
-** that implements the [SELECT] statement. ^The second parameter is the
-** column number. ^The leftmost column is number 0.
-**
-** ^The returned string pointer is valid until either the [prepared statement]
-** is destroyed by [sqlite3_finalize()] or until the next call to
-** sqlite3_column_name() or sqlite3_column_name16() on the same column.
-**
-** ^If sqlite3_malloc() fails during the processing of either routine
-** (for example during a conversion from UTF-8 to UTF-16) then a
-** NULL pointer is returned.
-**
-** ^The name of a result column is the value of the "AS" clause for
-** that column, if there is an AS clause. If there is no AS clause
-** then the name of the column is unspecified and may change from
-** one release of SQLite to the next.
-*/
-SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
-SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
-
-/*
-** CAPI3REF: Source Of Data In A Query Result
-**
-** ^These routines provide a means to determine the database, table, and
-** table column that is the origin of a particular result column in
-** [SELECT] statement.
-** ^The name of the database or table or column can be returned as
-** either a UTF-8 or UTF-16 string. ^The _database_ routines return
-** the database name, the _table_ routines return the table name, and
-** the origin_ routines return the column name.
-** ^The returned string is valid until the [prepared statement] is destroyed
-** using [sqlite3_finalize()] or until the same information is requested
-** again in a different encoding.
-**
-** ^The names returned are the original un-aliased names of the
-** database, table, and column.
-**
-** ^The first argument to these interfaces is a [prepared statement].
-** ^These functions return information about the Nth result column returned by
-** the statement, where N is the second function argument.
-** ^The left-most column is column 0 for these routines.
-**
-** ^If the Nth column returned by the statement is an expression or
-** subquery and is not a column value, then all of these functions return
-** NULL. ^These routine might also return NULL if a memory allocation error
-** occurs. ^Otherwise, they return the name of the attached database, table,
-** or column that query result column was extracted from.
-**
-** ^As with all other SQLite APIs, those whose names end with "16" return
-** UTF-16 encoded strings and the other functions return UTF-8.
-**
-** ^These APIs are only available if the library was compiled with the
-** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
-**
-** If two or more threads call one or more of these routines against the same
-** prepared statement and column at the same time then the results are
-** undefined.
-**
-** If two or more threads call one or more
-** [sqlite3_column_database_name | column metadata interfaces]
-** for the same [prepared statement] and result column
-** at the same time then the results are undefined.
-*/
-SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
-SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
-SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
-SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
-SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
-SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
-
-/*
-** CAPI3REF: Declared Datatype Of A Query Result
-**
-** ^(The first parameter is a [prepared statement].
-** If this statement is a [SELECT] statement and the Nth column of the
-** returned result set of that [SELECT] is a table column (not an
-** expression or subquery) then the declared type of the table
-** column is returned.)^ ^If the Nth column of the result set is an
-** expression or subquery, then a NULL pointer is returned.
-** ^The returned string is always UTF-8 encoded.
-**
-** ^(For example, given the database schema:
-**
-** CREATE TABLE t1(c1 VARIANT);
-**
-** and the following statement to be compiled:
-**
-** SELECT c1 + 1, c1 FROM t1;
-**
-** this routine would return the string "VARIANT" for the second result
-** column (i==1), and a NULL pointer for the first result column (i==0).)^
-**
-** ^SQLite uses dynamic run-time typing. ^So just because a column
-** is declared to contain a particular type does not mean that the
-** data stored in that column is of the declared type. SQLite is
-** strongly typed, but the typing is dynamic not static. ^Type
-** is associated with individual values, not with the containers
-** used to hold those values.
-*/
-SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
-SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
-
-/*
-** CAPI3REF: Evaluate An SQL Statement
-**
-** After a [prepared statement] has been prepared using either
-** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
-** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
-** must be called one or more times to evaluate the statement.
-**
-** The details of the behavior of the sqlite3_step() interface depend
-** on whether the statement was prepared using the newer "v2" interface
-** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
-** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
-** new "v2" interface is recommended for new applications but the legacy
-** interface will continue to be supported.
-**
-** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
-** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
-** ^With the "v2" interface, any of the other [result codes] or
-** [extended result codes] might be returned as well.
-**
-** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
-** database locks it needs to do its job. ^If the statement is a [COMMIT]
-** or occurs outside of an explicit transaction, then you can retry the
-** statement. If the statement is not a [COMMIT] and occurs within a
-** explicit transaction then you should rollback the transaction before
-** continuing.
-**
-** ^[SQLITE_DONE] means that the statement has finished executing
-** successfully. sqlite3_step() should not be called again on this virtual
-** machine without first calling [sqlite3_reset()] to reset the virtual
-** machine back to its initial state.
-**
-** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
-** is returned each time a new row of data is ready for processing by the
-** caller. The values may be accessed using the [column access functions].
-** sqlite3_step() is called again to retrieve the next row of data.
-**
-** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
-** violation) has occurred. sqlite3_step() should not be called again on
-** the VM. More information may be found by calling [sqlite3_errmsg()].
-** ^With the legacy interface, a more specific error code (for example,
-** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
-** can be obtained by calling [sqlite3_reset()] on the
-** [prepared statement]. ^In the "v2" interface,
-** the more specific error code is returned directly by sqlite3_step().
-**
-** [SQLITE_MISUSE] means that the this routine was called inappropriately.
-** Perhaps it was called on a [prepared statement] that has
-** already been [sqlite3_finalize | finalized] or on one that had
-** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
-** be the case that the same database connection is being used by two or
-** more threads at the same moment in time.
-**
-** Goofy Interface Alert: In the legacy interface, the sqlite3_step()
-** API always returns a generic error code, [SQLITE_ERROR], following any
-** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
-** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
-** specific [error codes] that better describes the error.
-** We admit that this is a goofy design. The problem has been fixed
-** with the "v2" interface. If you prepare all of your SQL statements
-** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
-** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
-** then the more specific [error codes] are returned directly
-** by sqlite3_step(). The use of the "v2" interface is recommended.
-*/
-SQLITE_API int sqlite3_step(sqlite3_stmt*);
-
-/*
-** CAPI3REF: Number of columns in a result set
-**
-** ^The sqlite3_data_count(P) the number of columns in the
-** of the result set of [prepared statement] P.
-*/
-SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
-
-/*
-** CAPI3REF: Fundamental Datatypes
-** KEYWORDS: SQLITE_TEXT
-**
-** ^(Every value in SQLite has one of five fundamental datatypes:
-**
-**
-**
64-bit signed integer
-**
64-bit IEEE floating point number
-**
string
-**
BLOB
-**
NULL
-**
)^
-**
-** These constants are codes for each of those types.
-**
-** Note that the SQLITE_TEXT constant was also used in SQLite version 2
-** for a completely different meaning. Software that links against both
-** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
-** SQLITE_TEXT.
-*/
-#define SQLITE_INTEGER 1
-#define SQLITE_FLOAT 2
-#define SQLITE_BLOB 4
-#define SQLITE_NULL 5
-#ifdef SQLITE_TEXT
-# undef SQLITE_TEXT
-#else
-# define SQLITE_TEXT 3
-#endif
-#define SQLITE3_TEXT 3
-
-/*
-** CAPI3REF: Result Values From A Query
-** KEYWORDS: {column access functions}
-**
-** These routines form the "result set" interface.
-**
-** ^These routines return information about a single column of the current
-** result row of a query. ^In every case the first argument is a pointer
-** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
-** that was returned from [sqlite3_prepare_v2()] or one of its variants)
-** and the second argument is the index of the column for which information
-** should be returned. ^The leftmost column of the result set has the index 0.
-** ^The number of columns in the result can be determined using
-** [sqlite3_column_count()].
-**
-** If the SQL statement does not currently point to a valid row, or if the
-** column index is out of range, the result is undefined.
-** These routines may only be called when the most recent call to
-** [sqlite3_step()] has returned [SQLITE_ROW] and neither
-** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
-** If any of these routines are called after [sqlite3_reset()] or
-** [sqlite3_finalize()] or after [sqlite3_step()] has returned
-** something other than [SQLITE_ROW], the results are undefined.
-** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
-** are called from a different thread while any of these routines
-** are pending, then the results are undefined.
-**
-** ^The sqlite3_column_type() routine returns the
-** [SQLITE_INTEGER | datatype code] for the initial data type
-** of the result column. ^The returned value is one of [SQLITE_INTEGER],
-** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
-** returned by sqlite3_column_type() is only meaningful if no type
-** conversions have occurred as described below. After a type conversion,
-** the value returned by sqlite3_column_type() is undefined. Future
-** versions of SQLite may change the behavior of sqlite3_column_type()
-** following a type conversion.
-**
-** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
-** routine returns the number of bytes in that BLOB or string.
-** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
-** the string to UTF-8 and then returns the number of bytes.
-** ^If the result is a numeric value then sqlite3_column_bytes() uses
-** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
-** the number of bytes in that string.
-** ^The value returned does not include the zero terminator at the end
-** of the string. ^For clarity: the value returned is the number of
-** bytes in the string, not the number of characters.
-**
-** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
-** even empty strings, are always zero terminated. ^The return
-** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
-** pointer, possibly even a NULL pointer.
-**
-** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
-** but leaves the result in UTF-16 in native byte order instead of UTF-8.
-** ^The zero terminator is not included in this count.
-**
-** ^The object returned by [sqlite3_column_value()] is an
-** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
-** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
-** If the [unprotected sqlite3_value] object returned by
-** [sqlite3_column_value()] is used in any other way, including calls
-** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
-** or [sqlite3_value_bytes()], then the behavior is undefined.
-**
-** These routines attempt to convert the value where appropriate. ^For
-** example, if the internal representation is FLOAT and a text result
-** is requested, [sqlite3_snprintf()] is used internally to perform the
-** conversion automatically. ^(The following table details the conversions
-** that are applied:
-**
-**
-**
-**
Internal Type
Requested Type
Conversion
-**
-**
NULL
INTEGER
Result is 0
-**
NULL
FLOAT
Result is 0.0
-**
NULL
TEXT
Result is NULL pointer
-**
NULL
BLOB
Result is NULL pointer
-**
INTEGER
FLOAT
Convert from integer to float
-**
INTEGER
TEXT
ASCII rendering of the integer
-**
INTEGER
BLOB
Same as INTEGER->TEXT
-**
FLOAT
INTEGER
Convert from float to integer
-**
FLOAT
TEXT
ASCII rendering of the float
-**
FLOAT
BLOB
Same as FLOAT->TEXT
-**
TEXT
INTEGER
Use atoi()
-**
TEXT
FLOAT
Use atof()
-**
TEXT
BLOB
No change
-**
BLOB
INTEGER
Convert to TEXT then use atoi()
-**
BLOB
FLOAT
Convert to TEXT then use atof()
-**
BLOB
TEXT
Add a zero terminator if needed
-**
-**
)^
-**
-** The table above makes reference to standard C library functions atoi()
-** and atof(). SQLite does not really use these functions. It has its
-** own equivalent internal routines. The atoi() and atof() names are
-** used in the table for brevity and because they are familiar to most
-** C programmers.
-**
-** ^Note that when type conversions occur, pointers returned by prior
-** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
-** sqlite3_column_text16() may be invalidated.
-** ^(Type conversions and pointer invalidations might occur
-** in the following cases:
-**
-**
-**
The initial content is a BLOB and sqlite3_column_text() or
-** sqlite3_column_text16() is called. A zero-terminator might
-** need to be added to the string.
-**
The initial content is UTF-8 text and sqlite3_column_bytes16() or
-** sqlite3_column_text16() is called. The content must be converted
-** to UTF-16.
-**
The initial content is UTF-16 text and sqlite3_column_bytes() or
-** sqlite3_column_text() is called. The content must be converted
-** to UTF-8.
-**
)^
-**
-** ^Conversions between UTF-16be and UTF-16le are always done in place and do
-** not invalidate a prior pointer, though of course the content of the buffer
-** that the prior pointer points to will have been modified. Other kinds
-** of conversion are done in place when it is possible, but sometimes they
-** are not possible and in those cases prior pointers are invalidated.
-**
-** ^(The safest and easiest to remember policy is to invoke these routines
-** in one of the following ways:
-**
-**
-**
sqlite3_column_text() followed by sqlite3_column_bytes()
-**
sqlite3_column_blob() followed by sqlite3_column_bytes()
-**
sqlite3_column_text16() followed by sqlite3_column_bytes16()
-**
)^
-**
-** In other words, you should call sqlite3_column_text(),
-** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
-** into the desired format, then invoke sqlite3_column_bytes() or
-** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
-** to sqlite3_column_text() or sqlite3_column_blob() with calls to
-** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
-** with calls to sqlite3_column_bytes().
-**
-** ^The pointers returned are valid until a type conversion occurs as
-** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
-** [sqlite3_finalize()] is called. ^The memory space used to hold strings
-** and BLOBs is freed automatically. Do not pass the pointers returned
-** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
-** [sqlite3_free()].
-**
-** ^(If a memory allocation error occurs during the evaluation of any
-** of these routines, a default value is returned. The default value
-** is either the integer 0, the floating point number 0.0, or a NULL
-** pointer. Subsequent calls to [sqlite3_errcode()] will return
-** [SQLITE_NOMEM].)^
-*/
-SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
-SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
-SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
-SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
-SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
-SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
-SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
-SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
-SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
-SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
-
-/*
-** CAPI3REF: Destroy A Prepared Statement Object
-**
-** ^The sqlite3_finalize() function is called to delete a [prepared statement].
-** ^If the statement was executed successfully or not executed at all, then
-** SQLITE_OK is returned. ^If execution of the statement failed then an
-** [error code] or [extended error code] is returned.
-**
-** ^This routine can be called at any point during the execution of the
-** [prepared statement]. ^If the virtual machine has not
-** completed execution when this routine is called, that is like
-** encountering an error or an [sqlite3_interrupt | interrupt].
-** ^Incomplete updates may be rolled back and transactions canceled,
-** depending on the circumstances, and the
-** [error code] returned will be [SQLITE_ABORT].
-*/
-SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
-
-/*
-** CAPI3REF: Reset A Prepared Statement Object
-**
-** The sqlite3_reset() function is called to reset a [prepared statement]
-** object back to its initial state, ready to be re-executed.
-** ^Any SQL statement variables that had values bound to them using
-** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
-** Use [sqlite3_clear_bindings()] to reset the bindings.
-**
-** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
-** back to the beginning of its program.
-**
-** ^If the most recent call to [sqlite3_step(S)] for the
-** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
-** or if [sqlite3_step(S)] has never before been called on S,
-** then [sqlite3_reset(S)] returns [SQLITE_OK].
-**
-** ^If the most recent call to [sqlite3_step(S)] for the
-** [prepared statement] S indicated an error, then
-** [sqlite3_reset(S)] returns an appropriate [error code].
-**
-** ^The [sqlite3_reset(S)] interface does not change the values
-** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
-*/
-SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
-
-/*
-** CAPI3REF: Create Or Redefine SQL Functions
-** KEYWORDS: {function creation routines}
-** KEYWORDS: {application-defined SQL function}
-** KEYWORDS: {application-defined SQL functions}
-**
-** ^These two functions (collectively known as "function creation routines")
-** are used to add SQL functions or aggregates or to redefine the behavior
-** of existing SQL functions or aggregates. The only difference between the
-** two is that the second parameter, the name of the (scalar) function or
-** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
-** for sqlite3_create_function16().
-**
-** ^The first parameter is the [database connection] to which the SQL
-** function is to be added. ^If an application uses more than one database
-** connection then application-defined SQL functions must be added
-** to each database connection separately.
-**
-** The second parameter is the name of the SQL function to be created or
-** redefined. ^The length of the name is limited to 255 bytes, exclusive of
-** the zero-terminator. Note that the name length limit is in bytes, not
-** characters. ^Any attempt to create a function with a longer name
-** will result in [SQLITE_ERROR] being returned.
-**
-** ^The third parameter (nArg)
-** is the number of arguments that the SQL function or
-** aggregate takes. ^If this parameter is -1, then the SQL function or
-** aggregate may take any number of arguments between 0 and the limit
-** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
-** parameter is less than -1 or greater than 127 then the behavior is
-** undefined.
-**
-** The fourth parameter, eTextRep, specifies what
-** [SQLITE_UTF8 | text encoding] this SQL function prefers for
-** its parameters. Any SQL function implementation should be able to work
-** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
-** more efficient with one encoding than another. ^An application may
-** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
-** times with the same function but with different values of eTextRep.
-** ^When multiple implementations of the same function are available, SQLite
-** will pick the one that involves the least amount of data conversion.
-** If there is only a single implementation which does not care what text
-** encoding is used, then the fourth argument should be [SQLITE_ANY].
-**
-** ^(The fifth parameter is an arbitrary pointer. The implementation of the
-** function can gain access to this pointer using [sqlite3_user_data()].)^
-**
-** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
-** pointers to C-language functions that implement the SQL function or
-** aggregate. ^A scalar SQL function requires an implementation of the xFunc
-** callback only; NULL pointers should be passed as the xStep and xFinal
-** parameters. ^An aggregate SQL function requires an implementation of xStep
-** and xFinal and NULL should be passed for xFunc. ^To delete an existing
-** SQL function or aggregate, pass NULL for all three function callbacks.
-**
-** ^It is permitted to register multiple implementations of the same
-** functions with the same name but with either differing numbers of
-** arguments or differing preferred text encodings. ^SQLite will use
-** the implementation that most closely matches the way in which the
-** SQL function is used. ^A function implementation with a non-negative
-** nArg parameter is a better match than a function implementation with
-** a negative nArg. ^A function where the preferred text encoding
-** matches the database encoding is a better
-** match than a function where the encoding is different.
-** ^A function where the encoding difference is between UTF16le and UTF16be
-** is a closer match than a function where the encoding difference is
-** between UTF8 and UTF16.
-**
-** ^Built-in functions may be overloaded by new application-defined functions.
-** ^The first application-defined function with a given name overrides all
-** built-in functions in the same [database connection] with the same name.
-** ^Subsequent application-defined functions of the same name only override
-** prior application-defined functions that are an exact match for the
-** number of parameters and preferred encoding.
-**
-** ^An application-defined function is permitted to call other
-** SQLite interfaces. However, such calls must not
-** close the database connection nor finalize or reset the prepared
-** statement in which the function is running.
-*/
-SQLITE_API int sqlite3_create_function(
- sqlite3 *db,
- const char *zFunctionName,
- int nArg,
- int eTextRep,
- void *pApp,
- void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
- void (*xStep)(sqlite3_context*,int,sqlite3_value**),
- void (*xFinal)(sqlite3_context*)
-);
-SQLITE_API int sqlite3_create_function16(
- sqlite3 *db,
- const void *zFunctionName,
- int nArg,
- int eTextRep,
- void *pApp,
- void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
- void (*xStep)(sqlite3_context*,int,sqlite3_value**),
- void (*xFinal)(sqlite3_context*)
-);
-
-/*
-** CAPI3REF: Text Encodings
-**
-** These constant define integer codes that represent the various
-** text encodings supported by SQLite.
-*/
-#define SQLITE_UTF8 1
-#define SQLITE_UTF16LE 2
-#define SQLITE_UTF16BE 3
-#define SQLITE_UTF16 4 /* Use native byte order */
-#define SQLITE_ANY 5 /* sqlite3_create_function only */
-#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
-
-/*
-** CAPI3REF: Deprecated Functions
-** DEPRECATED
-**
-** These functions are [deprecated]. In order to maintain
-** backwards compatibility with older code, these functions continue
-** to be supported. However, new applications should avoid
-** the use of these functions. To help encourage people to avoid
-** using these functions, we are not going to tell you what they do.
-*/
-#ifndef SQLITE_OMIT_DEPRECATED
-SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
-SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
-SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
-SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
-SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
-SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
-#endif
-
-/*
-** CAPI3REF: Obtaining SQL Function Parameter Values
-**
-** The C-language implementation of SQL functions and aggregates uses
-** this set of interface routines to access the parameter values on
-** the function or aggregate.
-**
-** The xFunc (for scalar functions) or xStep (for aggregates) parameters
-** to [sqlite3_create_function()] and [sqlite3_create_function16()]
-** define callbacks that implement the SQL functions and aggregates.
-** The 4th parameter to these callbacks is an array of pointers to
-** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
-** each parameter to the SQL function. These routines are used to
-** extract values from the [sqlite3_value] objects.
-**
-** These routines work only with [protected sqlite3_value] objects.
-** Any attempt to use these routines on an [unprotected sqlite3_value]
-** object results in undefined behavior.
-**
-** ^These routines work just like the corresponding [column access functions]
-** except that these routines take a single [protected sqlite3_value] object
-** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
-**
-** ^The sqlite3_value_text16() interface extracts a UTF-16 string
-** in the native byte-order of the host machine. ^The
-** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
-** extract UTF-16 strings as big-endian and little-endian respectively.
-**
-** ^(The sqlite3_value_numeric_type() interface attempts to apply
-** numeric affinity to the value. This means that an attempt is
-** made to convert the value to an integer or floating point. If
-** such a conversion is possible without loss of information (in other
-** words, if the value is a string that looks like a number)
-** then the conversion is performed. Otherwise no conversion occurs.
-** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
-**
-** Please pay particular attention to the fact that the pointer returned
-** from [sqlite3_value_blob()], [sqlite3_value_text()], or
-** [sqlite3_value_text16()] can be invalidated by a subsequent call to
-** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
-** or [sqlite3_value_text16()].
-**
-** These routines must be called from the same thread as
-** the SQL function that supplied the [sqlite3_value*] parameters.
-*/
-SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
-SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
-SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
-SQLITE_API double sqlite3_value_double(sqlite3_value*);
-SQLITE_API int sqlite3_value_int(sqlite3_value*);
-SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
-SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
-SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
-SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
-SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
-SQLITE_API int sqlite3_value_type(sqlite3_value*);
-SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
-
-/*
-** CAPI3REF: Obtain Aggregate Function Context
-**
-** Implementions of aggregate SQL functions use this
-** routine to allocate memory for storing their state.
-**
-** ^The first time the sqlite3_aggregate_context(C,N) routine is called
-** for a particular aggregate function, SQLite
-** allocates N of memory, zeroes out that memory, and returns a pointer
-** to the new memory. ^On second and subsequent calls to
-** sqlite3_aggregate_context() for the same aggregate function instance,
-** the same buffer is returned. Sqlite3_aggregate_context() is normally
-** called once for each invocation of the xStep callback and then one
-** last time when the xFinal callback is invoked. ^(When no rows match
-** an aggregate query, the xStep() callback of the aggregate function
-** implementation is never called and xFinal() is called exactly once.
-** In those cases, sqlite3_aggregate_context() might be called for the
-** first time from within xFinal().)^
-**
-** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
-** less than or equal to zero or if a memory allocate error occurs.
-**
-** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
-** determined by the N parameter on first successful call. Changing the
-** value of N in subsequent call to sqlite3_aggregate_context() within
-** the same aggregate function instance will not resize the memory
-** allocation.)^
-**
-** ^SQLite automatically frees the memory allocated by
-** sqlite3_aggregate_context() when the aggregate query concludes.
-**
-** The first parameter must be a copy of the
-** [sqlite3_context | SQL function context] that is the first parameter
-** to the xStep or xFinal callback routine that implements the aggregate
-** function.
-**
-** This routine must be called from the same thread in which
-** the aggregate SQL function is running.
-*/
-SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
-
-/*
-** CAPI3REF: User Data For Functions
-**
-** ^The sqlite3_user_data() interface returns a copy of
-** the pointer that was the pUserData parameter (the 5th parameter)
-** of the [sqlite3_create_function()]
-** and [sqlite3_create_function16()] routines that originally
-** registered the application defined function.
-**
-** This routine must be called from the same thread in which
-** the application-defined function is running.
-*/
-SQLITE_API void *sqlite3_user_data(sqlite3_context*);
-
-/*
-** CAPI3REF: Database Connection For Functions
-**
-** ^The sqlite3_context_db_handle() interface returns a copy of
-** the pointer to the [database connection] (the 1st parameter)
-** of the [sqlite3_create_function()]
-** and [sqlite3_create_function16()] routines that originally
-** registered the application defined function.
-*/
-SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
-
-/*
-** CAPI3REF: Function Auxiliary Data
-**
-** The following two functions may be used by scalar SQL functions to
-** associate metadata with argument values. If the same value is passed to
-** multiple invocations of the same SQL function during query execution, under
-** some circumstances the associated metadata may be preserved. This may
-** be used, for example, to add a regular-expression matching scalar
-** function. The compiled version of the regular expression is stored as
-** metadata associated with the SQL value passed as the regular expression
-** pattern. The compiled regular expression can be reused on multiple
-** invocations of the same function so that the original pattern string
-** does not need to be recompiled on each invocation.
-**
-** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
-** associated by the sqlite3_set_auxdata() function with the Nth argument
-** value to the application-defined function. ^If no metadata has been ever
-** been set for the Nth argument of the function, or if the corresponding
-** function parameter has changed since the meta-data was set,
-** then sqlite3_get_auxdata() returns a NULL pointer.
-**
-** ^The sqlite3_set_auxdata() interface saves the metadata
-** pointed to by its 3rd parameter as the metadata for the N-th
-** argument of the application-defined function. Subsequent
-** calls to sqlite3_get_auxdata() might return this data, if it has
-** not been destroyed.
-** ^If it is not NULL, SQLite will invoke the destructor
-** function given by the 4th parameter to sqlite3_set_auxdata() on
-** the metadata when the corresponding function parameter changes
-** or when the SQL statement completes, whichever comes first.
-**
-** SQLite is free to call the destructor and drop metadata on any
-** parameter of any function at any time. ^The only guarantee is that
-** the destructor will be called before the metadata is dropped.
-**
-** ^(In practice, metadata is preserved between function calls for
-** expressions that are constant at compile time. This includes literal
-** values and [parameters].)^
-**
-** These routines must be called from the same thread in which
-** the SQL function is running.
-*/
-SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
-SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
-
-
-/*
-** CAPI3REF: Constants Defining Special Destructor Behavior
-**
-** These are special values for the destructor that is passed in as the
-** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
-** argument is SQLITE_STATIC, it means that the content pointer is constant
-** and will never change. It does not need to be destroyed. ^The
-** SQLITE_TRANSIENT value means that the content will likely change in
-** the near future and that SQLite should make its own private copy of
-** the content before returning.
-**
-** The typedef is necessary to work around problems in certain
-** C++ compilers. See ticket #2191.
-*/
-typedef void (*sqlite3_destructor_type)(void*);
-#define SQLITE_STATIC ((sqlite3_destructor_type)0)
-#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
-
-/*
-** CAPI3REF: Setting The Result Of An SQL Function
-**
-** These routines are used by the xFunc or xFinal callbacks that
-** implement SQL functions and aggregates. See
-** [sqlite3_create_function()] and [sqlite3_create_function16()]
-** for additional information.
-**
-** These functions work very much like the [parameter binding] family of
-** functions used to bind values to host parameters in prepared statements.
-** Refer to the [SQL parameter] documentation for additional information.
-**
-** ^The sqlite3_result_blob() interface sets the result from
-** an application-defined function to be the BLOB whose content is pointed
-** to by the second parameter and which is N bytes long where N is the
-** third parameter.
-**
-** ^The sqlite3_result_zeroblob() interfaces set the result of
-** the application-defined function to be a BLOB containing all zero
-** bytes and N bytes in size, where N is the value of the 2nd parameter.
-**
-** ^The sqlite3_result_double() interface sets the result from
-** an application-defined function to be a floating point value specified
-** by its 2nd argument.
-**
-** ^The sqlite3_result_error() and sqlite3_result_error16() functions
-** cause the implemented SQL function to throw an exception.
-** ^SQLite uses the string pointed to by the
-** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
-** as the text of an error message. ^SQLite interprets the error
-** message string from sqlite3_result_error() as UTF-8. ^SQLite
-** interprets the string from sqlite3_result_error16() as UTF-16 in native
-** byte order. ^If the third parameter to sqlite3_result_error()
-** or sqlite3_result_error16() is negative then SQLite takes as the error
-** message all text up through the first zero character.
-** ^If the third parameter to sqlite3_result_error() or
-** sqlite3_result_error16() is non-negative then SQLite takes that many
-** bytes (not characters) from the 2nd parameter as the error message.
-** ^The sqlite3_result_error() and sqlite3_result_error16()
-** routines make a private copy of the error message text before
-** they return. Hence, the calling function can deallocate or
-** modify the text after they return without harm.
-** ^The sqlite3_result_error_code() function changes the error code
-** returned by SQLite as a result of an error in a function. ^By default,
-** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
-** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
-**
-** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
-** indicating that a string or BLOB is too long to represent.
-**
-** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
-** indicating that a memory allocation failed.
-**
-** ^The sqlite3_result_int() interface sets the return value
-** of the application-defined function to be the 32-bit signed integer
-** value given in the 2nd argument.
-** ^The sqlite3_result_int64() interface sets the return value
-** of the application-defined function to be the 64-bit signed integer
-** value given in the 2nd argument.
-**
-** ^The sqlite3_result_null() interface sets the return value
-** of the application-defined function to be NULL.
-**
-** ^The sqlite3_result_text(), sqlite3_result_text16(),
-** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
-** set the return value of the application-defined function to be
-** a text string which is represented as UTF-8, UTF-16 native byte order,
-** UTF-16 little endian, or UTF-16 big endian, respectively.
-** ^SQLite takes the text result from the application from
-** the 2nd parameter of the sqlite3_result_text* interfaces.
-** ^If the 3rd parameter to the sqlite3_result_text* interfaces
-** is negative, then SQLite takes result text from the 2nd parameter
-** through the first zero character.
-** ^If the 3rd parameter to the sqlite3_result_text* interfaces
-** is non-negative, then as many bytes (not characters) of the text
-** pointed to by the 2nd parameter are taken as the application-defined
-** function result.
-** ^If the 4th parameter to the sqlite3_result_text* interfaces
-** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
-** function as the destructor on the text or BLOB result when it has
-** finished using that result.
-** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
-** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
-** assumes that the text or BLOB result is in constant space and does not
-** copy the content of the parameter nor call a destructor on the content
-** when it has finished using that result.
-** ^If the 4th parameter to the sqlite3_result_text* interfaces
-** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
-** then SQLite makes a copy of the result into space obtained from
-** from [sqlite3_malloc()] before it returns.
-**
-** ^The sqlite3_result_value() interface sets the result of
-** the application-defined function to be a copy the
-** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
-** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
-** so that the [sqlite3_value] specified in the parameter may change or
-** be deallocated after sqlite3_result_value() returns without harm.
-** ^A [protected sqlite3_value] object may always be used where an
-** [unprotected sqlite3_value] object is required, so either
-** kind of [sqlite3_value] object can be used with this interface.
-**
-** If these routines are called from within the different thread
-** than the one containing the application-defined function that received
-** the [sqlite3_context] pointer, the results are undefined.
-*/
-SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
-SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
-SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
-SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
-SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
-SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
-SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
-SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
-SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
-SQLITE_API void sqlite3_result_null(sqlite3_context*);
-SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
-SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
-SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
-SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
-SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
-SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
-
-/*
-** CAPI3REF: Define New Collating Sequences
-**
-** These functions are used to add new collation sequences to the
-** [database connection] specified as the first argument.
-**
-** ^The name of the new collation sequence is specified as a UTF-8 string
-** for sqlite3_create_collation() and sqlite3_create_collation_v2()
-** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
-** the name is passed as the second function argument.
-**
-** ^The third argument may be one of the constants [SQLITE_UTF8],
-** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
-** routine expects to be passed pointers to strings encoded using UTF-8,
-** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
-** third argument might also be [SQLITE_UTF16] to indicate that the routine
-** expects pointers to be UTF-16 strings in the native byte order, or the
-** argument can be [SQLITE_UTF16_ALIGNED] if the
-** the routine expects pointers to 16-bit word aligned strings
-** of UTF-16 in the native byte order.
-**
-** A pointer to the user supplied routine must be passed as the fifth
-** argument. ^If it is NULL, this is the same as deleting the collation
-** sequence (so that SQLite cannot call it anymore).
-** ^Each time the application supplied function is invoked, it is passed
-** as its first parameter a copy of the void* passed as the fourth argument
-** to sqlite3_create_collation() or sqlite3_create_collation16().
-**
-** ^The remaining arguments to the application-supplied routine are two strings,
-** each represented by a (length, data) pair and encoded in the encoding
-** that was passed as the third argument when the collation sequence was
-** registered. The application defined collation routine should
-** return negative, zero or positive if the first string is less than,
-** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
-**
-** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
-** except that it takes an extra argument which is a destructor for
-** the collation. ^The destructor is called when the collation is
-** destroyed and is passed a copy of the fourth parameter void* pointer
-** of the sqlite3_create_collation_v2().
-** ^Collations are destroyed when they are overridden by later calls to the
-** collation creation functions or when the [database connection] is closed
-** using [sqlite3_close()].
-**
-** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
-*/
-SQLITE_API int sqlite3_create_collation(
- sqlite3*,
- const char *zName,
- int eTextRep,
- void*,
- int(*xCompare)(void*,int,const void*,int,const void*)
-);
-SQLITE_API int sqlite3_create_collation_v2(
- sqlite3*,
- const char *zName,
- int eTextRep,
- void*,
- int(*xCompare)(void*,int,const void*,int,const void*),
- void(*xDestroy)(void*)
-);
-SQLITE_API int sqlite3_create_collation16(
- sqlite3*,
- const void *zName,
- int eTextRep,
- void*,
- int(*xCompare)(void*,int,const void*,int,const void*)
-);
-
-/*
-** CAPI3REF: Collation Needed Callbacks
-**
-** ^To avoid having to register all collation sequences before a database
-** can be used, a single callback function may be registered with the
-** [database connection] to be invoked whenever an undefined collation
-** sequence is required.
-**
-** ^If the function is registered using the sqlite3_collation_needed() API,
-** then it is passed the names of undefined collation sequences as strings
-** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
-** the names are passed as UTF-16 in machine native byte order.
-** ^A call to either function replaces the existing collation-needed callback.
-**
-** ^(When the callback is invoked, the first argument passed is a copy
-** of the second argument to sqlite3_collation_needed() or
-** sqlite3_collation_needed16(). The second argument is the database
-** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
-** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
-** sequence function required. The fourth parameter is the name of the
-** required collation sequence.)^
-**
-** The callback function should register the desired collation using
-** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
-** [sqlite3_create_collation_v2()].
-*/
-SQLITE_API int sqlite3_collation_needed(
- sqlite3*,
- void*,
- void(*)(void*,sqlite3*,int eTextRep,const char*)
-);
-SQLITE_API int sqlite3_collation_needed16(
- sqlite3*,
- void*,
- void(*)(void*,sqlite3*,int eTextRep,const void*)
-);
-
-/*
-** Specify the key for an encrypted database. This routine should be
-** called right after sqlite3_open().
-**
-** The code to implement this API is not available in the public release
-** of SQLite.
-*/
-SQLITE_API int sqlite3_key(
- sqlite3 *db, /* Database to be rekeyed */
- const void *pKey, int nKey /* The key */
-);
-
-/*
-** Change the key on an open database. If the current database is not
-** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
-** database is decrypted.
-**
-** The code to implement this API is not available in the public release
-** of SQLite.
-*/
-SQLITE_API int sqlite3_rekey(
- sqlite3 *db, /* Database to be rekeyed */
- const void *pKey, int nKey /* The new key */
-);
-
-/*
-** CAPI3REF: Suspend Execution For A Short Time
-**
-** ^The sqlite3_sleep() function causes the current thread to suspend execution
-** for at least a number of milliseconds specified in its parameter.
-**
-** ^If the operating system does not support sleep requests with
-** millisecond time resolution, then the time will be rounded up to
-** the nearest second. ^The number of milliseconds of sleep actually
-** requested from the operating system is returned.
-**
-** ^SQLite implements this interface by calling the xSleep()
-** method of the default [sqlite3_vfs] object.
-*/
-SQLITE_API int sqlite3_sleep(int);
-
-/*
-** CAPI3REF: Name Of The Folder Holding Temporary Files
-**
-** ^(If this global variable is made to point to a string which is
-** the name of a folder (a.k.a. directory), then all temporary files
-** created by SQLite when using a built-in [sqlite3_vfs | VFS]
-** will be placed in that directory.)^ ^If this variable
-** is a NULL pointer, then SQLite performs a search for an appropriate
-** temporary file directory.
-**
-** It is not safe to read or modify this variable in more than one
-** thread at a time. It is not safe to read or modify this variable
-** if a [database connection] is being used at the same time in a separate
-** thread.
-** It is intended that this variable be set once
-** as part of process initialization and before any SQLite interface
-** routines have been called and that this variable remain unchanged
-** thereafter.
-**
-** ^The [temp_store_directory pragma] may modify this variable and cause
-** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
-** the [temp_store_directory pragma] always assumes that any string
-** that this variable points to is held in memory obtained from
-** [sqlite3_malloc] and the pragma may attempt to free that memory
-** using [sqlite3_free].
-** Hence, if this variable is modified directly, either it should be
-** made NULL or made to point to memory obtained from [sqlite3_malloc]
-** or else the use of the [temp_store_directory pragma] should be avoided.
-*/
-SQLITE_API char *sqlite3_temp_directory;
-
-/*
-** CAPI3REF: Test For Auto-Commit Mode
-** KEYWORDS: {autocommit mode}
-**
-** ^The sqlite3_get_autocommit() interface returns non-zero or
-** zero if the given database connection is or is not in autocommit mode,
-** respectively. ^Autocommit mode is on by default.
-** ^Autocommit mode is disabled by a [BEGIN] statement.
-** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
-**
-** If certain kinds of errors occur on a statement within a multi-statement
-** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
-** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
-** transaction might be rolled back automatically. The only way to
-** find out whether SQLite automatically rolled back the transaction after
-** an error is to use this function.
-**
-** If another thread changes the autocommit status of the database
-** connection while this routine is running, then the return value
-** is undefined.
-*/
-SQLITE_API int sqlite3_get_autocommit(sqlite3*);
-
-/*
-** CAPI3REF: Find The Database Handle Of A Prepared Statement
-**
-** ^The sqlite3_db_handle interface returns the [database connection] handle
-** to which a [prepared statement] belongs. ^The [database connection]
-** returned by sqlite3_db_handle is the same [database connection]
-** that was the first argument
-** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
-** create the statement in the first place.
-*/
-SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
-
-/*
-** CAPI3REF: Find the next prepared statement
-**
-** ^This interface returns a pointer to the next [prepared statement] after
-** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
-** then this interface returns a pointer to the first prepared statement
-** associated with the database connection pDb. ^If no prepared statement
-** satisfies the conditions of this routine, it returns NULL.
-**
-** The [database connection] pointer D in a call to
-** [sqlite3_next_stmt(D,S)] must refer to an open database
-** connection and in particular must not be a NULL pointer.
-*/
-SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
-
-/*
-** CAPI3REF: Commit And Rollback Notification Callbacks
-**
-** ^The sqlite3_commit_hook() interface registers a callback
-** function to be invoked whenever a transaction is [COMMIT | committed].
-** ^Any callback set by a previous call to sqlite3_commit_hook()
-** for the same database connection is overridden.
-** ^The sqlite3_rollback_hook() interface registers a callback
-** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
-** ^Any callback set by a previous call to sqlite3_rollback_hook()
-** for the same database connection is overridden.
-** ^The pArg argument is passed through to the callback.
-** ^If the callback on a commit hook function returns non-zero,
-** then the commit is converted into a rollback.
-**
-** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
-** return the P argument from the previous call of the same function
-** on the same [database connection] D, or NULL for
-** the first call for each function on D.
-**
-** The callback implementation must not do anything that will modify
-** the database connection that invoked the callback. Any actions
-** to modify the database connection must be deferred until after the
-** completion of the [sqlite3_step()] call that triggered the commit
-** or rollback hook in the first place.
-** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
-** database connections for the meaning of "modify" in this paragraph.
-**
-** ^Registering a NULL function disables the callback.
-**
-** ^When the commit hook callback routine returns zero, the [COMMIT]
-** operation is allowed to continue normally. ^If the commit hook
-** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
-** ^The rollback hook is invoked on a rollback that results from a commit
-** hook returning non-zero, just as it would be with any other rollback.
-**
-** ^For the purposes of this API, a transaction is said to have been
-** rolled back if an explicit "ROLLBACK" statement is executed, or
-** an error or constraint causes an implicit rollback to occur.
-** ^The rollback callback is not invoked if a transaction is
-** automatically rolled back because the database connection is closed.
-** ^The rollback callback is not invoked if a transaction is
-** rolled back because a commit callback returned non-zero.
-**
-** See also the [sqlite3_update_hook()] interface.
-*/
-SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
-SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
-
-/*
-** CAPI3REF: Data Change Notification Callbacks
-**
-** ^The sqlite3_update_hook() interface registers a callback function
-** with the [database connection] identified by the first argument
-** to be invoked whenever a row is updated, inserted or deleted.
-** ^Any callback set by a previous call to this function
-** for the same database connection is overridden.
-**
-** ^The second argument is a pointer to the function to invoke when a
-** row is updated, inserted or deleted.
-** ^The first argument to the callback is a copy of the third argument
-** to sqlite3_update_hook().
-** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
-** or [SQLITE_UPDATE], depending on the operation that caused the callback
-** to be invoked.
-** ^The third and fourth arguments to the callback contain pointers to the
-** database and table name containing the affected row.
-** ^The final callback parameter is the [rowid] of the row.
-** ^In the case of an update, this is the [rowid] after the update takes place.
-**
-** ^(The update hook is not invoked when internal system tables are
-** modified (i.e. sqlite_master and sqlite_sequence).)^
-**
-** ^In the current implementation, the update hook
-** is not invoked when duplication rows are deleted because of an
-** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
-** invoked when rows are deleted using the [truncate optimization].
-** The exceptions defined in this paragraph might change in a future
-** release of SQLite.
-**
-** The update hook implementation must not do anything that will modify
-** the database connection that invoked the update hook. Any actions
-** to modify the database connection must be deferred until after the
-** completion of the [sqlite3_step()] call that triggered the update hook.
-** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
-** database connections for the meaning of "modify" in this paragraph.
-**
-** ^The sqlite3_update_hook(D,C,P) function
-** returns the P argument from the previous call
-** on the same [database connection] D, or NULL for
-** the first call on D.
-**
-** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
-** interfaces.
-*/
-SQLITE_API void *sqlite3_update_hook(
- sqlite3*,
- void(*)(void *,int ,char const *,char const *,sqlite3_int64),
- void*
-);
-
-/*
-** CAPI3REF: Enable Or Disable Shared Pager Cache
-** KEYWORDS: {shared cache}
-**
-** ^(This routine enables or disables the sharing of the database cache
-** and schema data structures between [database connection | connections]
-** to the same database. Sharing is enabled if the argument is true
-** and disabled if the argument is false.)^
-**
-** ^Cache sharing is enabled and disabled for an entire process.
-** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
-** sharing was enabled or disabled for each thread separately.
-**
-** ^(The cache sharing mode set by this interface effects all subsequent
-** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
-** Existing database connections continue use the sharing mode
-** that was in effect at the time they were opened.)^
-**
-** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
-** successfully. An [error code] is returned otherwise.)^
-**
-** ^Shared cache is disabled by default. But this might change in
-** future releases of SQLite. Applications that care about shared
-** cache setting should set it explicitly.
-**
-** See Also: [SQLite Shared-Cache Mode]
-*/
-SQLITE_API int sqlite3_enable_shared_cache(int);
-
-/*
-** CAPI3REF: Attempt To Free Heap Memory
-**
-** ^The sqlite3_release_memory() interface attempts to free N bytes
-** of heap memory by deallocating non-essential memory allocations
-** held by the database library. Memory used to cache database
-** pages to improve performance is an example of non-essential memory.
-** ^sqlite3_release_memory() returns the number of bytes actually freed,
-** which might be more or less than the amount requested.
-*/
-SQLITE_API int sqlite3_release_memory(int);
-
-/*
-** CAPI3REF: Impose A Limit On Heap Size
-**
-** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
-** on the amount of heap memory that may be allocated by SQLite.
-** ^If an internal allocation is requested that would exceed the
-** soft heap limit, [sqlite3_release_memory()] is invoked one or
-** more times to free up some space before the allocation is performed.
-**
-** ^The limit is called "soft" because if [sqlite3_release_memory()]
-** cannot free sufficient memory to prevent the limit from being exceeded,
-** the memory is allocated anyway and the current operation proceeds.
-**
-** ^A negative or zero value for N means that there is no soft heap limit and
-** [sqlite3_release_memory()] will only be called when memory is exhausted.
-** ^The default value for the soft heap limit is zero.
-**
-** ^(SQLite makes a best effort to honor the soft heap limit.
-** But if the soft heap limit cannot be honored, execution will
-** continue without error or notification.)^ This is why the limit is
-** called a "soft" limit. It is advisory only.
-**
-** Prior to SQLite version 3.5.0, this routine only constrained the memory
-** allocated by a single thread - the same thread in which this routine
-** runs. Beginning with SQLite version 3.5.0, the soft heap limit is
-** applied to all threads. The value specified for the soft heap limit
-** is an upper bound on the total memory allocation for all threads. In
-** version 3.5.0 there is no mechanism for limiting the heap usage for
-** individual threads.
-*/
-SQLITE_API void sqlite3_soft_heap_limit(int);
-
-/*
-** CAPI3REF: Extract Metadata About A Column Of A Table
-**
-** ^This routine returns metadata about a specific column of a specific
-** database table accessible using the [database connection] handle
-** passed as the first function argument.
-**
-** ^The column is identified by the second, third and fourth parameters to
-** this function. ^The second parameter is either the name of the database
-** (i.e. "main", "temp", or an attached database) containing the specified
-** table or NULL. ^If it is NULL, then all attached databases are searched
-** for the table using the same algorithm used by the database engine to
-** resolve unqualified table references.
-**
-** ^The third and fourth parameters to this function are the table and column
-** name of the desired column, respectively. Neither of these parameters
-** may be NULL.
-**
-** ^Metadata is returned by writing to the memory locations passed as the 5th
-** and subsequent parameters to this function. ^Any of these arguments may be
-** NULL, in which case the corresponding element of metadata is omitted.
-**
-** ^(
-**
-**
Parameter
Output Type
Description
-**
-**
5th
const char*
Data type
-**
6th
const char*
Name of default collation sequence
-**
7th
int
True if column has a NOT NULL constraint
-**
8th
int
True if column is part of the PRIMARY KEY
-**
9th
int
True if column is [AUTOINCREMENT]
-**
-**
)^
-**
-** ^The memory pointed to by the character pointers returned for the
-** declaration type and collation sequence is valid only until the next
-** call to any SQLite API function.
-**
-** ^If the specified table is actually a view, an [error code] is returned.
-**
-** ^If the specified column is "rowid", "oid" or "_rowid_" and an
-** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
-** parameters are set for the explicitly declared column. ^(If there is no
-** explicitly declared [INTEGER PRIMARY KEY] column, then the output
-** parameters are set as follows:
-**
-**
-** data type: "INTEGER"
-** collation sequence: "BINARY"
-** not null: 0
-** primary key: 1
-** auto increment: 0
-**
)^
-**
-** ^(This function may load one or more schemas from database files. If an
-** error occurs during this process, or if the requested table or column
-** cannot be found, an [error code] is returned and an error message left
-** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
-**
-** ^This API is only available if the library was compiled with the
-** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
-*/
-SQLITE_API int sqlite3_table_column_metadata(
- sqlite3 *db, /* Connection handle */
- const char *zDbName, /* Database name or NULL */
- const char *zTableName, /* Table name */
- const char *zColumnName, /* Column name */
- char const **pzDataType, /* OUTPUT: Declared data type */
- char const **pzCollSeq, /* OUTPUT: Collation sequence name */
- int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
- int *pPrimaryKey, /* OUTPUT: True if column part of PK */
- int *pAutoinc /* OUTPUT: True if column is auto-increment */
-);
-
-/*
-** CAPI3REF: Load An Extension
-**
-** ^This interface loads an SQLite extension library from the named file.
-**
-** ^The sqlite3_load_extension() interface attempts to load an
-** SQLite extension library contained in the file zFile.
-**
-** ^The entry point is zProc.
-** ^zProc may be 0, in which case the name of the entry point
-** defaults to "sqlite3_extension_init".
-** ^The sqlite3_load_extension() interface returns
-** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
-** ^If an error occurs and pzErrMsg is not 0, then the
-** [sqlite3_load_extension()] interface shall attempt to
-** fill *pzErrMsg with error message text stored in memory
-** obtained from [sqlite3_malloc()]. The calling function
-** should free this memory by calling [sqlite3_free()].
-**
-** ^Extension loading must be enabled using
-** [sqlite3_enable_load_extension()] prior to calling this API,
-** otherwise an error will be returned.
-**
-** See also the [load_extension() SQL function].
-*/
-SQLITE_API int sqlite3_load_extension(
- sqlite3 *db, /* Load the extension into this database connection */
- const char *zFile, /* Name of the shared library containing extension */
- const char *zProc, /* Entry point. Derived from zFile if 0 */
- char **pzErrMsg /* Put error message here if not 0 */
-);
-
-/*
-** CAPI3REF: Enable Or Disable Extension Loading
-**
-** ^So as not to open security holes in older applications that are
-** unprepared to deal with extension loading, and as a means of disabling
-** extension loading while evaluating user-entered SQL, the following API
-** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
-**
-** ^Extension loading is off by default. See ticket #1863.
-** ^Call the sqlite3_enable_load_extension() routine with onoff==1
-** to turn extension loading on and call it with onoff==0 to turn
-** it back off again.
-*/
-SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
-
-/*
-** CAPI3REF: Automatically Load An Extensions
-**
-** ^This API can be invoked at program startup in order to register
-** one or more statically linked extensions that will be available
-** to all new [database connections].
-**
-** ^(This routine stores a pointer to the extension entry point
-** in an array that is obtained from [sqlite3_malloc()]. That memory
-** is deallocated by [sqlite3_reset_auto_extension()].)^
-**
-** ^This function registers an extension entry point that is
-** automatically invoked whenever a new [database connection]
-** is opened using [sqlite3_open()], [sqlite3_open16()],
-** or [sqlite3_open_v2()].
-** ^Duplicate extensions are detected so calling this routine
-** multiple times with the same extension is harmless.
-** ^Automatic extensions apply across all threads.
-*/
-SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
-
-/*
-** CAPI3REF: Reset Automatic Extension Loading
-**
-** ^(This function disables all previously registered automatic
-** extensions. It undoes the effect of all prior
-** [sqlite3_auto_extension()] calls.)^
-**
-** ^This function disables automatic extensions in all threads.
-*/
-SQLITE_API void sqlite3_reset_auto_extension(void);
-
-/*
-****** EXPERIMENTAL - subject to change without notice **************
-**
-** The interface to the virtual-table mechanism is currently considered
-** to be experimental. The interface might change in incompatible ways.
-** If this is a problem for you, do not use the interface at this time.
-**
-** When the virtual-table mechanism stabilizes, we will declare the
-** interface fixed, support it indefinitely, and remove this comment.
-*/
-
-/*
-** Structures used by the virtual table interface
-*/
-typedef struct sqlite3_vtab sqlite3_vtab;
-typedef struct sqlite3_index_info sqlite3_index_info;
-typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
-typedef struct sqlite3_module sqlite3_module;
-
-/*
-** CAPI3REF: Virtual Table Object
-** KEYWORDS: sqlite3_module {virtual table module}
-** EXPERIMENTAL
-**
-** This structure, sometimes called a a "virtual table module",
-** defines the implementation of a [virtual tables].
-** This structure consists mostly of methods for the module.
-**
-** ^A virtual table module is created by filling in a persistent
-** instance of this structure and passing a pointer to that instance
-** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
-** ^The registration remains valid until it is replaced by a different
-** module or until the [database connection] closes. The content
-** of this structure must not change while it is registered with
-** any database connection.
-*/
-struct sqlite3_module {
- int iVersion;
- int (*xCreate)(sqlite3*, void *pAux,
- int argc, const char *const*argv,
- sqlite3_vtab **ppVTab, char**);
- int (*xConnect)(sqlite3*, void *pAux,
- int argc, const char *const*argv,
- sqlite3_vtab **ppVTab, char**);
- int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
- int (*xDisconnect)(sqlite3_vtab *pVTab);
- int (*xDestroy)(sqlite3_vtab *pVTab);
- int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
- int (*xClose)(sqlite3_vtab_cursor*);
- int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
- int argc, sqlite3_value **argv);
- int (*xNext)(sqlite3_vtab_cursor*);
- int (*xEof)(sqlite3_vtab_cursor*);
- int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
- int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
- int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
- int (*xBegin)(sqlite3_vtab *pVTab);
- int (*xSync)(sqlite3_vtab *pVTab);
- int (*xCommit)(sqlite3_vtab *pVTab);
- int (*xRollback)(sqlite3_vtab *pVTab);
- int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
- void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
- void **ppArg);
- int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
-};
-
-/*
-** CAPI3REF: Virtual Table Indexing Information
-** KEYWORDS: sqlite3_index_info
-** EXPERIMENTAL
-**
-** The sqlite3_index_info structure and its substructures is used to
-** pass information into and receive the reply from the [xBestIndex]
-** method of a [virtual table module]. The fields under **Inputs** are the
-** inputs to xBestIndex and are read-only. xBestIndex inserts its
-** results into the **Outputs** fields.
-**
-** ^(The aConstraint[] array records WHERE clause constraints of the form:
-**
-**
column OP expr
-**
-** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is
-** stored in aConstraint[].op.)^ ^(The index of the column is stored in
-** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
-** expr on the right-hand side can be evaluated (and thus the constraint
-** is usable) and false if it cannot.)^
-**
-** ^The optimizer automatically inverts terms of the form "expr OP column"
-** and makes other simplifications to the WHERE clause in an attempt to
-** get as many WHERE clause terms into the form shown above as possible.
-** ^The aConstraint[] array only reports WHERE clause terms that are
-** relevant to the particular virtual table being queried.
-**
-** ^Information about the ORDER BY clause is stored in aOrderBy[].
-** ^Each term of aOrderBy records a column of the ORDER BY clause.
-**
-** The [xBestIndex] method must fill aConstraintUsage[] with information
-** about what parameters to pass to xFilter. ^If argvIndex>0 then
-** the right-hand side of the corresponding aConstraint[] is evaluated
-** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
-** is true, then the constraint is assumed to be fully handled by the
-** virtual table and is not checked again by SQLite.)^
-**
-** ^The idxNum and idxPtr values are recorded and passed into the
-** [xFilter] method.
-** ^[sqlite3_free()] is used to free idxPtr if and only if
-** needToFreeIdxPtr is true.
-**
-** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
-** the correct order to satisfy the ORDER BY clause so that no separate
-** sorting step is required.
-**
-** ^The estimatedCost value is an estimate of the cost of doing the
-** particular lookup. A full scan of a table with N entries should have
-** a cost of N. A binary search of a table of N entries should have a
-** cost of approximately log(N).
-*/
-struct sqlite3_index_info {
- /* Inputs */
- int nConstraint; /* Number of entries in aConstraint */
- struct sqlite3_index_constraint {
- int iColumn; /* Column on left-hand side of constraint */
- unsigned char op; /* Constraint operator */
- unsigned char usable; /* True if this constraint is usable */
- int iTermOffset; /* Used internally - xBestIndex should ignore */
- } *aConstraint; /* Table of WHERE clause constraints */
- int nOrderBy; /* Number of terms in the ORDER BY clause */
- struct sqlite3_index_orderby {
- int iColumn; /* Column number */
- unsigned char desc; /* True for DESC. False for ASC. */
- } *aOrderBy; /* The ORDER BY clause */
- /* Outputs */
- struct sqlite3_index_constraint_usage {
- int argvIndex; /* if >0, constraint is part of argv to xFilter */
- unsigned char omit; /* Do not code a test for this constraint */
- } *aConstraintUsage;
- int idxNum; /* Number used to identify the index */
- char *idxStr; /* String, possibly obtained from sqlite3_malloc */
- int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
- int orderByConsumed; /* True if output is already ordered */
- double estimatedCost; /* Estimated cost of using this index */
-};
-#define SQLITE_INDEX_CONSTRAINT_EQ 2
-#define SQLITE_INDEX_CONSTRAINT_GT 4
-#define SQLITE_INDEX_CONSTRAINT_LE 8
-#define SQLITE_INDEX_CONSTRAINT_LT 16
-#define SQLITE_INDEX_CONSTRAINT_GE 32
-#define SQLITE_INDEX_CONSTRAINT_MATCH 64
-
-/*
-** CAPI3REF: Register A Virtual Table Implementation
-** EXPERIMENTAL
-**
-** ^These routines are used to register a new [virtual table module] name.
-** ^Module names must be registered before
-** creating a new [virtual table] using the module and before using a
-** preexisting [virtual table] for the module.
-**
-** ^The module name is registered on the [database connection] specified
-** by the first parameter. ^The name of the module is given by the
-** second parameter. ^The third parameter is a pointer to
-** the implementation of the [virtual table module]. ^The fourth
-** parameter is an arbitrary client data pointer that is passed through
-** into the [xCreate] and [xConnect] methods of the virtual table module
-** when a new virtual table is be being created or reinitialized.
-**
-** ^The sqlite3_create_module_v2() interface has a fifth parameter which
-** is a pointer to a destructor for the pClientData. ^SQLite will
-** invoke the destructor function (if it is not NULL) when SQLite
-** no longer needs the pClientData pointer. ^The sqlite3_create_module()
-** interface is equivalent to sqlite3_create_module_v2() with a NULL
-** destructor.
-*/
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
- sqlite3 *db, /* SQLite connection to register module with */
- const char *zName, /* Name of the module */
- const sqlite3_module *p, /* Methods for the module */
- void *pClientData /* Client data for xCreate/xConnect */
-);
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
- sqlite3 *db, /* SQLite connection to register module with */
- const char *zName, /* Name of the module */
- const sqlite3_module *p, /* Methods for the module */
- void *pClientData, /* Client data for xCreate/xConnect */
- void(*xDestroy)(void*) /* Module destructor function */
-);
-
-/*
-** CAPI3REF: Virtual Table Instance Object
-** KEYWORDS: sqlite3_vtab
-** EXPERIMENTAL
-**
-** Every [virtual table module] implementation uses a subclass
-** of this object to describe a particular instance
-** of the [virtual table]. Each subclass will
-** be tailored to the specific needs of the module implementation.
-** The purpose of this superclass is to define certain fields that are
-** common to all module implementations.
-**
-** ^Virtual tables methods can set an error message by assigning a
-** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
-** take care that any prior string is freed by a call to [sqlite3_free()]
-** prior to assigning a new string to zErrMsg. ^After the error message
-** is delivered up to the client application, the string will be automatically
-** freed by sqlite3_free() and the zErrMsg field will be zeroed.
-*/
-struct sqlite3_vtab {
- const sqlite3_module *pModule; /* The module for this virtual table */
- int nRef; /* NO LONGER USED */
- char *zErrMsg; /* Error message from sqlite3_mprintf() */
- /* Virtual table implementations will typically add additional fields */
-};
-
-/*
-** CAPI3REF: Virtual Table Cursor Object
-** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
-** EXPERIMENTAL
-**
-** Every [virtual table module] implementation uses a subclass of the
-** following structure to describe cursors that point into the
-** [virtual table] and are used
-** to loop through the virtual table. Cursors are created using the
-** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
-** by the [sqlite3_module.xClose | xClose] method. Cursors are used
-** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
-** of the module. Each module implementation will define
-** the content of a cursor structure to suit its own needs.
-**
-** This superclass exists in order to define fields of the cursor that
-** are common to all implementations.
-*/
-struct sqlite3_vtab_cursor {
- sqlite3_vtab *pVtab; /* Virtual table of this cursor */
- /* Virtual table implementations will typically add additional fields */
-};
-
-/*
-** CAPI3REF: Declare The Schema Of A Virtual Table
-** EXPERIMENTAL
-**
-** ^The [xCreate] and [xConnect] methods of a
-** [virtual table module] call this interface
-** to declare the format (the names and datatypes of the columns) of
-** the virtual tables they implement.
-*/
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
-
-/*
-** CAPI3REF: Overload A Function For A Virtual Table
-** EXPERIMENTAL
-**
-** ^(Virtual tables can provide alternative implementations of functions
-** using the [xFindFunction] method of the [virtual table module].
-** But global versions of those functions
-** must exist in order to be overloaded.)^
-**
-** ^(This API makes sure a global version of a function with a particular
-** name and number of parameters exists. If no such function exists
-** before this API is called, a new function is created.)^ ^The implementation
-** of the new function always causes an exception to be thrown. So
-** the new function is not good for anything by itself. Its only
-** purpose is to be a placeholder function that can be overloaded
-** by a [virtual table].
-*/
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
-
-/*
-** The interface to the virtual-table mechanism defined above (back up
-** to a comment remarkably similar to this one) is currently considered
-** to be experimental. The interface might change in incompatible ways.
-** If this is a problem for you, do not use the interface at this time.
-**
-** When the virtual-table mechanism stabilizes, we will declare the
-** interface fixed, support it indefinitely, and remove this comment.
-**
-****** EXPERIMENTAL - subject to change without notice **************
-*/
-
-/*
-** CAPI3REF: A Handle To An Open BLOB
-** KEYWORDS: {BLOB handle} {BLOB handles}
-**
-** An instance of this object represents an open BLOB on which
-** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
-** ^Objects of this type are created by [sqlite3_blob_open()]
-** and destroyed by [sqlite3_blob_close()].
-** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
-** can be used to read or write small subsections of the BLOB.
-** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
-*/
-typedef struct sqlite3_blob sqlite3_blob;
-
-/*
-** CAPI3REF: Open A BLOB For Incremental I/O
-**
-** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
-** in row iRow, column zColumn, table zTable in database zDb;
-** in other words, the same BLOB that would be selected by:
-**
-**
-** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
-**
)^
-**
-** ^If the flags parameter is non-zero, then the BLOB is opened for read
-** and write access. ^If it is zero, the BLOB is opened for read access.
-** ^It is not possible to open a column that is part of an index or primary
-** key for writing. ^If [foreign key constraints] are enabled, it is
-** not possible to open a column that is part of a [child key] for writing.
-**
-** ^Note that the database name is not the filename that contains
-** the database but rather the symbolic name of the database that
-** appears after the AS keyword when the database is connected using [ATTACH].
-** ^For the main database file, the database name is "main".
-** ^For TEMP tables, the database name is "temp".
-**
-** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
-** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
-** to be a null pointer.)^
-** ^This function sets the [database connection] error code and message
-** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
-** functions. ^Note that the *ppBlob variable is always initialized in a
-** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
-** regardless of the success or failure of this routine.
-**
-** ^(If the row that a BLOB handle points to is modified by an
-** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
-** then the BLOB handle is marked as "expired".
-** This is true if any column of the row is changed, even a column
-** other than the one the BLOB handle is open on.)^
-** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
-** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
-** ^(Changes written into a BLOB prior to the BLOB expiring are not
-** rolled back by the expiration of the BLOB. Such changes will eventually
-** commit if the transaction continues to completion.)^
-**
-** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
-** the opened blob. ^The size of a blob may not be changed by this
-** interface. Use the [UPDATE] SQL command to change the size of a
-** blob.
-**
-** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
-** and the built-in [zeroblob] SQL function can be used, if desired,
-** to create an empty, zero-filled blob in which to read or write using
-** this interface.
-**
-** To avoid a resource leak, every open [BLOB handle] should eventually
-** be released by a call to [sqlite3_blob_close()].
-*/
-SQLITE_API int sqlite3_blob_open(
- sqlite3*,
- const char *zDb,
- const char *zTable,
- const char *zColumn,
- sqlite3_int64 iRow,
- int flags,
- sqlite3_blob **ppBlob
-);
-
-/*
-** CAPI3REF: Close A BLOB Handle
-**
-** ^Closes an open [BLOB handle].
-**
-** ^Closing a BLOB shall cause the current transaction to commit
-** if there are no other BLOBs, no pending prepared statements, and the
-** database connection is in [autocommit mode].
-** ^If any writes were made to the BLOB, they might be held in cache
-** until the close operation if they will fit.
-**
-** ^(Closing the BLOB often forces the changes
-** out to disk and so if any I/O errors occur, they will likely occur
-** at the time when the BLOB is closed. Any errors that occur during
-** closing are reported as a non-zero return value.)^
-**
-** ^(The BLOB is closed unconditionally. Even if this routine returns
-** an error code, the BLOB is still closed.)^
-**
-** ^Calling this routine with a null pointer (such as would be returned
-** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
-*/
-SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
-
-/*
-** CAPI3REF: Return The Size Of An Open BLOB
-**
-** ^Returns the size in bytes of the BLOB accessible via the
-** successfully opened [BLOB handle] in its only argument. ^The
-** incremental blob I/O routines can only read or overwriting existing
-** blob content; they cannot change the size of a blob.
-**
-** This routine only works on a [BLOB handle] which has been created
-** by a prior successful call to [sqlite3_blob_open()] and which has not
-** been closed by [sqlite3_blob_close()]. Passing any other pointer in
-** to this routine results in undefined and probably undesirable behavior.
-*/
-SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
-
-/*
-** CAPI3REF: Read Data From A BLOB Incrementally
-**
-** ^(This function is used to read data from an open [BLOB handle] into a
-** caller-supplied buffer. N bytes of data are copied into buffer Z
-** from the open BLOB, starting at offset iOffset.)^
-**
-** ^If offset iOffset is less than N bytes from the end of the BLOB,
-** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
-** less than zero, [SQLITE_ERROR] is returned and no data is read.
-** ^The size of the blob (and hence the maximum value of N+iOffset)
-** can be determined using the [sqlite3_blob_bytes()] interface.
-**
-** ^An attempt to read from an expired [BLOB handle] fails with an
-** error code of [SQLITE_ABORT].
-**
-** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
-** Otherwise, an [error code] or an [extended error code] is returned.)^
-**
-** This routine only works on a [BLOB handle] which has been created
-** by a prior successful call to [sqlite3_blob_open()] and which has not
-** been closed by [sqlite3_blob_close()]. Passing any other pointer in
-** to this routine results in undefined and probably undesirable behavior.
-**
-** See also: [sqlite3_blob_write()].
-*/
-SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
-
-/*
-** CAPI3REF: Write Data Into A BLOB Incrementally
-**
-** ^This function is used to write data into an open [BLOB handle] from a
-** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
-** into the open BLOB, starting at offset iOffset.
-**
-** ^If the [BLOB handle] passed as the first argument was not opened for
-** writing (the flags parameter to [sqlite3_blob_open()] was zero),
-** this function returns [SQLITE_READONLY].
-**
-** ^This function may only modify the contents of the BLOB; it is
-** not possible to increase the size of a BLOB using this API.
-** ^If offset iOffset is less than N bytes from the end of the BLOB,
-** [SQLITE_ERROR] is returned and no data is written. ^If N is
-** less than zero [SQLITE_ERROR] is returned and no data is written.
-** The size of the BLOB (and hence the maximum value of N+iOffset)
-** can be determined using the [sqlite3_blob_bytes()] interface.
-**
-** ^An attempt to write to an expired [BLOB handle] fails with an
-** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
-** before the [BLOB handle] expired are not rolled back by the
-** expiration of the handle, though of course those changes might
-** have been overwritten by the statement that expired the BLOB handle
-** or by other independent statements.
-**
-** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
-** Otherwise, an [error code] or an [extended error code] is returned.)^
-**
-** This routine only works on a [BLOB handle] which has been created
-** by a prior successful call to [sqlite3_blob_open()] and which has not
-** been closed by [sqlite3_blob_close()]. Passing any other pointer in
-** to this routine results in undefined and probably undesirable behavior.
-**
-** See also: [sqlite3_blob_read()].
-*/
-SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
-
-/*
-** CAPI3REF: Virtual File System Objects
-**
-** A virtual filesystem (VFS) is an [sqlite3_vfs] object
-** that SQLite uses to interact
-** with the underlying operating system. Most SQLite builds come with a
-** single default VFS that is appropriate for the host computer.
-** New VFSes can be registered and existing VFSes can be unregistered.
-** The following interfaces are provided.
-**
-** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
-** ^Names are case sensitive.
-** ^Names are zero-terminated UTF-8 strings.
-** ^If there is no match, a NULL pointer is returned.
-** ^If zVfsName is NULL then the default VFS is returned.
-**
-** ^New VFSes are registered with sqlite3_vfs_register().
-** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
-** ^The same VFS can be registered multiple times without injury.
-** ^To make an existing VFS into the default VFS, register it again
-** with the makeDflt flag set. If two different VFSes with the
-** same name are registered, the behavior is undefined. If a
-** VFS is registered with a name that is NULL or an empty string,
-** then the behavior is undefined.
-**
-** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
-** ^(If the default VFS is unregistered, another VFS is chosen as
-** the default. The choice for the new VFS is arbitrary.)^
-*/
-SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
-SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
-SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
-
-/*
-** CAPI3REF: Mutexes
-**
-** The SQLite core uses these routines for thread
-** synchronization. Though they are intended for internal
-** use by SQLite, code that links against SQLite is
-** permitted to use any of these routines.
-**
-** The SQLite source code contains multiple implementations
-** of these mutex routines. An appropriate implementation
-** is selected automatically at compile-time. ^(The following
-** implementations are available in the SQLite core:
-**
-**
-**
SQLITE_MUTEX_OS2
-**
SQLITE_MUTEX_PTHREAD
-**
SQLITE_MUTEX_W32
-**
SQLITE_MUTEX_NOOP
-**
)^
-**
-** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
-** that does no real locking and is appropriate for use in
-** a single-threaded application. ^The SQLITE_MUTEX_OS2,
-** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
-** are appropriate for use on OS/2, Unix, and Windows.
-**
-** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
-** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
-** implementation is included with the library. In this case the
-** application must supply a custom mutex implementation using the
-** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
-** before calling sqlite3_initialize() or any other public sqlite3_
-** function that calls sqlite3_initialize().)^
-**
-** ^The sqlite3_mutex_alloc() routine allocates a new
-** mutex and returns a pointer to it. ^If it returns NULL
-** that means that a mutex could not be allocated. ^SQLite
-** will unwind its stack and return an error. ^(The argument
-** to sqlite3_mutex_alloc() is one of these integer constants:
-**
-**
-**
SQLITE_MUTEX_FAST
-**
SQLITE_MUTEX_RECURSIVE
-**
SQLITE_MUTEX_STATIC_MASTER
-**
SQLITE_MUTEX_STATIC_MEM
-**
SQLITE_MUTEX_STATIC_MEM2
-**
SQLITE_MUTEX_STATIC_PRNG
-**
SQLITE_MUTEX_STATIC_LRU
-**
SQLITE_MUTEX_STATIC_LRU2
-**
)^
-**
-** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
-** cause sqlite3_mutex_alloc() to create
-** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
-** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
-** The mutex implementation does not need to make a distinction
-** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
-** not want to. ^SQLite will only request a recursive mutex in
-** cases where it really needs one. ^If a faster non-recursive mutex
-** implementation is available on the host platform, the mutex subsystem
-** might return such a mutex in response to SQLITE_MUTEX_FAST.
-**
-** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
-** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
-** a pointer to a static preexisting mutex. ^Six static mutexes are
-** used by the current version of SQLite. Future versions of SQLite
-** may add additional static mutexes. Static mutexes are for internal
-** use by SQLite only. Applications that use SQLite mutexes should
-** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
-** SQLITE_MUTEX_RECURSIVE.
-**
-** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
-** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
-** returns a different mutex on every call. ^But for the static
-** mutex types, the same mutex is returned on every call that has
-** the same type number.
-**
-** ^The sqlite3_mutex_free() routine deallocates a previously
-** allocated dynamic mutex. ^SQLite is careful to deallocate every
-** dynamic mutex that it allocates. The dynamic mutexes must not be in
-** use when they are deallocated. Attempting to deallocate a static
-** mutex results in undefined behavior. ^SQLite never deallocates
-** a static mutex.
-**
-** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
-** to enter a mutex. ^If another thread is already within the mutex,
-** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
-** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
-** upon successful entry. ^(Mutexes created using
-** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
-** In such cases the,
-** mutex must be exited an equal number of times before another thread
-** can enter.)^ ^(If the same thread tries to enter any other
-** kind of mutex more than once, the behavior is undefined.
-** SQLite will never exhibit
-** such behavior in its own use of mutexes.)^
-**
-** ^(Some systems (for example, Windows 95) do not support the operation
-** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
-** will always return SQLITE_BUSY. The SQLite core only ever uses
-** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
-**
-** ^The sqlite3_mutex_leave() routine exits a mutex that was
-** previously entered by the same thread. ^(The behavior
-** is undefined if the mutex is not currently entered by the
-** calling thread or is not currently allocated. SQLite will
-** never do either.)^
-**
-** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
-** sqlite3_mutex_leave() is a NULL pointer, then all three routines
-** behave as no-ops.
-**
-** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
-*/
-SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
-SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
-SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
-SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
-SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
-
-/*
-** CAPI3REF: Mutex Methods Object
-** EXPERIMENTAL
-**
-** An instance of this structure defines the low-level routines
-** used to allocate and use mutexes.
-**
-** Usually, the default mutex implementations provided by SQLite are
-** sufficient, however the user has the option of substituting a custom
-** implementation for specialized deployments or systems for which SQLite
-** does not provide a suitable implementation. In this case, the user
-** creates and populates an instance of this structure to pass
-** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
-** Additionally, an instance of this structure can be used as an
-** output variable when querying the system for the current mutex
-** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
-**
-** ^The xMutexInit method defined by this structure is invoked as
-** part of system initialization by the sqlite3_initialize() function.
-** ^The xMutexInit routine is calle by SQLite exactly once for each
-** effective call to [sqlite3_initialize()].
-**
-** ^The xMutexEnd method defined by this structure is invoked as
-** part of system shutdown by the sqlite3_shutdown() function. The
-** implementation of this method is expected to release all outstanding
-** resources obtained by the mutex methods implementation, especially
-** those obtained by the xMutexInit method. ^The xMutexEnd()
-** interface is invoked exactly once for each call to [sqlite3_shutdown()].
-**
-** ^(The remaining seven methods defined by this structure (xMutexAlloc,
-** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
-** xMutexNotheld) implement the following interfaces (respectively):
-**
-**
-**
[sqlite3_mutex_alloc()]
-**
[sqlite3_mutex_free()]
-**
[sqlite3_mutex_enter()]
-**
[sqlite3_mutex_try()]
-**
[sqlite3_mutex_leave()]
-**
[sqlite3_mutex_held()]
-**
[sqlite3_mutex_notheld()]
-**
)^
-**
-** The only difference is that the public sqlite3_XXX functions enumerated
-** above silently ignore any invocations that pass a NULL pointer instead
-** of a valid mutex handle. The implementations of the methods defined
-** by this structure are not required to handle this case, the results
-** of passing a NULL pointer instead of a valid mutex handle are undefined
-** (i.e. it is acceptable to provide an implementation that segfaults if
-** it is passed a NULL pointer).
-**
-** The xMutexInit() method must be threadsafe. ^It must be harmless to
-** invoke xMutexInit() mutiple times within the same process and without
-** intervening calls to xMutexEnd(). Second and subsequent calls to
-** xMutexInit() must be no-ops.
-**
-** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
-** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
-** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
-** memory allocation for a fast or recursive mutex.
-**
-** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
-** called, but only if the prior call to xMutexInit returned SQLITE_OK.
-** If xMutexInit fails in any way, it is expected to clean up after itself
-** prior to returning.
-*/
-typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
-struct sqlite3_mutex_methods {
- int (*xMutexInit)(void);
- int (*xMutexEnd)(void);
- sqlite3_mutex *(*xMutexAlloc)(int);
- void (*xMutexFree)(sqlite3_mutex *);
- void (*xMutexEnter)(sqlite3_mutex *);
- int (*xMutexTry)(sqlite3_mutex *);
- void (*xMutexLeave)(sqlite3_mutex *);
- int (*xMutexHeld)(sqlite3_mutex *);
- int (*xMutexNotheld)(sqlite3_mutex *);
-};
-
-/*
-** CAPI3REF: Mutex Verification Routines
-**
-** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
-** are intended for use inside assert() statements. ^The SQLite core
-** never uses these routines except inside an assert() and applications
-** are advised to follow the lead of the core. ^The SQLite core only
-** provides implementations for these routines when it is compiled
-** with the SQLITE_DEBUG flag. ^External mutex implementations
-** are only required to provide these routines if SQLITE_DEBUG is
-** defined and if NDEBUG is not defined.
-**
-** ^These routines should return true if the mutex in their argument
-** is held or not held, respectively, by the calling thread.
-**
-** ^The implementation is not required to provided versions of these
-** routines that actually work. If the implementation does not provide working
-** versions of these routines, it should at least provide stubs that always
-** return true so that one does not get spurious assertion failures.
-**
-** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
-** the routine should return 1. This seems counter-intuitive since
-** clearly the mutex cannot be held if it does not exist. But the
-** the reason the mutex does not exist is because the build is not
-** using mutexes. And we do not want the assert() containing the
-** call to sqlite3_mutex_held() to fail, so a non-zero return is
-** the appropriate thing to do. ^The sqlite3_mutex_notheld()
-** interface should also return 1 when given a NULL pointer.
-*/
-#ifndef NDEBUG
-SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
-SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
-#endif
-
-/*
-** CAPI3REF: Mutex Types
-**
-** The [sqlite3_mutex_alloc()] interface takes a single argument
-** which is one of these integer constants.
-**
-** The set of static mutexes may change from one SQLite release to the
-** next. Applications that override the built-in mutex logic must be
-** prepared to accommodate additional static mutexes.
-*/
-#define SQLITE_MUTEX_FAST 0
-#define SQLITE_MUTEX_RECURSIVE 1
-#define SQLITE_MUTEX_STATIC_MASTER 2
-#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
-#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
-#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
-#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
-#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
-#define SQLITE_MUTEX_STATIC_LRU2 7 /* lru page list */
-
-/*
-** CAPI3REF: Retrieve the mutex for a database connection
-**
-** ^This interface returns a pointer the [sqlite3_mutex] object that
-** serializes access to the [database connection] given in the argument
-** when the [threading mode] is Serialized.
-** ^If the [threading mode] is Single-thread or Multi-thread then this
-** routine returns a NULL pointer.
-*/
-SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
-
-/*
-** CAPI3REF: Low-Level Control Of Database Files
-**
-** ^The [sqlite3_file_control()] interface makes a direct call to the
-** xFileControl method for the [sqlite3_io_methods] object associated
-** with a particular database identified by the second argument. ^The
-** name of the database "main" for the main database or "temp" for the
-** TEMP database, or the name that appears after the AS keyword for
-** databases that are added using the [ATTACH] SQL command.
-** ^A NULL pointer can be used in place of "main" to refer to the
-** main database file.
-** ^The third and fourth parameters to this routine
-** are passed directly through to the second and third parameters of
-** the xFileControl method. ^The return value of the xFileControl
-** method becomes the return value of this routine.
-**
-** ^If the second parameter (zDbName) does not match the name of any
-** open database file, then SQLITE_ERROR is returned. ^This error
-** code is not remembered and will not be recalled by [sqlite3_errcode()]
-** or [sqlite3_errmsg()]. The underlying xFileControl method might
-** also return SQLITE_ERROR. There is no way to distinguish between
-** an incorrect zDbName and an SQLITE_ERROR return from the underlying
-** xFileControl method.
-**
-** See also: [SQLITE_FCNTL_LOCKSTATE]
-*/
-SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
-
-/*
-** CAPI3REF: Testing Interface
-**
-** ^The sqlite3_test_control() interface is used to read out internal
-** state of SQLite and to inject faults into SQLite for testing
-** purposes. ^The first parameter is an operation code that determines
-** the number, meaning, and operation of all subsequent parameters.
-**
-** This interface is not for use by applications. It exists solely
-** for verifying the correct operation of the SQLite library. Depending
-** on how the SQLite library is compiled, this interface might not exist.
-**
-** The details of the operation codes, their meanings, the parameters
-** they take, and what they do are all subject to change without notice.
-** Unlike most of the SQLite API, this function is not guaranteed to
-** operate consistently from one release to the next.
-*/
-SQLITE_API int sqlite3_test_control(int op, ...);
-
-/*
-** CAPI3REF: Testing Interface Operation Codes
-**
-** These constants are the valid operation code parameters used
-** as the first argument to [sqlite3_test_control()].
-**
-** These parameters and their meanings are subject to change
-** without notice. These values are for testing purposes only.
-** Applications should not use any of these parameters or the
-** [sqlite3_test_control()] interface.
-*/
-#define SQLITE_TESTCTRL_FIRST 5
-#define SQLITE_TESTCTRL_PRNG_SAVE 5
-#define SQLITE_TESTCTRL_PRNG_RESTORE 6
-#define SQLITE_TESTCTRL_PRNG_RESET 7
-#define SQLITE_TESTCTRL_BITVEC_TEST 8
-#define SQLITE_TESTCTRL_FAULT_INSTALL 9
-#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
-#define SQLITE_TESTCTRL_PENDING_BYTE 11
-#define SQLITE_TESTCTRL_ASSERT 12
-#define SQLITE_TESTCTRL_ALWAYS 13
-#define SQLITE_TESTCTRL_RESERVE 14
-#define SQLITE_TESTCTRL_OPTIMIZATIONS 15
-#define SQLITE_TESTCTRL_ISKEYWORD 16
-#define SQLITE_TESTCTRL_LAST 16
-
-/*
-** CAPI3REF: SQLite Runtime Status
-** EXPERIMENTAL
-**
-** ^This interface is used to retrieve runtime status information
-** about the preformance of SQLite, and optionally to reset various
-** highwater marks. ^The first argument is an integer code for
-** the specific parameter to measure. ^(Recognized integer codes
-** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
-** ^The current value of the parameter is returned into *pCurrent.
-** ^The highest recorded value is returned in *pHighwater. ^If the
-** resetFlag is true, then the highest record value is reset after
-** *pHighwater is written. ^(Some parameters do not record the highest
-** value. For those parameters
-** nothing is written into *pHighwater and the resetFlag is ignored.)^
-** ^(Other parameters record only the highwater mark and not the current
-** value. For these latter parameters nothing is written into *pCurrent.)^
-**
-** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
-** non-zero [error code] on failure.
-**
-** This routine is threadsafe but is not atomic. This routine can be
-** called while other threads are running the same or different SQLite
-** interfaces. However the values returned in *pCurrent and
-** *pHighwater reflect the status of SQLite at different points in time
-** and it is possible that another thread might change the parameter
-** in between the times when *pCurrent and *pHighwater are written.
-**
-** See also: [sqlite3_db_status()]
-*/
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
-
-
-/*
-** CAPI3REF: Status Parameters
-** EXPERIMENTAL
-**
-** These integer constants designate various run-time status parameters
-** that can be returned by [sqlite3_status()].
-**
-**
-** ^(
SQLITE_STATUS_MEMORY_USED
-**
This parameter is the current amount of memory checked out
-** using [sqlite3_malloc()], either directly or indirectly. The
-** figure includes calls made to [sqlite3_malloc()] by the application
-** and internal memory usage by the SQLite library. Scratch memory
-** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
-** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
-** this parameter. The amount returned is the sum of the allocation
-** sizes as reported by the xSize method in [sqlite3_mem_methods].
)^
-**
-** ^(
SQLITE_STATUS_MALLOC_SIZE
-**
This parameter records the largest memory allocation request
-** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
-** internal equivalents). Only the value returned in the
-** *pHighwater parameter to [sqlite3_status()] is of interest.
-** The value written into the *pCurrent parameter is undefined.
)^
-**
-** ^(
SQLITE_STATUS_PAGECACHE_USED
-**
This parameter returns the number of pages used out of the
-** [pagecache memory allocator] that was configured using
-** [SQLITE_CONFIG_PAGECACHE]. The
-** value returned is in pages, not in bytes.
)^
-**
-** ^(
SQLITE_STATUS_PAGECACHE_OVERFLOW
-**
This parameter returns the number of bytes of page cache
-** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
-** buffer and where forced to overflow to [sqlite3_malloc()]. The
-** returned value includes allocations that overflowed because they
-** where too large (they were larger than the "sz" parameter to
-** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
-** no space was left in the page cache.
)^
-**
-** ^(
SQLITE_STATUS_PAGECACHE_SIZE
-**
This parameter records the largest memory allocation request
-** handed to [pagecache memory allocator]. Only the value returned in the
-** *pHighwater parameter to [sqlite3_status()] is of interest.
-** The value written into the *pCurrent parameter is undefined.
)^
-**
-** ^(
SQLITE_STATUS_SCRATCH_USED
-**
This parameter returns the number of allocations used out of the
-** [scratch memory allocator] configured using
-** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
-** in bytes. Since a single thread may only have one scratch allocation
-** outstanding at time, this parameter also reports the number of threads
-** using scratch memory at the same time.
)^
-**
-** ^(
SQLITE_STATUS_SCRATCH_OVERFLOW
-**
This parameter returns the number of bytes of scratch memory
-** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
-** buffer and where forced to overflow to [sqlite3_malloc()]. The values
-** returned include overflows because the requested allocation was too
-** larger (that is, because the requested allocation was larger than the
-** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
-** slots were available.
-**
)^
-**
-** ^(
SQLITE_STATUS_SCRATCH_SIZE
-**
This parameter records the largest memory allocation request
-** handed to [scratch memory allocator]. Only the value returned in the
-** *pHighwater parameter to [sqlite3_status()] is of interest.
-** The value written into the *pCurrent parameter is undefined.
)^
-**
-** ^(
SQLITE_STATUS_PARSER_STACK
-**
This parameter records the deepest parser stack. It is only
-** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
)^
-**
-**
-** New status parameters may be added from time to time.
-*/
-#define SQLITE_STATUS_MEMORY_USED 0
-#define SQLITE_STATUS_PAGECACHE_USED 1
-#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
-#define SQLITE_STATUS_SCRATCH_USED 3
-#define SQLITE_STATUS_SCRATCH_OVERFLOW 4
-#define SQLITE_STATUS_MALLOC_SIZE 5
-#define SQLITE_STATUS_PARSER_STACK 6
-#define SQLITE_STATUS_PAGECACHE_SIZE 7
-#define SQLITE_STATUS_SCRATCH_SIZE 8
-
-/*
-** CAPI3REF: Database Connection Status
-** EXPERIMENTAL
-**
-** ^This interface is used to retrieve runtime status information
-** about a single [database connection]. ^The first argument is the
-** database connection object to be interrogated. ^The second argument
-** is the parameter to interrogate. ^Currently, the only allowed value
-** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
-** Additional options will likely appear in future releases of SQLite.
-**
-** ^The current value of the requested parameter is written into *pCur
-** and the highest instantaneous value is written into *pHiwtr. ^If
-** the resetFlg is true, then the highest instantaneous value is
-** reset back down to the current value.
-**
-** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
-*/
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
-
-/*
-** CAPI3REF: Status Parameters for database connections
-** EXPERIMENTAL
-**
-** These constants are the available integer "verbs" that can be passed as
-** the second argument to the [sqlite3_db_status()] interface.
-**
-** New verbs may be added in future releases of SQLite. Existing verbs
-** might be discontinued. Applications should check the return code from
-** [sqlite3_db_status()] to make sure that the call worked.
-** The [sqlite3_db_status()] interface will return a non-zero error code
-** if a discontinued or unsupported verb is invoked.
-**
-**
-** ^(
SQLITE_DBSTATUS_LOOKASIDE_USED
-**
This parameter returns the number of lookaside memory slots currently
-** checked out.
)^
-**
-*/
-#define SQLITE_DBSTATUS_LOOKASIDE_USED 0
-
-
-/*
-** CAPI3REF: Prepared Statement Status
-** EXPERIMENTAL
-**
-** ^(Each prepared statement maintains various
-** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
-** of times it has performed specific operations.)^ These counters can
-** be used to monitor the performance characteristics of the prepared
-** statements. For example, if the number of table steps greatly exceeds
-** the number of table searches or result rows, that would tend to indicate
-** that the prepared statement is using a full table scan rather than
-** an index.
-**
-** ^(This interface is used to retrieve and reset counter values from
-** a [prepared statement]. The first argument is the prepared statement
-** object to be interrogated. The second argument
-** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
-** to be interrogated.)^
-** ^The current value of the requested counter is returned.
-** ^If the resetFlg is true, then the counter is reset to zero after this
-** interface call returns.
-**
-** See also: [sqlite3_status()] and [sqlite3_db_status()].
-*/
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
-
-/*
-** CAPI3REF: Status Parameters for prepared statements
-** EXPERIMENTAL
-**
-** These preprocessor macros define integer codes that name counter
-** values associated with the [sqlite3_stmt_status()] interface.
-** The meanings of the various counters are as follows:
-**
-**
-**
SQLITE_STMTSTATUS_FULLSCAN_STEP
-**
^This is the number of times that SQLite has stepped forward in
-** a table as part of a full table scan. Large numbers for this counter
-** may indicate opportunities for performance improvement through
-** careful use of indices.
-**
-**
SQLITE_STMTSTATUS_SORT
-**
^This is the number of sort operations that have occurred.
-** A non-zero value in this counter may indicate an opportunity to
-** improvement performance through careful use of indices.
-**
-**
-*/
-#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
-#define SQLITE_STMTSTATUS_SORT 2
-
-/*
-** CAPI3REF: Custom Page Cache Object
-** EXPERIMENTAL
-**
-** The sqlite3_pcache type is opaque. It is implemented by
-** the pluggable module. The SQLite core has no knowledge of
-** its size or internal structure and never deals with the
-** sqlite3_pcache object except by holding and passing pointers
-** to the object.
-**
-** See [sqlite3_pcache_methods] for additional information.
-*/
-typedef struct sqlite3_pcache sqlite3_pcache;
-
-/*
-** CAPI3REF: Application Defined Page Cache.
-** KEYWORDS: {page cache}
-** EXPERIMENTAL
-**
-** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
-** register an alternative page cache implementation by passing in an
-** instance of the sqlite3_pcache_methods structure.)^ The majority of the
-** heap memory used by SQLite is used by the page cache to cache data read
-** from, or ready to be written to, the database file. By implementing a
-** custom page cache using this API, an application can control more
-** precisely the amount of memory consumed by SQLite, the way in which
-** that memory is allocated and released, and the policies used to
-** determine exactly which parts of a database file are cached and for
-** how long.
-**
-** ^(The contents of the sqlite3_pcache_methods structure are copied to an
-** internal buffer by SQLite within the call to [sqlite3_config]. Hence
-** the application may discard the parameter after the call to
-** [sqlite3_config()] returns.)^
-**
-** ^The xInit() method is called once for each call to [sqlite3_initialize()]
-** (usually only once during the lifetime of the process). ^(The xInit()
-** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
-** ^The xInit() method can set up up global structures and/or any mutexes
-** required by the custom page cache implementation.
-**
-** ^The xShutdown() method is called from within [sqlite3_shutdown()],
-** if the application invokes this API. It can be used to clean up
-** any outstanding resources before process shutdown, if required.
-**
-** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
-** the xInit method, so the xInit method need not be threadsafe. ^The
-** xShutdown method is only called from [sqlite3_shutdown()] so it does
-** not need to be threadsafe either. All other methods must be threadsafe
-** in multithreaded applications.
-**
-** ^SQLite will never invoke xInit() more than once without an intervening
-** call to xShutdown().
-**
-** ^The xCreate() method is used to construct a new cache instance. SQLite
-** will typically create one cache instance for each open database file,
-** though this is not guaranteed. ^The
-** first parameter, szPage, is the size in bytes of the pages that must
-** be allocated by the cache. ^szPage will not be a power of two. ^szPage
-** will the page size of the database file that is to be cached plus an
-** increment (here called "R") of about 100 or 200. ^SQLite will use the
-** extra R bytes on each page to store metadata about the underlying
-** database page on disk. The value of R depends
-** on the SQLite version, the target platform, and how SQLite was compiled.
-** ^R is constant for a particular build of SQLite. ^The second argument to
-** xCreate(), bPurgeable, is true if the cache being created will
-** be used to cache database pages of a file stored on disk, or
-** false if it is used for an in-memory database. ^The cache implementation
-** does not have to do anything special based with the value of bPurgeable;
-** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
-** never invoke xUnpin() except to deliberately delete a page.
-** ^In other words, a cache created with bPurgeable set to false will
-** never contain any unpinned pages.
-**
-** ^(The xCachesize() method may be called at any time by SQLite to set the
-** suggested maximum cache-size (number of pages stored by) the cache
-** instance passed as the first argument. This is the value configured using
-** the SQLite "[PRAGMA cache_size]" command.)^ ^As with the bPurgeable
-** parameter, the implementation is not required to do anything with this
-** value; it is advisory only.
-**
-** ^The xPagecount() method should return the number of pages currently
-** stored in the cache.
-**
-** ^The xFetch() method is used to fetch a page and return a pointer to it.
-** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
-** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
-** mimimum key value is 1. After it has been retrieved using xFetch, the page
-** is considered to be "pinned".
-**
-** ^If the requested page is already in the page cache, then the page cache
-** implementation must return a pointer to the page buffer with its content
-** intact. ^(If the requested page is not already in the cache, then the
-** behavior of the cache implementation is determined by the value of the
-** createFlag parameter passed to xFetch, according to the following table:
-**
-**
-**
createFlag
Behaviour when page is not already in cache
-**
0
Do not allocate a new page. Return NULL.
-**
1
Allocate a new page if it easy and convenient to do so.
-** Otherwise return NULL.
-**
2
Make every effort to allocate a new page. Only return
-** NULL if allocating a new page is effectively impossible.
-**
)^
-**
-** SQLite will normally invoke xFetch() with a createFlag of 0 or 1. If
-** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
-** attempt to unpin one or more cache pages by spilling the content of
-** pinned pages to disk and synching the operating system disk cache. After
-** attempting to unpin pages, the xFetch() method will be invoked again with
-** a createFlag of 2.
-**
-** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
-** as its second argument. ^(If the third parameter, discard, is non-zero,
-** then the page should be evicted from the cache. In this case SQLite
-** assumes that the next time the page is retrieved from the cache using
-** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
-** zero, then the page is considered to be unpinned. ^The cache implementation
-** may choose to evict unpinned pages at any time.
-**
-** ^(The cache is not required to perform any reference counting. A single
-** call to xUnpin() unpins the page regardless of the number of prior calls
-** to xFetch().)^
-**
-** ^The xRekey() method is used to change the key value associated with the
-** page passed as the second argument from oldKey to newKey. ^If the cache
-** previously contains an entry associated with newKey, it should be
-** discarded. ^Any prior cache entry associated with newKey is guaranteed not
-** to be pinned.
-**
-** ^When SQLite calls the xTruncate() method, the cache must discard all
-** existing cache entries with page numbers (keys) greater than or equal
-** to the value of the iLimit parameter passed to xTruncate(). ^If any
-** of these pages are pinned, they are implicitly unpinned, meaning that
-** they can be safely discarded.
-**
-** ^The xDestroy() method is used to delete a cache allocated by xCreate().
-** All resources associated with the specified cache should be freed. ^After
-** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
-** handle invalid, and will not use it with any other sqlite3_pcache_methods
-** functions.
-*/
-typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
-struct sqlite3_pcache_methods {
- void *pArg;
- int (*xInit)(void*);
- void (*xShutdown)(void*);
- sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
- void (*xCachesize)(sqlite3_pcache*, int nCachesize);
- int (*xPagecount)(sqlite3_pcache*);
- void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
- void (*xUnpin)(sqlite3_pcache*, void*, int discard);
- void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
- void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
- void (*xDestroy)(sqlite3_pcache*);
-};
-
-/*
-** CAPI3REF: Online Backup Object
-** EXPERIMENTAL
-**
-** The sqlite3_backup object records state information about an ongoing
-** online backup operation. ^The sqlite3_backup object is created by
-** a call to [sqlite3_backup_init()] and is destroyed by a call to
-** [sqlite3_backup_finish()].
-**
-** See Also: [Using the SQLite Online Backup API]
-*/
-typedef struct sqlite3_backup sqlite3_backup;
-
-/*
-** CAPI3REF: Online Backup API.
-** EXPERIMENTAL
-**
-** The backup API copies the content of one database into another.
-** It is useful either for creating backups of databases or
-** for copying in-memory databases to or from persistent files.
-**
-** See Also: [Using the SQLite Online Backup API]
-**
-** ^Exclusive access is required to the destination database for the
-** duration of the operation. ^However the source database is only
-** read-locked while it is actually being read; it is not locked
-** continuously for the entire backup operation. ^Thus, the backup may be
-** performed on a live source database without preventing other users from
-** reading or writing to the source database while the backup is underway.
-**
-** ^(To perform a backup operation:
-**
-**
sqlite3_backup_init() is called once to initialize the
-** backup,
-**
sqlite3_backup_step() is called one or more times to transfer
-** the data between the two databases, and finally
-**
sqlite3_backup_finish() is called to release all resources
-** associated with the backup operation.
-**
)^
-** There should be exactly one call to sqlite3_backup_finish() for each
-** successful call to sqlite3_backup_init().
-**
-** sqlite3_backup_init()
-**
-** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
-** [database connection] associated with the destination database
-** and the database name, respectively.
-** ^The database name is "main" for the main database, "temp" for the
-** temporary database, or the name specified after the AS keyword in
-** an [ATTACH] statement for an attached database.
-** ^The S and M arguments passed to
-** sqlite3_backup_init(D,N,S,M) identify the [database connection]
-** and database name of the source database, respectively.
-** ^The source and destination [database connections] (parameters S and D)
-** must be different or else sqlite3_backup_init(D,N,S,M) will file with
-** an error.
-**
-** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
-** returned and an error code and error message are store3d in the
-** destination [database connection] D.
-** ^The error code and message for the failed call to sqlite3_backup_init()
-** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
-** [sqlite3_errmsg16()] functions.
-** ^A successful call to sqlite3_backup_init() returns a pointer to an
-** [sqlite3_backup] object.
-** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
-** sqlite3_backup_finish() functions to perform the specified backup
-** operation.
-**
-** sqlite3_backup_step()
-**
-** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
-** the source and destination databases specified by [sqlite3_backup] object B.
-** ^If N is negative, all remaining source pages are copied.
-** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
-** are still more pages to be copied, then the function resturns [SQLITE_OK].
-** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
-** from source to destination, then it returns [SQLITE_DONE].
-** ^If an error occurs while running sqlite3_backup_step(B,N),
-** then an [error code] is returned. ^As well as [SQLITE_OK] and
-** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
-** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
-** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
-**
-** ^The sqlite3_backup_step() might return [SQLITE_READONLY] if the destination
-** database was opened read-only or if
-** the destination is an in-memory database with a different page size
-** from the source database.
-**
-** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
-** the [sqlite3_busy_handler | busy-handler function]
-** is invoked (if one is specified). ^If the
-** busy-handler returns non-zero before the lock is available, then
-** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
-** sqlite3_backup_step() can be retried later. ^If the source
-** [database connection]
-** is being used to write to the source database when sqlite3_backup_step()
-** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
-** case the call to sqlite3_backup_step() can be retried later on. ^(If
-** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
-** [SQLITE_READONLY] is returned, then
-** there is no point in retrying the call to sqlite3_backup_step(). These
-** errors are considered fatal.)^ The application must accept
-** that the backup operation has failed and pass the backup operation handle
-** to the sqlite3_backup_finish() to release associated resources.
-**
-** ^The first call to sqlite3_backup_step() obtains an exclusive lock
-** on the destination file. ^The exclusive lock is not released until either
-** sqlite3_backup_finish() is called or the backup operation is complete
-** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
-** sqlite3_backup_step() obtains a [shared lock] on the source database that
-** lasts for the duration of the sqlite3_backup_step() call.
-** ^Because the source database is not locked between calls to
-** sqlite3_backup_step(), the source database may be modified mid-way
-** through the backup process. ^If the source database is modified by an
-** external process or via a database connection other than the one being
-** used by the backup operation, then the backup will be automatically
-** restarted by the next call to sqlite3_backup_step(). ^If the source
-** database is modified by the using the same database connection as is used
-** by the backup operation, then the backup database is automatically
-** updated at the same time.
-**
-** sqlite3_backup_finish()
-**
-** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
-** application wishes to abandon the backup operation, the application
-** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
-** ^The sqlite3_backup_finish() interfaces releases all
-** resources associated with the [sqlite3_backup] object.
-** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
-** active write-transaction on the destination database is rolled back.
-** The [sqlite3_backup] object is invalid
-** and may not be used following a call to sqlite3_backup_finish().
-**
-** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
-** sqlite3_backup_step() errors occurred, regardless or whether or not
-** sqlite3_backup_step() completed.
-** ^If an out-of-memory condition or IO error occurred during any prior
-** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
-** sqlite3_backup_finish() returns the corresponding [error code].
-**
-** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
-** is not a permanent error and does not affect the return value of
-** sqlite3_backup_finish().
-**
-** sqlite3_backup_remaining(), sqlite3_backup_pagecount()
-**
-** ^Each call to sqlite3_backup_step() sets two values inside
-** the [sqlite3_backup] object: the number of pages still to be backed
-** up and the total number of pages in the source databae file.
-** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
-** retrieve these two values, respectively.
-**
-** ^The values returned by these functions are only updated by
-** sqlite3_backup_step(). ^If the source database is modified during a backup
-** operation, then the values are not updated to account for any extra
-** pages that need to be updated or the size of the source database file
-** changing.
-**
-** Concurrent Usage of Database Handles
-**
-** ^The source [database connection] may be used by the application for other
-** purposes while a backup operation is underway or being initialized.
-** ^If SQLite is compiled and configured to support threadsafe database
-** connections, then the source database connection may be used concurrently
-** from within other threads.
-**
-** However, the application must guarantee that the destination
-** [database connection] is not passed to any other API (by any thread) after
-** sqlite3_backup_init() is called and before the corresponding call to
-** sqlite3_backup_finish(). SQLite does not currently check to see
-** if the application incorrectly accesses the destination [database connection]
-** and so no error code is reported, but the operations may malfunction
-** nevertheless. Use of the destination database connection while a
-** backup is in progress might also also cause a mutex deadlock.
-**
-** If running in [shared cache mode], the application must
-** guarantee that the shared cache used by the destination database
-** is not accessed while the backup is running. In practice this means
-** that the application must guarantee that the disk file being
-** backed up to is not accessed by any connection within the process,
-** not just the specific connection that was passed to sqlite3_backup_init().
-**
-** The [sqlite3_backup] object itself is partially threadsafe. Multiple
-** threads may safely make multiple concurrent calls to sqlite3_backup_step().
-** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
-** APIs are not strictly speaking threadsafe. If they are invoked at the
-** same time as another thread is invoking sqlite3_backup_step() it is
-** possible that they return invalid values.
-*/
-SQLITE_API sqlite3_backup *sqlite3_backup_init(
- sqlite3 *pDest, /* Destination database handle */
- const char *zDestName, /* Destination database name */
- sqlite3 *pSource, /* Source database handle */
- const char *zSourceName /* Source database name */
-);
-SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
-SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
-SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
-SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
-
-/*
-** CAPI3REF: Unlock Notification
-** EXPERIMENTAL
-**
-** ^When running in shared-cache mode, a database operation may fail with
-** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
-** individual tables within the shared-cache cannot be obtained. See
-** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
-** ^This API may be used to register a callback that SQLite will invoke
-** when the connection currently holding the required lock relinquishes it.
-** ^This API is only available if the library was compiled with the
-** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
-**
-** See Also: [Using the SQLite Unlock Notification Feature].
-**
-** ^Shared-cache locks are released when a database connection concludes
-** its current transaction, either by committing it or rolling it back.
-**
-** ^When a connection (known as the blocked connection) fails to obtain a
-** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
-** identity of the database connection (the blocking connection) that
-** has locked the required resource is stored internally. ^After an
-** application receives an SQLITE_LOCKED error, it may call the
-** sqlite3_unlock_notify() method with the blocked connection handle as
-** the first argument to register for a callback that will be invoked
-** when the blocking connections current transaction is concluded. ^The
-** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
-** call that concludes the blocking connections transaction.
-**
-** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
-** there is a chance that the blocking connection will have already
-** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
-** If this happens, then the specified callback is invoked immediately,
-** from within the call to sqlite3_unlock_notify().)^
-**
-** ^If the blocked connection is attempting to obtain a write-lock on a
-** shared-cache table, and more than one other connection currently holds
-** a read-lock on the same table, then SQLite arbitrarily selects one of
-** the other connections to use as the blocking connection.
-**
-** ^(There may be at most one unlock-notify callback registered by a
-** blocked connection. If sqlite3_unlock_notify() is called when the
-** blocked connection already has a registered unlock-notify callback,
-** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
-** called with a NULL pointer as its second argument, then any existing
-** unlock-notify callback is cancelled. ^The blocked connections
-** unlock-notify callback may also be canceled by closing the blocked
-** connection using [sqlite3_close()].
-**
-** The unlock-notify callback is not reentrant. If an application invokes
-** any sqlite3_xxx API functions from within an unlock-notify callback, a
-** crash or deadlock may be the result.
-**
-** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
-** returns SQLITE_OK.
-**
-** Callback Invocation Details
-**
-** When an unlock-notify callback is registered, the application provides a
-** single void* pointer that is passed to the callback when it is invoked.
-** However, the signature of the callback function allows SQLite to pass
-** it an array of void* context pointers. The first argument passed to
-** an unlock-notify callback is a pointer to an array of void* pointers,
-** and the second is the number of entries in the array.
-**
-** When a blocking connections transaction is concluded, there may be
-** more than one blocked connection that has registered for an unlock-notify
-** callback. ^If two or more such blocked connections have specified the
-** same callback function, then instead of invoking the callback function
-** multiple times, it is invoked once with the set of void* context pointers
-** specified by the blocked connections bundled together into an array.
-** This gives the application an opportunity to prioritize any actions
-** related to the set of unblocked database connections.
-**
-** Deadlock Detection
-**
-** Assuming that after registering for an unlock-notify callback a
-** database waits for the callback to be issued before taking any further
-** action (a reasonable assumption), then using this API may cause the
-** application to deadlock. For example, if connection X is waiting for
-** connection Y's transaction to be concluded, and similarly connection
-** Y is waiting on connection X's transaction, then neither connection
-** will proceed and the system may remain deadlocked indefinitely.
-**
-** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
-** detection. ^If a given call to sqlite3_unlock_notify() would put the
-** system in a deadlocked state, then SQLITE_LOCKED is returned and no
-** unlock-notify callback is registered. The system is said to be in
-** a deadlocked state if connection A has registered for an unlock-notify
-** callback on the conclusion of connection B's transaction, and connection
-** B has itself registered for an unlock-notify callback when connection
-** A's transaction is concluded. ^Indirect deadlock is also detected, so
-** the system is also considered to be deadlocked if connection B has
-** registered for an unlock-notify callback on the conclusion of connection
-** C's transaction, where connection C is waiting on connection A. ^Any
-** number of levels of indirection are allowed.
-**
-** The "DROP TABLE" Exception
-**
-** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
-** always appropriate to call sqlite3_unlock_notify(). There is however,
-** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
-** SQLite checks if there are any currently executing SELECT statements
-** that belong to the same connection. If there are, SQLITE_LOCKED is
-** returned. In this case there is no "blocking connection", so invoking
-** sqlite3_unlock_notify() results in the unlock-notify callback being
-** invoked immediately. If the application then re-attempts the "DROP TABLE"
-** or "DROP INDEX" query, an infinite loop might be the result.
-**
-** One way around this problem is to check the extended error code returned
-** by an sqlite3_step() call. ^(If there is a blocking connection, then the
-** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
-** the special "DROP TABLE/INDEX" case, the extended error code is just
-** SQLITE_LOCKED.)^
-*/
-SQLITE_API int sqlite3_unlock_notify(
- sqlite3 *pBlocked, /* Waiting connection */
- void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
- void *pNotifyArg /* Argument to pass to xNotify */
-);
-
-
-/*
-** CAPI3REF: String Comparison
-** EXPERIMENTAL
-**
-** ^The [sqlite3_strnicmp()] API allows applications and extensions to
-** compare the contents of two buffers containing UTF-8 strings in a
-** case-indendent fashion, using the same definition of case independence
-** that SQLite uses internally when comparing identifiers.
-*/
-SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
-
-/*
-** Undo the hack that converts floating point types to integer for
-** builds on processors without floating point support.
-*/
-#ifdef SQLITE_OMIT_FLOATING_POINT
-# undef double
-#endif
-
-#if 0
-} /* End of the 'extern "C"' block */
-#endif
-#endif
-
-
-/************** End of sqlite3.h *********************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-/************** Include hash.h in the middle of sqliteInt.h ******************/
-/************** Begin file hash.h ********************************************/
-/*
-** 2001 September 22
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This is the header file for the generic hash-table implemenation
-** used in SQLite.
-*/
-#ifndef _SQLITE_HASH_H_
-#define _SQLITE_HASH_H_
-
-/* Forward declarations of structures. */
-typedef struct Hash Hash;
-typedef struct HashElem HashElem;
-
-/* A complete hash table is an instance of the following structure.
-** The internals of this structure are intended to be opaque -- client
-** code should not attempt to access or modify the fields of this structure
-** directly. Change this structure only by using the routines below.
-** However, some of the "procedures" and "functions" for modifying and
-** accessing this structure are really macros, so we can't really make
-** this structure opaque.
-**
-** All elements of the hash table are on a single doubly-linked list.
-** Hash.first points to the head of this list.
-**
-** There are Hash.htsize buckets. Each bucket points to a spot in
-** the global doubly-linked list. The contents of the bucket are the
-** element pointed to plus the next _ht.count-1 elements in the list.
-**
-** Hash.htsize and Hash.ht may be zero. In that case lookup is done
-** by a linear search of the global list. For small tables, the
-** Hash.ht table is never allocated because if there are few elements
-** in the table, it is faster to do a linear search than to manage
-** the hash table.
-*/
-struct Hash {
- unsigned int htsize; /* Number of buckets in the hash table */
- unsigned int count; /* Number of entries in this table */
- HashElem *first; /* The first element of the array */
- struct _ht { /* the hash table */
- int count; /* Number of entries with this hash */
- HashElem *chain; /* Pointer to first entry with this hash */
- } *ht;
-};
-
-/* Each element in the hash table is an instance of the following
-** structure. All elements are stored on a single doubly-linked list.
-**
-** Again, this structure is intended to be opaque, but it can't really
-** be opaque because it is used by macros.
-*/
-struct HashElem {
- HashElem *next, *prev; /* Next and previous elements in the table */
- void *data; /* Data associated with this element */
- const char *pKey; int nKey; /* Key associated with this element */
-};
-
-/*
-** Access routines. To delete, insert a NULL pointer.
-*/
-SQLITE_PRIVATE void sqlite3HashInit(Hash*);
-SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
-SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
-SQLITE_PRIVATE void sqlite3HashClear(Hash*);
-
-/*
-** Macros for looping over all elements of a hash table. The idiom is
-** like this:
-**
-** Hash h;
-** HashElem *p;
-** ...
-** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
-** SomeStructure *pData = sqliteHashData(p);
-** // do something with pData
-** }
-*/
-#define sqliteHashFirst(H) ((H)->first)
-#define sqliteHashNext(E) ((E)->next)
-#define sqliteHashData(E) ((E)->data)
-/* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
-/* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
-
-/*
-** Number of entries in a hash table
-*/
-/* #define sqliteHashCount(H) ((H)->count) // NOT USED */
-
-#endif /* _SQLITE_HASH_H_ */
-
-/************** End of hash.h ************************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-/************** Include parse.h in the middle of sqliteInt.h *****************/
-/************** Begin file parse.h *******************************************/
-#define TK_SEMI 1
-#define TK_EXPLAIN 2
-#define TK_QUERY 3
-#define TK_PLAN 4
-#define TK_BEGIN 5
-#define TK_TRANSACTION 6
-#define TK_DEFERRED 7
-#define TK_IMMEDIATE 8
-#define TK_EXCLUSIVE 9
-#define TK_COMMIT 10
-#define TK_END 11
-#define TK_ROLLBACK 12
-#define TK_SAVEPOINT 13
-#define TK_RELEASE 14
-#define TK_TO 15
-#define TK_TABLE 16
-#define TK_CREATE 17
-#define TK_IF 18
-#define TK_NOT 19
-#define TK_EXISTS 20
-#define TK_TEMP 21
-#define TK_LP 22
-#define TK_RP 23
-#define TK_AS 24
-#define TK_COMMA 25
-#define TK_ID 26
-#define TK_INDEXED 27
-#define TK_ABORT 28
-#define TK_ACTION 29
-#define TK_AFTER 30
-#define TK_ANALYZE 31
-#define TK_ASC 32
-#define TK_ATTACH 33
-#define TK_BEFORE 34
-#define TK_BY 35
-#define TK_CASCADE 36
-#define TK_CAST 37
-#define TK_COLUMNKW 38
-#define TK_CONFLICT 39
-#define TK_DATABASE 40
-#define TK_DESC 41
-#define TK_DETACH 42
-#define TK_EACH 43
-#define TK_FAIL 44
-#define TK_FOR 45
-#define TK_IGNORE 46
-#define TK_INITIALLY 47
-#define TK_INSTEAD 48
-#define TK_LIKE_KW 49
-#define TK_MATCH 50
-#define TK_NO 51
-#define TK_KEY 52
-#define TK_OF 53
-#define TK_OFFSET 54
-#define TK_PRAGMA 55
-#define TK_RAISE 56
-#define TK_REPLACE 57
-#define TK_RESTRICT 58
-#define TK_ROW 59
-#define TK_TRIGGER 60
-#define TK_VACUUM 61
-#define TK_VIEW 62
-#define TK_VIRTUAL 63
-#define TK_REINDEX 64
-#define TK_RENAME 65
-#define TK_CTIME_KW 66
-#define TK_ANY 67
-#define TK_OR 68
-#define TK_AND 69
-#define TK_IS 70
-#define TK_BETWEEN 71
-#define TK_IN 72
-#define TK_ISNULL 73
-#define TK_NOTNULL 74
-#define TK_NE 75
-#define TK_EQ 76
-#define TK_GT 77
-#define TK_LE 78
-#define TK_LT 79
-#define TK_GE 80
-#define TK_ESCAPE 81
-#define TK_BITAND 82
-#define TK_BITOR 83
-#define TK_LSHIFT 84
-#define TK_RSHIFT 85
-#define TK_PLUS 86
-#define TK_MINUS 87
-#define TK_STAR 88
-#define TK_SLASH 89
-#define TK_REM 90
-#define TK_CONCAT 91
-#define TK_COLLATE 92
-#define TK_BITNOT 93
-#define TK_STRING 94
-#define TK_JOIN_KW 95
-#define TK_CONSTRAINT 96
-#define TK_DEFAULT 97
-#define TK_NULL 98
-#define TK_PRIMARY 99
-#define TK_UNIQUE 100
-#define TK_CHECK 101
-#define TK_REFERENCES 102
-#define TK_AUTOINCR 103
-#define TK_ON 104
-#define TK_INSERT 105
-#define TK_DELETE 106
-#define TK_UPDATE 107
-#define TK_SET 108
-#define TK_DEFERRABLE 109
-#define TK_FOREIGN 110
-#define TK_DROP 111
-#define TK_UNION 112
-#define TK_ALL 113
-#define TK_EXCEPT 114
-#define TK_INTERSECT 115
-#define TK_SELECT 116
-#define TK_DISTINCT 117
-#define TK_DOT 118
-#define TK_FROM 119
-#define TK_JOIN 120
-#define TK_USING 121
-#define TK_ORDER 122
-#define TK_GROUP 123
-#define TK_HAVING 124
-#define TK_LIMIT 125
-#define TK_WHERE 126
-#define TK_INTO 127
-#define TK_VALUES 128
-#define TK_INTEGER 129
-#define TK_FLOAT 130
-#define TK_BLOB 131
-#define TK_REGISTER 132
-#define TK_VARIABLE 133
-#define TK_CASE 134
-#define TK_WHEN 135
-#define TK_THEN 136
-#define TK_ELSE 137
-#define TK_INDEX 138
-#define TK_ALTER 139
-#define TK_ADD 140
-#define TK_TO_TEXT 141
-#define TK_TO_BLOB 142
-#define TK_TO_NUMERIC 143
-#define TK_TO_INT 144
-#define TK_TO_REAL 145
-#define TK_ISNOT 146
-#define TK_END_OF_FILE 147
-#define TK_ILLEGAL 148
-#define TK_SPACE 149
-#define TK_UNCLOSED_STRING 150
-#define TK_FUNCTION 151
-#define TK_COLUMN 152
-#define TK_AGG_FUNCTION 153
-#define TK_AGG_COLUMN 154
-#define TK_CONST_FUNC 155
-#define TK_UMINUS 156
-#define TK_UPLUS 157
-
-/************** End of parse.h ***********************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-#include
-#include
-#include
-#include
-#include
-
-/*
-** If compiling for a processor that lacks floating point support,
-** substitute integer for floating-point
-*/
-#ifdef SQLITE_OMIT_FLOATING_POINT
-# define double sqlite_int64
-# define LONGDOUBLE_TYPE sqlite_int64
-# ifndef SQLITE_BIG_DBL
-# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
-# endif
-# define SQLITE_OMIT_DATETIME_FUNCS 1
-# define SQLITE_OMIT_TRACE 1
-# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
-# undef SQLITE_HAVE_ISNAN
-#endif
-#ifndef SQLITE_BIG_DBL
-# define SQLITE_BIG_DBL (1e99)
-#endif
-
-/*
-** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
-** afterward. Having this macro allows us to cause the C compiler
-** to omit code used by TEMP tables without messy #ifndef statements.
-*/
-#ifdef SQLITE_OMIT_TEMPDB
-#define OMIT_TEMPDB 1
-#else
-#define OMIT_TEMPDB 0
-#endif
-
-/*
-** If the following macro is set to 1, then NULL values are considered
-** distinct when determining whether or not two entries are the same
-** in a UNIQUE index. This is the way PostgreSQL, Oracle, DB2, MySQL,
-** OCELOT, and Firebird all work. The SQL92 spec explicitly says this
-** is the way things are suppose to work.
-**
-** If the following macro is set to 0, the NULLs are indistinct for
-** a UNIQUE index. In this mode, you can only have a single NULL entry
-** for a column declared UNIQUE. This is the way Informix and SQL Server
-** work.
-*/
-#define NULL_DISTINCT_FOR_UNIQUE 1
-
-/*
-** The "file format" number is an integer that is incremented whenever
-** the VDBE-level file format changes. The following macros define the
-** the default file format for new databases and the maximum file format
-** that the library can read.
-*/
-#define SQLITE_MAX_FILE_FORMAT 4
-#ifndef SQLITE_DEFAULT_FILE_FORMAT
-# define SQLITE_DEFAULT_FILE_FORMAT 1
-#endif
-
-#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
-# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
-#endif
-
-/*
-** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
-** on the command-line
-*/
-#ifndef SQLITE_TEMP_STORE
-# define SQLITE_TEMP_STORE 1
-#endif
-
-/*
-** GCC does not define the offsetof() macro so we'll have to do it
-** ourselves.
-*/
-#ifndef offsetof
-#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
-#endif
-
-/*
-** Check to see if this machine uses EBCDIC. (Yes, believe it or
-** not, there are still machines out there that use EBCDIC.)
-*/
-#if 'A' == '\301'
-# define SQLITE_EBCDIC 1
-#else
-# define SQLITE_ASCII 1
-#endif
-
-/*
-** Integers of known sizes. These typedefs might change for architectures
-** where the sizes very. Preprocessor macros are available so that the
-** types can be conveniently redefined at compile-type. Like this:
-**
-** cc '-DUINTPTR_TYPE=long long int' ...
-*/
-#ifndef UINT32_TYPE
-# ifdef HAVE_UINT32_T
-# define UINT32_TYPE uint32_t
-# else
-# define UINT32_TYPE unsigned int
-# endif
-#endif
-#ifndef UINT16_TYPE
-# ifdef HAVE_UINT16_T
-# define UINT16_TYPE uint16_t
-# else
-# define UINT16_TYPE unsigned short int
-# endif
-#endif
-#ifndef INT16_TYPE
-# ifdef HAVE_INT16_T
-# define INT16_TYPE int16_t
-# else
-# define INT16_TYPE short int
-# endif
-#endif
-#ifndef UINT8_TYPE
-# ifdef HAVE_UINT8_T
-# define UINT8_TYPE uint8_t
-# else
-# define UINT8_TYPE unsigned char
-# endif
-#endif
-#ifndef INT8_TYPE
-# ifdef HAVE_INT8_T
-# define INT8_TYPE int8_t
-# else
-# define INT8_TYPE signed char
-# endif
-#endif
-#ifndef LONGDOUBLE_TYPE
-# define LONGDOUBLE_TYPE long double
-#endif
-typedef sqlite_int64 i64; /* 8-byte signed integer */
-typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
-typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
-typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
-typedef INT16_TYPE i16; /* 2-byte signed integer */
-typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
-typedef INT8_TYPE i8; /* 1-byte signed integer */
-
-/*
-** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
-** that can be stored in a u32 without loss of data. The value
-** is 0x00000000ffffffff. But because of quirks of some compilers, we
-** have to specify the value in the less intuitive manner shown:
-*/
-#define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
-
-/*
-** Macros to determine whether the machine is big or little endian,
-** evaluated at runtime.
-*/
-#ifdef SQLITE_AMALGAMATION
-SQLITE_PRIVATE const int sqlite3one = 1;
-#else
-SQLITE_PRIVATE const int sqlite3one;
-#endif
-#if defined(i386) || defined(__i386__) || defined(_M_IX86)\
- || defined(__x86_64) || defined(__x86_64__)
-# define SQLITE_BIGENDIAN 0
-# define SQLITE_LITTLEENDIAN 1
-# define SQLITE_UTF16NATIVE SQLITE_UTF16LE
-#else
-# define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
-# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
-# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
-#endif
-
-/*
-** Constants for the largest and smallest possible 64-bit signed integers.
-** These macros are designed to work correctly on both 32-bit and 64-bit
-** compilers.
-*/
-#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
-#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
-
-/*
-** Round up a number to the next larger multiple of 8. This is used
-** to force 8-byte alignment on 64-bit architectures.
-*/
-#define ROUND8(x) (((x)+7)&~7)
-
-/*
-** Round down to the nearest multiple of 8
-*/
-#define ROUNDDOWN8(x) ((x)&~7)
-
-/*
-** Assert that the pointer X is aligned to an 8-byte boundary. This
-** macro is used only within assert() to verify that the code gets
-** all alignment restrictions correct.
-**
-** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
-** underlying malloc() implemention might return us 4-byte aligned
-** pointers. In that case, only verify 4-byte alignment.
-*/
-#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
-# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
-#else
-# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
-#endif
-
-
-/*
-** An instance of the following structure is used to store the busy-handler
-** callback for a given sqlite handle.
-**
-** The sqlite.busyHandler member of the sqlite struct contains the busy
-** callback for the database handle. Each pager opened via the sqlite
-** handle is passed a pointer to sqlite.busyHandler. The busy-handler
-** callback is currently invoked only from within pager.c.
-*/
-typedef struct BusyHandler BusyHandler;
-struct BusyHandler {
- int (*xFunc)(void *,int); /* The busy callback */
- void *pArg; /* First arg to busy callback */
- int nBusy; /* Incremented with each busy call */
-};
-
-/*
-** Name of the master database table. The master database table
-** is a special table that holds the names and attributes of all
-** user tables and indices.
-*/
-#define MASTER_NAME "sqlite_master"
-#define TEMP_MASTER_NAME "sqlite_temp_master"
-
-/*
-** The root-page of the master database table.
-*/
-#define MASTER_ROOT 1
-
-/*
-** The name of the schema table.
-*/
-#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
-
-/*
-** A convenience macro that returns the number of elements in
-** an array.
-*/
-#define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
-
-/*
-** The following value as a destructor means to use sqlite3DbFree().
-** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
-*/
-#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3DbFree)
-
-/*
-** When SQLITE_OMIT_WSD is defined, it means that the target platform does
-** not support Writable Static Data (WSD) such as global and static variables.
-** All variables must either be on the stack or dynamically allocated from
-** the heap. When WSD is unsupported, the variable declarations scattered
-** throughout the SQLite code must become constants instead. The SQLITE_WSD
-** macro is used for this purpose. And instead of referencing the variable
-** directly, we use its constant as a key to lookup the run-time allocated
-** buffer that holds real variable. The constant is also the initializer
-** for the run-time allocated buffer.
-**
-** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
-** macros become no-ops and have zero performance impact.
-*/
-#ifdef SQLITE_OMIT_WSD
- #define SQLITE_WSD const
- #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
- #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
-SQLITE_API int sqlite3_wsd_init(int N, int J);
-SQLITE_API void *sqlite3_wsd_find(void *K, int L);
-#else
- #define SQLITE_WSD
- #define GLOBAL(t,v) v
- #define sqlite3GlobalConfig sqlite3Config
-#endif
-
-/*
-** The following macros are used to suppress compiler warnings and to
-** make it clear to human readers when a function parameter is deliberately
-** left unused within the body of a function. This usually happens when
-** a function is called via a function pointer. For example the
-** implementation of an SQL aggregate step callback may not use the
-** parameter indicating the number of arguments passed to the aggregate,
-** if it knows that this is enforced elsewhere.
-**
-** When a function parameter is not used at all within the body of a function,
-** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
-** However, these macros may also be used to suppress warnings related to
-** parameters that may or may not be used depending on compilation options.
-** For example those parameters only used in assert() statements. In these
-** cases the parameters are named as per the usual conventions.
-*/
-#define UNUSED_PARAMETER(x) (void)(x)
-#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
-
-/*
-** Forward references to structures
-*/
-typedef struct AggInfo AggInfo;
-typedef struct AuthContext AuthContext;
-typedef struct AutoincInfo AutoincInfo;
-typedef struct Bitvec Bitvec;
-typedef struct RowSet RowSet;
-typedef struct CollSeq CollSeq;
-typedef struct Column Column;
-typedef struct Db Db;
-typedef struct Schema Schema;
-typedef struct Expr Expr;
-typedef struct ExprList ExprList;
-typedef struct ExprSpan ExprSpan;
-typedef struct FKey FKey;
-typedef struct FuncDef FuncDef;
-typedef struct FuncDefHash FuncDefHash;
-typedef struct IdList IdList;
-typedef struct Index Index;
-typedef struct IndexSample IndexSample;
-typedef struct KeyClass KeyClass;
-typedef struct KeyInfo KeyInfo;
-typedef struct Lookaside Lookaside;
-typedef struct LookasideSlot LookasideSlot;
-typedef struct Module Module;
-typedef struct NameContext NameContext;
-typedef struct Parse Parse;
-typedef struct Savepoint Savepoint;
-typedef struct Select Select;
-typedef struct SrcList SrcList;
-typedef struct StrAccum StrAccum;
-typedef struct Table Table;
-typedef struct TableLock TableLock;
-typedef struct Token Token;
-typedef struct TriggerPrg TriggerPrg;
-typedef struct TriggerStep TriggerStep;
-typedef struct Trigger Trigger;
-typedef struct UnpackedRecord UnpackedRecord;
-typedef struct VTable VTable;
-typedef struct Walker Walker;
-typedef struct WherePlan WherePlan;
-typedef struct WhereInfo WhereInfo;
-typedef struct WhereLevel WhereLevel;
-
-/*
-** Defer sourcing vdbe.h and btree.h until after the "u8" and
-** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
-** pointer types (i.e. FuncDef) defined above.
-*/
-/************** Include btree.h in the middle of sqliteInt.h *****************/
-/************** Begin file btree.h *******************************************/
-/*
-** 2001 September 15
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This header file defines the interface that the sqlite B-Tree file
-** subsystem. See comments in the source code for a detailed description
-** of what each interface routine does.
-*/
-#ifndef _BTREE_H_
-#define _BTREE_H_
-
-/* TODO: This definition is just included so other modules compile. It
-** needs to be revisited.
-*/
-#define SQLITE_N_BTREE_META 10
-
-/*
-** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
-** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
-*/
-#ifndef SQLITE_DEFAULT_AUTOVACUUM
- #define SQLITE_DEFAULT_AUTOVACUUM 0
-#endif
-
-#define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
-#define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
-#define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
-
-/*
-** Forward declarations of structure
-*/
-typedef struct Btree Btree;
-typedef struct BtCursor BtCursor;
-typedef struct BtShared BtShared;
-typedef struct BtreeMutexArray BtreeMutexArray;
-
-/*
-** This structure records all of the Btrees that need to hold
-** a mutex before we enter sqlite3VdbeExec(). The Btrees are
-** are placed in aBtree[] in order of aBtree[]->pBt. That way,
-** we can always lock and unlock them all quickly.
-*/
-struct BtreeMutexArray {
- int nMutex;
- Btree *aBtree[SQLITE_MAX_ATTACHED+1];
-};
-
-
-SQLITE_PRIVATE int sqlite3BtreeOpen(
- const char *zFilename, /* Name of database file to open */
- sqlite3 *db, /* Associated database connection */
- Btree **ppBtree, /* Return open Btree* here */
- int flags, /* Flags */
- int vfsFlags /* Flags passed through to VFS open */
-);
-
-/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
-** following values.
-**
-** NOTE: These values must match the corresponding PAGER_ values in
-** pager.h.
-*/
-#define BTREE_OMIT_JOURNAL 1 /* Do not use journal. No argument */
-#define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
-#define BTREE_MEMORY 4 /* In-memory DB. No argument */
-#define BTREE_READONLY 8 /* Open the database in read-only mode */
-#define BTREE_READWRITE 16 /* Open for both reading and writing */
-#define BTREE_CREATE 32 /* Create the database if it does not exist */
-
-SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
-SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
-SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
-SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
-SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
-SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
-SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
-SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
-SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
-SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
-SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
-SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
-SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
-SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
-SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
-
-SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
-SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
-SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
-
-SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
-
-/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
-** of the following flags:
-*/
-#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
-#define BTREE_ZERODATA 2 /* Table has keys only - no data */
-#define BTREE_LEAFDATA 4 /* Data stored in leaves only. Implies INTKEY */
-
-SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
-SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
-SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
-
-SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
-SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
-
-/*
-** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
-** should be one of the following values. The integer values are assigned
-** to constants so that the offset of the corresponding field in an
-** SQLite database header may be found using the following formula:
-**
-** offset = 36 + (idx * 4)
-**
-** For example, the free-page-count field is located at byte offset 36 of
-** the database file header. The incr-vacuum-flag field is located at
-** byte offset 64 (== 36+4*7).
-*/
-#define BTREE_FREE_PAGE_COUNT 0
-#define BTREE_SCHEMA_VERSION 1
-#define BTREE_FILE_FORMAT 2
-#define BTREE_DEFAULT_CACHE_SIZE 3
-#define BTREE_LARGEST_ROOT_PAGE 4
-#define BTREE_TEXT_ENCODING 5
-#define BTREE_USER_VERSION 6
-#define BTREE_INCR_VACUUM 7
-
-SQLITE_PRIVATE int sqlite3BtreeCursor(
- Btree*, /* BTree containing table to open */
- int iTable, /* Index of root page */
- int wrFlag, /* 1 for writing. 0 for read-only */
- struct KeyInfo*, /* First argument to compare function */
- BtCursor *pCursor /* Space to write cursor structure */
-);
-SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
-SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
-
-SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
-SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
- BtCursor*,
- UnpackedRecord *pUnKey,
- i64 intKey,
- int bias,
- int *pRes
-);
-SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
-SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
-SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
- const void *pData, int nData,
- int nZero, int bias, int seekResult);
-SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
-SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
-SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
-SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
-SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
-SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
-SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
-SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
-SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
-SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
-SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
-SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
-SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
-
-SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
-SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
-
-SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
-SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
-SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
-
-#ifndef NDEBUG
-SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
-#endif
-
-#ifndef SQLITE_OMIT_BTREECOUNT
-SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
-#endif
-
-#ifdef SQLITE_TEST
-SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
-SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
-#endif
-
-/*
-** If we are not using shared cache, then there is no need to
-** use mutexes to access the BtShared structures. So make the
-** Enter and Leave procedures no-ops.
-*/
-#ifndef SQLITE_OMIT_SHARED_CACHE
-SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
-SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
-#else
-# define sqlite3BtreeEnter(X)
-# define sqlite3BtreeEnterAll(X)
-#endif
-
-#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
-SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
-SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
-SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
-SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
-SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
-SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
-SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
-#ifndef NDEBUG
- /* These routines are used inside assert() statements only. */
-SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
-#endif
-#else
-
-# define sqlite3BtreeLeave(X)
-# define sqlite3BtreeEnterCursor(X)
-# define sqlite3BtreeLeaveCursor(X)
-# define sqlite3BtreeLeaveAll(X)
-# define sqlite3BtreeMutexArrayEnter(X)
-# define sqlite3BtreeMutexArrayLeave(X)
-# define sqlite3BtreeMutexArrayInsert(X,Y)
-
-# define sqlite3BtreeHoldsMutex(X) 1
-# define sqlite3BtreeHoldsAllMutexes(X) 1
-#endif
-
-
-#endif /* _BTREE_H_ */
-
-/************** End of btree.h ***********************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-/************** Include vdbe.h in the middle of sqliteInt.h ******************/
-/************** Begin file vdbe.h ********************************************/
-/*
-** 2001 September 15
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** Header file for the Virtual DataBase Engine (VDBE)
-**
-** This header defines the interface to the virtual database engine
-** or VDBE. The VDBE implements an abstract machine that runs a
-** simple program to access and modify the underlying database.
-*/
-#ifndef _SQLITE_VDBE_H_
-#define _SQLITE_VDBE_H_
-
-/*
-** A single VDBE is an opaque structure named "Vdbe". Only routines
-** in the source file sqliteVdbe.c are allowed to see the insides
-** of this structure.
-*/
-typedef struct Vdbe Vdbe;
-
-/*
-** The names of the following types declared in vdbeInt.h are required
-** for the VdbeOp definition.
-*/
-typedef struct VdbeFunc VdbeFunc;
-typedef struct Mem Mem;
-typedef struct SubProgram SubProgram;
-
-/*
-** A single instruction of the virtual machine has an opcode
-** and as many as three operands. The instruction is recorded
-** as an instance of the following structure:
-*/
-struct VdbeOp {
- u8 opcode; /* What operation to perform */
- signed char p4type; /* One of the P4_xxx constants for p4 */
- u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
- u8 p5; /* Fifth parameter is an unsigned character */
- int p1; /* First operand */
- int p2; /* Second parameter (often the jump destination) */
- int p3; /* The third parameter */
- union { /* fourth parameter */
- int i; /* Integer value if p4type==P4_INT32 */
- void *p; /* Generic pointer */
- char *z; /* Pointer to data for string (char array) types */
- i64 *pI64; /* Used when p4type is P4_INT64 */
- double *pReal; /* Used when p4type is P4_REAL */
- FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
- VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */
- CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
- Mem *pMem; /* Used when p4type is P4_MEM */
- VTable *pVtab; /* Used when p4type is P4_VTAB */
- KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
- int *ai; /* Used when p4type is P4_INTARRAY */
- SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
- } p4;
-#ifdef SQLITE_DEBUG
- char *zComment; /* Comment to improve readability */
-#endif
-#ifdef VDBE_PROFILE
- int cnt; /* Number of times this instruction was executed */
- u64 cycles; /* Total time spent executing this instruction */
-#endif
-};
-typedef struct VdbeOp VdbeOp;
-
-
-/*
-** A sub-routine used to implement a trigger program.
-*/
-struct SubProgram {
- VdbeOp *aOp; /* Array of opcodes for sub-program */
- int nOp; /* Elements in aOp[] */
- int nMem; /* Number of memory cells required */
- int nCsr; /* Number of cursors required */
- int nRef; /* Number of pointers to this structure */
- void *token; /* id that may be used to recursive triggers */
-};
-
-/*
-** A smaller version of VdbeOp used for the VdbeAddOpList() function because
-** it takes up less space.
-*/
-struct VdbeOpList {
- u8 opcode; /* What operation to perform */
- signed char p1; /* First operand */
- signed char p2; /* Second parameter (often the jump destination) */
- signed char p3; /* Third parameter */
-};
-typedef struct VdbeOpList VdbeOpList;
-
-/*
-** Allowed values of VdbeOp.p4type
-*/
-#define P4_NOTUSED 0 /* The P4 parameter is not used */
-#define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
-#define P4_STATIC (-2) /* Pointer to a static string */
-#define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
-#define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
-#define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
-#define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */
-#define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
-#define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
-#define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
-#define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
-#define P4_REAL (-12) /* P4 is a 64-bit floating point value */
-#define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
-#define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
-#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
-#define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
-
-/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
-** is made. That copy is freed when the Vdbe is finalized. But if the
-** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
-** gets freed when the Vdbe is finalized so it still should be obtained
-** from a single sqliteMalloc(). But no copy is made and the calling
-** function should *not* try to free the KeyInfo.
-*/
-#define P4_KEYINFO_HANDOFF (-16)
-#define P4_KEYINFO_STATIC (-17)
-
-/*
-** The Vdbe.aColName array contains 5n Mem structures, where n is the
-** number of columns of data returned by the statement.
-*/
-#define COLNAME_NAME 0
-#define COLNAME_DECLTYPE 1
-#define COLNAME_DATABASE 2
-#define COLNAME_TABLE 3
-#define COLNAME_COLUMN 4
-#ifdef SQLITE_ENABLE_COLUMN_METADATA
-# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
-#else
-# ifdef SQLITE_OMIT_DECLTYPE
-# define COLNAME_N 1 /* Store only the name */
-# else
-# define COLNAME_N 2 /* Store the name and decltype */
-# endif
-#endif
-
-/*
-** The following macro converts a relative address in the p2 field
-** of a VdbeOp structure into a negative number so that
-** sqlite3VdbeAddOpList() knows that the address is relative. Calling
-** the macro again restores the address.
-*/
-#define ADDR(X) (-1-(X))
-
-/*
-** The makefile scans the vdbe.c source file and creates the "opcodes.h"
-** header file that defines a number for each opcode used by the VDBE.
-*/
-/************** Include opcodes.h in the middle of vdbe.h ********************/
-/************** Begin file opcodes.h *****************************************/
-/* Automatically generated. Do not edit */
-/* See the mkopcodeh.awk script for details */
-#define OP_Goto 1
-#define OP_Gosub 2
-#define OP_Return 3
-#define OP_Yield 4
-#define OP_HaltIfNull 5
-#define OP_Halt 6
-#define OP_Integer 7
-#define OP_Int64 8
-#define OP_Real 130 /* same as TK_FLOAT */
-#define OP_String8 94 /* same as TK_STRING */
-#define OP_String 9
-#define OP_Null 10
-#define OP_Blob 11
-#define OP_Variable 12
-#define OP_Move 13
-#define OP_Copy 14
-#define OP_SCopy 15
-#define OP_ResultRow 16
-#define OP_Concat 91 /* same as TK_CONCAT */
-#define OP_Add 86 /* same as TK_PLUS */
-#define OP_Subtract 87 /* same as TK_MINUS */
-#define OP_Multiply 88 /* same as TK_STAR */
-#define OP_Divide 89 /* same as TK_SLASH */
-#define OP_Remainder 90 /* same as TK_REM */
-#define OP_CollSeq 17
-#define OP_Function 18
-#define OP_BitAnd 82 /* same as TK_BITAND */
-#define OP_BitOr 83 /* same as TK_BITOR */
-#define OP_ShiftLeft 84 /* same as TK_LSHIFT */
-#define OP_ShiftRight 85 /* same as TK_RSHIFT */
-#define OP_AddImm 20
-#define OP_MustBeInt 21
-#define OP_RealAffinity 22
-#define OP_ToText 141 /* same as TK_TO_TEXT */
-#define OP_ToBlob 142 /* same as TK_TO_BLOB */
-#define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
-#define OP_ToInt 144 /* same as TK_TO_INT */
-#define OP_ToReal 145 /* same as TK_TO_REAL */
-#define OP_Eq 76 /* same as TK_EQ */
-#define OP_Ne 75 /* same as TK_NE */
-#define OP_Lt 79 /* same as TK_LT */
-#define OP_Le 78 /* same as TK_LE */
-#define OP_Gt 77 /* same as TK_GT */
-#define OP_Ge 80 /* same as TK_GE */
-#define OP_Permutation 23
-#define OP_Compare 24
-#define OP_Jump 25
-#define OP_And 69 /* same as TK_AND */
-#define OP_Or 68 /* same as TK_OR */
-#define OP_Not 19 /* same as TK_NOT */
-#define OP_BitNot 93 /* same as TK_BITNOT */
-#define OP_If 26
-#define OP_IfNot 27
-#define OP_IsNull 73 /* same as TK_ISNULL */
-#define OP_NotNull 74 /* same as TK_NOTNULL */
-#define OP_Column 28
-#define OP_Affinity 29
-#define OP_MakeRecord 30
-#define OP_Count 31
-#define OP_Savepoint 32
-#define OP_AutoCommit 33
-#define OP_Transaction 34
-#define OP_ReadCookie 35
-#define OP_SetCookie 36
-#define OP_VerifyCookie 37
-#define OP_OpenRead 38
-#define OP_OpenWrite 39
-#define OP_OpenEphemeral 40
-#define OP_OpenPseudo 41
-#define OP_Close 42
-#define OP_SeekLt 43
-#define OP_SeekLe 44
-#define OP_SeekGe 45
-#define OP_SeekGt 46
-#define OP_Seek 47
-#define OP_NotFound 48
-#define OP_Found 49
-#define OP_IsUnique 50
-#define OP_NotExists 51
-#define OP_Sequence 52
-#define OP_NewRowid 53
-#define OP_Insert 54
-#define OP_InsertInt 55
-#define OP_Delete 56
-#define OP_ResetCount 57
-#define OP_RowKey 58
-#define OP_RowData 59
-#define OP_Rowid 60
-#define OP_NullRow 61
-#define OP_Last 62
-#define OP_Sort 63
-#define OP_Rewind 64
-#define OP_Prev 65
-#define OP_Next 66
-#define OP_IdxInsert 67
-#define OP_IdxDelete 70
-#define OP_IdxRowid 71
-#define OP_IdxLT 72
-#define OP_IdxGE 81
-#define OP_Destroy 92
-#define OP_Clear 95
-#define OP_CreateIndex 96
-#define OP_CreateTable 97
-#define OP_ParseSchema 98
-#define OP_LoadAnalysis 99
-#define OP_DropTable 100
-#define OP_DropIndex 101
-#define OP_DropTrigger 102
-#define OP_IntegrityCk 103
-#define OP_RowSetAdd 104
-#define OP_RowSetRead 105
-#define OP_RowSetTest 106
-#define OP_Program 107
-#define OP_Param 108
-#define OP_FkCounter 109
-#define OP_FkIfZero 110
-#define OP_MemMax 111
-#define OP_IfPos 112
-#define OP_IfNeg 113
-#define OP_IfZero 114
-#define OP_AggStep 115
-#define OP_AggFinal 116
-#define OP_Vacuum 117
-#define OP_IncrVacuum 118
-#define OP_Expire 119
-#define OP_TableLock 120
-#define OP_VBegin 121
-#define OP_VCreate 122
-#define OP_VDestroy 123
-#define OP_VOpen 124
-#define OP_VFilter 125
-#define OP_VColumn 126
-#define OP_VNext 127
-#define OP_VRename 128
-#define OP_VUpdate 129
-#define OP_Pagecount 131
-#define OP_Trace 132
-#define OP_Noop 133
-#define OP_Explain 134
-
-/* The following opcode values are never used */
-#define OP_NotUsed_135 135
-#define OP_NotUsed_136 136
-#define OP_NotUsed_137 137
-#define OP_NotUsed_138 138
-#define OP_NotUsed_139 139
-#define OP_NotUsed_140 140
-
-
-/* Properties such as "out2" or "jump" that are specified in
-** comments following the "case" for each opcode in the vdbe.c
-** are encoded into bitvectors as follows:
-*/
-#define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
-#define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
-#define OPFLG_IN1 0x0004 /* in1: P1 is an input */
-#define OPFLG_IN2 0x0008 /* in2: P2 is an input */
-#define OPFLG_IN3 0x0010 /* in3: P3 is an input */
-#define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
-#define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
-#define OPFLG_INITIALIZER {\
-/* 0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
-/* 8 */ 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x24,\
-/* 16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
-/* 24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
-/* 32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
-/* 40 */ 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x08,\
-/* 48 */ 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, 0x00,\
-/* 56 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x01,\
-/* 64 */ 0x01, 0x01, 0x01, 0x08, 0x4c, 0x4c, 0x00, 0x02,\
-/* 72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
-/* 80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
-/* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x02, 0x24, 0x02, 0x00,\
-/* 96 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
-/* 104 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
-/* 112 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00,\
-/* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,\
-/* 128 */ 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\
-/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
-/* 144 */ 0x04, 0x04,}
-
-/************** End of opcodes.h *********************************************/
-/************** Continuing where we left off in vdbe.h ***********************/
-
-/*
-** Prototypes for the VDBE interface. See comments on the implementation
-** for a description of what each of these routines does.
-*/
-SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
-SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
-SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
-SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
-SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
-SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
-SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
-SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
-SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
-SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
-SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
-SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
-SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
-SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
-SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
-SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
-SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
-SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
-SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
-SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
-SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
-#endif
-SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
-SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
-SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
-SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
-SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
-SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
-SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
-SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
-SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
-SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
-#ifndef SQLITE_OMIT_TRACE
-SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
-#endif
-
-SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
-SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
-SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
-
-
-#ifndef NDEBUG
-SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
-# define VdbeComment(X) sqlite3VdbeComment X
-SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
-# define VdbeNoopComment(X) sqlite3VdbeNoopComment X
-#else
-# define VdbeComment(X)
-# define VdbeNoopComment(X)
-#endif
-
-#endif
-
-/************** End of vdbe.h ************************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-/************** Include pager.h in the middle of sqliteInt.h *****************/
-/************** Begin file pager.h *******************************************/
-/*
-** 2001 September 15
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This header file defines the interface that the sqlite page cache
-** subsystem. The page cache subsystem reads and writes a file a page
-** at a time and provides a journal for rollback.
-*/
-
-#ifndef _PAGER_H_
-#define _PAGER_H_
-
-/*
-** Default maximum size for persistent journal files. A negative
-** value means no limit. This value may be overridden using the
-** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
-*/
-#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
- #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
-#endif
-
-/*
-** The type used to represent a page number. The first page in a file
-** is called page 1. 0 is used to represent "not a page".
-*/
-typedef u32 Pgno;
-
-/*
-** Each open file is managed by a separate instance of the "Pager" structure.
-*/
-typedef struct Pager Pager;
-
-/*
-** Handle type for pages.
-*/
-typedef struct PgHdr DbPage;
-
-/*
-** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
-** reserved for working around a windows/posix incompatibility). It is
-** used in the journal to signify that the remainder of the journal file
-** is devoted to storing a master journal name - there are no more pages to
-** roll back. See comments for function writeMasterJournal() in pager.c
-** for details.
-*/
-#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
-
-/*
-** Allowed values for the flags parameter to sqlite3PagerOpen().
-**
-** NOTE: These values must match the corresponding BTREE_ values in btree.h.
-*/
-#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
-#define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */
-
-/*
-** Valid values for the second argument to sqlite3PagerLockingMode().
-*/
-#define PAGER_LOCKINGMODE_QUERY -1
-#define PAGER_LOCKINGMODE_NORMAL 0
-#define PAGER_LOCKINGMODE_EXCLUSIVE 1
-
-/*
-** Valid values for the second argument to sqlite3PagerJournalMode().
-*/
-#define PAGER_JOURNALMODE_QUERY -1
-#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
-#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
-#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
-#define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
-#define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
-
-/*
-** The remainder of this file contains the declarations of the functions
-** that make up the Pager sub-system API. See source code comments for
-** a detailed description of each routine.
-*/
-
-/* Open and close a Pager connection. */
-SQLITE_PRIVATE int sqlite3PagerOpen(
- sqlite3_vfs*,
- Pager **ppPager,
- const char*,
- int,
- int,
- int,
- void(*)(DbPage*)
-);
-SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
-SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
-
-/* Functions used to configure a Pager object. */
-SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
-SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int);
-SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
-SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
-SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
-SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
-SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
-SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
-SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
-
-/* Functions used to obtain and release page references. */
-SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
-#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
-SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
-SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
-SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
-
-/* Operations on page references. */
-SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
-SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
-SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
-SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
-SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
-SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
-
-/* Functions used to manage pager transactions and savepoints. */
-SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
-SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
-SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
-SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
-SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
-SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
-SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
-SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
-SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
-
-/* Functions used to query pager state and configuration. */
-SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
-SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
-SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
-SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
-SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
-SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
-SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
-SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
-SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
-
-/* Functions used to truncate the database file. */
-SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
-
-/* Functions to support testing and debugging. */
-#if !defined(NDEBUG) || defined(SQLITE_TEST)
-SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
-SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
-#endif
-#ifdef SQLITE_TEST
-SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
-SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
- void disable_simulated_io_errors(void);
- void enable_simulated_io_errors(void);
-#else
-# define disable_simulated_io_errors()
-# define enable_simulated_io_errors()
-#endif
-
-#endif /* _PAGER_H_ */
-
-/************** End of pager.h ***********************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-/************** Include pcache.h in the middle of sqliteInt.h ****************/
-/************** Begin file pcache.h ******************************************/
-/*
-** 2008 August 05
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This header file defines the interface that the sqlite page cache
-** subsystem.
-*/
-
-#ifndef _PCACHE_H_
-
-typedef struct PgHdr PgHdr;
-typedef struct PCache PCache;
-
-/*
-** Every page in the cache is controlled by an instance of the following
-** structure.
-*/
-struct PgHdr {
- void *pData; /* Content of this page */
- void *pExtra; /* Extra content */
- PgHdr *pDirty; /* Transient list of dirty pages */
- Pgno pgno; /* Page number for this page */
- Pager *pPager; /* The pager this page is part of */
-#ifdef SQLITE_CHECK_PAGES
- u32 pageHash; /* Hash of page content */
-#endif
- u16 flags; /* PGHDR flags defined below */
-
- /**********************************************************************
- ** Elements above are public. All that follows is private to pcache.c
- ** and should not be accessed by other modules.
- */
- i16 nRef; /* Number of users of this page */
- PCache *pCache; /* Cache that owns this page */
-
- PgHdr *pDirtyNext; /* Next element in list of dirty pages */
- PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
-};
-
-/* Bit values for PgHdr.flags */
-#define PGHDR_DIRTY 0x002 /* Page has changed */
-#define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
- ** writing this page to the database */
-#define PGHDR_NEED_READ 0x008 /* Content is unread */
-#define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
-#define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
-
-/* Initialize and shutdown the page cache subsystem */
-SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
-SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
-
-/* Page cache buffer management:
-** These routines implement SQLITE_CONFIG_PAGECACHE.
-*/
-SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
-
-/* Create a new pager cache.
-** Under memory stress, invoke xStress to try to make pages clean.
-** Only clean and unpinned pages can be reclaimed.
-*/
-SQLITE_PRIVATE void sqlite3PcacheOpen(
- int szPage, /* Size of every page */
- int szExtra, /* Extra space associated with each page */
- int bPurgeable, /* True if pages are on backing store */
- int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
- void *pStress, /* Argument to xStress */
- PCache *pToInit /* Preallocated space for the PCache */
-);
-
-/* Modify the page-size after the cache has been created. */
-SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
-
-/* Return the size in bytes of a PCache object. Used to preallocate
-** storage space.
-*/
-SQLITE_PRIVATE int sqlite3PcacheSize(void);
-
-/* One release per successful fetch. Page is pinned until released.
-** Reference counted.
-*/
-SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
-SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
-
-SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
-SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
-SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
-SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
-
-/* Change a page number. Used by incr-vacuum. */
-SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
-
-/* Remove all pages with pgno>x. Reset the cache if x==0 */
-SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
-
-/* Get a list of all dirty pages in the cache, sorted by page number */
-SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
-
-/* Reset and close the cache object */
-SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
-
-/* Clear flags from pages of the page cache */
-SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
-
-/* Discard the contents of the cache */
-SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
-
-/* Return the total number of outstanding page references */
-SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
-
-/* Increment the reference count of an existing page */
-SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
-
-SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
-
-/* Return the total number of pages stored in the cache */
-SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
-
-#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
-/* Iterate through all dirty pages currently stored in the cache. This
-** interface is only available if SQLITE_CHECK_PAGES is defined when the
-** library is built.
-*/
-SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
-#endif
-
-/* Set and get the suggested cache-size for the specified pager-cache.
-**
-** If no global maximum is configured, then the system attempts to limit
-** the total number of pages cached by purgeable pager-caches to the sum
-** of the suggested cache-sizes.
-*/
-SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
-#ifdef SQLITE_TEST
-SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
-#endif
-
-#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
-/* Try to return memory used by the pcache module to the main memory heap */
-SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
-#endif
-
-#ifdef SQLITE_TEST
-SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
-#endif
-
-SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
-
-#endif /* _PCACHE_H_ */
-
-/************** End of pcache.h **********************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-
-/************** Include os.h in the middle of sqliteInt.h ********************/
-/************** Begin file os.h **********************************************/
-/*
-** 2001 September 16
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-******************************************************************************
-**
-** This header file (together with is companion C source-code file
-** "os.c") attempt to abstract the underlying operating system so that
-** the SQLite library will work on both POSIX and windows systems.
-**
-** This header file is #include-ed by sqliteInt.h and thus ends up
-** being included by every source file.
-*/
-#ifndef _SQLITE_OS_H_
-#define _SQLITE_OS_H_
-
-/*
-** Figure out if we are dealing with Unix, Windows, or some other
-** operating system. After the following block of preprocess macros,
-** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
-** will defined to either 1 or 0. One of the four will be 1. The other
-** three will be 0.
-*/
-#if defined(SQLITE_OS_OTHER)
-# if SQLITE_OS_OTHER==1
-# undef SQLITE_OS_UNIX
-# define SQLITE_OS_UNIX 0
-# undef SQLITE_OS_WIN
-# define SQLITE_OS_WIN 0
-# undef SQLITE_OS_OS2
-# define SQLITE_OS_OS2 0
-# else
-# undef SQLITE_OS_OTHER
-# endif
-#endif
-#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
-# define SQLITE_OS_OTHER 0
-# ifndef SQLITE_OS_WIN
-# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
-# define SQLITE_OS_WIN 1
-# define SQLITE_OS_UNIX 0
-# define SQLITE_OS_OS2 0
-# elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
-# define SQLITE_OS_WIN 0
-# define SQLITE_OS_UNIX 0
-# define SQLITE_OS_OS2 1
-# else
-# define SQLITE_OS_WIN 0
-# define SQLITE_OS_UNIX 1
-# define SQLITE_OS_OS2 0
-# endif
-# else
-# define SQLITE_OS_UNIX 0
-# define SQLITE_OS_OS2 0
-# endif
-#else
-# ifndef SQLITE_OS_WIN
-# define SQLITE_OS_WIN 0
-# endif
-#endif
-
-/*
-** Determine if we are dealing with WindowsCE - which has a much
-** reduced API.
-*/
-#if defined(_WIN32_WCE)
-# define SQLITE_OS_WINCE 1
-#else
-# define SQLITE_OS_WINCE 0
-#endif
-
-
-/*
-** Define the maximum size of a temporary filename
-*/
-#if SQLITE_OS_WIN
-# include
-# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
-#elif SQLITE_OS_OS2
-# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
-# include /* has to be included before os2.h for linking to work */
-# endif
-# define INCL_DOSDATETIME
-# define INCL_DOSFILEMGR
-# define INCL_DOSERRORS
-# define INCL_DOSMISC
-# define INCL_DOSPROCESS
-# define INCL_DOSMODULEMGR
-# define INCL_DOSSEMAPHORES
-# include
-# include
-# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
-#else
-# define SQLITE_TEMPNAME_SIZE 200
-#endif
-
-/* If the SET_FULLSYNC macro is not defined above, then make it
-** a no-op
-*/
-#ifndef SET_FULLSYNC
-# define SET_FULLSYNC(x,y)
-#endif
-
-/*
-** The default size of a disk sector
-*/
-#ifndef SQLITE_DEFAULT_SECTOR_SIZE
-# define SQLITE_DEFAULT_SECTOR_SIZE 512
-#endif
-
-/*
-** Temporary files are named starting with this prefix followed by 16 random
-** alphanumeric characters, and no file extension. They are stored in the
-** OS's standard temporary file directory, and are deleted prior to exit.
-** If sqlite is being embedded in another program, you may wish to change the
-** prefix to reflect your program's name, so that if your program exits
-** prematurely, old temporary files can be easily identified. This can be done
-** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
-**
-** 2006-10-31: The default prefix used to be "sqlite_". But then
-** Mcafee started using SQLite in their anti-virus product and it
-** started putting files with the "sqlite" name in the c:/temp folder.
-** This annoyed many windows users. Those users would then do a
-** Google search for "sqlite", find the telephone numbers of the
-** developers and call to wake them up at night and complain.
-** For this reason, the default name prefix is changed to be "sqlite"
-** spelled backwards. So the temp files are still identified, but
-** anybody smart enough to figure out the code is also likely smart
-** enough to know that calling the developer will not help get rid
-** of the file.
-*/
-#ifndef SQLITE_TEMP_FILE_PREFIX
-# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
-#endif
-
-/*
-** The following values may be passed as the second argument to
-** sqlite3OsLock(). The various locks exhibit the following semantics:
-**
-** SHARED: Any number of processes may hold a SHARED lock simultaneously.
-** RESERVED: A single process may hold a RESERVED lock on a file at
-** any time. Other processes may hold and obtain new SHARED locks.
-** PENDING: A single process may hold a PENDING lock on a file at
-** any one time. Existing SHARED locks may persist, but no new
-** SHARED locks may be obtained by other processes.
-** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
-**
-** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
-** process that requests an EXCLUSIVE lock may actually obtain a PENDING
-** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
-** sqlite3OsLock().
-*/
-#define NO_LOCK 0
-#define SHARED_LOCK 1
-#define RESERVED_LOCK 2
-#define PENDING_LOCK 3
-#define EXCLUSIVE_LOCK 4
-
-/*
-** File Locking Notes: (Mostly about windows but also some info for Unix)
-**
-** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
-** those functions are not available. So we use only LockFile() and
-** UnlockFile().
-**
-** LockFile() prevents not just writing but also reading by other processes.
-** A SHARED_LOCK is obtained by locking a single randomly-chosen
-** byte out of a specific range of bytes. The lock byte is obtained at
-** random so two separate readers can probably access the file at the
-** same time, unless they are unlucky and choose the same lock byte.
-** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
-** There can only be one writer. A RESERVED_LOCK is obtained by locking
-** a single byte of the file that is designated as the reserved lock byte.
-** A PENDING_LOCK is obtained by locking a designated byte different from
-** the RESERVED_LOCK byte.
-**
-** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
-** which means we can use reader/writer locks. When reader/writer locks
-** are used, the lock is placed on the same range of bytes that is used
-** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
-** will support two or more Win95 readers or two or more WinNT readers.
-** But a single Win95 reader will lock out all WinNT readers and a single
-** WinNT reader will lock out all other Win95 readers.
-**
-** The following #defines specify the range of bytes used for locking.
-** SHARED_SIZE is the number of bytes available in the pool from which
-** a random byte is selected for a shared lock. The pool of bytes for
-** shared locks begins at SHARED_FIRST.
-**
-** The same locking strategy and
-** byte ranges are used for Unix. This leaves open the possiblity of having
-** clients on win95, winNT, and unix all talking to the same shared file
-** and all locking correctly. To do so would require that samba (or whatever
-** tool is being used for file sharing) implements locks correctly between
-** windows and unix. I'm guessing that isn't likely to happen, but by
-** using the same locking range we are at least open to the possibility.
-**
-** Locking in windows is manditory. For this reason, we cannot store
-** actual data in the bytes used for locking. The pager never allocates
-** the pages involved in locking therefore. SHARED_SIZE is selected so
-** that all locks will fit on a single page even at the minimum page size.
-** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
-** is set high so that we don't have to allocate an unused page except
-** for very large databases. But one should test the page skipping logic
-** by setting PENDING_BYTE low and running the entire regression suite.
-**
-** Changing the value of PENDING_BYTE results in a subtly incompatible
-** file format. Depending on how it is changed, you might not notice
-** the incompatibility right away, even running a full regression test.
-** The default location of PENDING_BYTE is the first byte past the
-** 1GB boundary.
-**
-*/
-#define PENDING_BYTE sqlite3PendingByte
-#define RESERVED_BYTE (PENDING_BYTE+1)
-#define SHARED_FIRST (PENDING_BYTE+2)
-#define SHARED_SIZE 510
-
-/*
-** Wrapper around OS specific sqlite3_os_init() function.
-*/
-SQLITE_PRIVATE int sqlite3OsInit(void);
-
-/*
-** Functions for accessing sqlite3_file methods
-*/
-SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
-SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
-SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
-SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
-SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
-SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
-SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
-SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
-SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
-SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
-#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
-SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
-SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
-
-/*
-** Functions for accessing sqlite3_vfs methods
-*/
-SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
-SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
-SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
-SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
-#ifndef SQLITE_OMIT_LOAD_EXTENSION
-SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
-SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
-SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
-SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
-#endif /* SQLITE_OMIT_LOAD_EXTENSION */
-SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
-SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
-SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
-
-/*
-** Convenience functions for opening and closing files using
-** sqlite3_malloc() to obtain space for the file-handle structure.
-*/
-SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
-SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
-
-#endif /* _SQLITE_OS_H_ */
-
-/************** End of os.h **************************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-/************** Include mutex.h in the middle of sqliteInt.h *****************/
-/************** Begin file mutex.h *******************************************/
-/*
-** 2007 August 28
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-**
-** This file contains the common header for all mutex implementations.
-** The sqliteInt.h header #includes this file so that it is available
-** to all source files. We break it out in an effort to keep the code
-** better organized.
-**
-** NOTE: source files should *not* #include this header file directly.
-** Source files should #include the sqliteInt.h file and let that file
-** include this one indirectly.
-*/
-
-
-/*
-** Figure out what version of the code to use. The choices are
-**
-** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
-** mutexes implemention cannot be overridden
-** at start-time.
-**
-** SQLITE_MUTEX_NOOP For single-threaded applications. No
-** mutual exclusion is provided. But this
-** implementation can be overridden at
-** start-time.
-**
-** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
-**
-** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
-**
-** SQLITE_MUTEX_OS2 For multi-threaded applications on OS/2.
-*/
-#if !SQLITE_THREADSAFE
-# define SQLITE_MUTEX_OMIT
-#endif
-#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
-# if SQLITE_OS_UNIX
-# define SQLITE_MUTEX_PTHREADS
-# elif SQLITE_OS_WIN
-# define SQLITE_MUTEX_W32
-# elif SQLITE_OS_OS2
-# define SQLITE_MUTEX_OS2
-# else
-# define SQLITE_MUTEX_NOOP
-# endif
-#endif
-
-#ifdef SQLITE_MUTEX_OMIT
-/*
-** If this is a no-op implementation, implement everything as macros.
-*/
-#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
-#define sqlite3_mutex_free(X)
-#define sqlite3_mutex_enter(X)
-#define sqlite3_mutex_try(X) SQLITE_OK
-#define sqlite3_mutex_leave(X)
-#define sqlite3_mutex_held(X) 1
-#define sqlite3_mutex_notheld(X) 1
-#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
-#define sqlite3MutexInit() SQLITE_OK
-#define sqlite3MutexEnd()
-#endif /* defined(SQLITE_MUTEX_OMIT) */
-
-/************** End of mutex.h ***********************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-
-
-/*
-** Each database file to be accessed by the system is an instance
-** of the following structure. There are normally two of these structures
-** in the sqlite.aDb[] array. aDb[0] is the main database file and
-** aDb[1] is the database file used to hold temporary tables. Additional
-** databases may be attached.
-*/
-struct Db {
- char *zName; /* Name of this database */
- Btree *pBt; /* The B*Tree structure for this database file */
- u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
- u8 safety_level; /* How aggressive at syncing data to disk */
- Schema *pSchema; /* Pointer to database schema (possibly shared) */
-};
-
-/*
-** An instance of the following structure stores a database schema.
-**
-** If there are no virtual tables configured in this schema, the
-** Schema.db variable is set to NULL. After the first virtual table
-** has been added, it is set to point to the database connection
-** used to create the connection. Once a virtual table has been
-** added to the Schema structure and the Schema.db variable populated,
-** only that database connection may use the Schema to prepare
-** statements.
-*/
-struct Schema {
- int schema_cookie; /* Database schema version number for this file */
- Hash tblHash; /* All tables indexed by name */
- Hash idxHash; /* All (named) indices indexed by name */
- Hash trigHash; /* All triggers indexed by name */
- Hash fkeyHash; /* All foreign keys by referenced table name */
- Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
- u8 file_format; /* Schema format version for this file */
- u8 enc; /* Text encoding used by this database */
- u16 flags; /* Flags associated with this schema */
- int cache_size; /* Number of pages to use in the cache */
-#ifndef SQLITE_OMIT_VIRTUALTABLE
- sqlite3 *db; /* "Owner" connection. See comment above */
-#endif
-};
-
-/*
-** These macros can be used to test, set, or clear bits in the
-** Db.flags field.
-*/
-#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
-#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
-#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
-#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
-
-/*
-** Allowed values for the DB.flags field.
-**
-** The DB_SchemaLoaded flag is set after the database schema has been
-** read into internal hash tables.
-**
-** DB_UnresetViews means that one or more views have column names that
-** have been filled out. If the schema changes, these column names might
-** changes and so the view will need to be reset.
-*/
-#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
-#define DB_UnresetViews 0x0002 /* Some views have defined column names */
-#define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
-
-/*
-** The number of different kinds of things that can be limited
-** using the sqlite3_limit() interface.
-*/
-#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
-
-/*
-** Lookaside malloc is a set of fixed-size buffers that can be used
-** to satisfy small transient memory allocation requests for objects
-** associated with a particular database connection. The use of
-** lookaside malloc provides a significant performance enhancement
-** (approx 10%) by avoiding numerous malloc/free requests while parsing
-** SQL statements.
-**
-** The Lookaside structure holds configuration information about the
-** lookaside malloc subsystem. Each available memory allocation in
-** the lookaside subsystem is stored on a linked list of LookasideSlot
-** objects.
-**
-** Lookaside allocations are only allowed for objects that are associated
-** with a particular database connection. Hence, schema information cannot
-** be stored in lookaside because in shared cache mode the schema information
-** is shared by multiple database connections. Therefore, while parsing
-** schema information, the Lookaside.bEnabled flag is cleared so that
-** lookaside allocations are not used to construct the schema objects.
-*/
-struct Lookaside {
- u16 sz; /* Size of each buffer in bytes */
- u8 bEnabled; /* False to disable new lookaside allocations */
- u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
- int nOut; /* Number of buffers currently checked out */
- int mxOut; /* Highwater mark for nOut */
- LookasideSlot *pFree; /* List of available buffers */
- void *pStart; /* First byte of available memory space */
- void *pEnd; /* First byte past end of available space */
-};
-struct LookasideSlot {
- LookasideSlot *pNext; /* Next buffer in the list of free buffers */
-};
-
-/*
-** A hash table for function definitions.
-**
-** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
-** Collisions are on the FuncDef.pHash chain.
-*/
-struct FuncDefHash {
- FuncDef *a[23]; /* Hash table for functions */
-};
-
-/*
-** Each database is an instance of the following structure.
-**
-** The sqlite.lastRowid records the last insert rowid generated by an
-** insert statement. Inserts on views do not affect its value. Each
-** trigger has its own context, so that lastRowid can be updated inside
-** triggers as usual. The previous value will be restored once the trigger
-** exits. Upon entering a before or instead of trigger, lastRowid is no
-** longer (since after version 2.8.12) reset to -1.
-**
-** The sqlite.nChange does not count changes within triggers and keeps no
-** context. It is reset at start of sqlite3_exec.
-** The sqlite.lsChange represents the number of changes made by the last
-** insert, update, or delete statement. It remains constant throughout the
-** length of a statement and is then updated by OP_SetCounts. It keeps a
-** context stack just like lastRowid so that the count of changes
-** within a trigger is not seen outside the trigger. Changes to views do not
-** affect the value of lsChange.
-** The sqlite.csChange keeps track of the number of current changes (since
-** the last statement) and is used to update sqlite_lsChange.
-**
-** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
-** store the most recent error code and, if applicable, string. The
-** internal function sqlite3Error() is used to set these variables
-** consistently.
-*/
-struct sqlite3 {
- sqlite3_vfs *pVfs; /* OS Interface */
- int nDb; /* Number of backends currently in use */
- Db *aDb; /* All backends */
- int flags; /* Miscellaneous flags. See below */
- int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
- int errCode; /* Most recent error code (SQLITE_*) */
- int errMask; /* & result codes with this before returning */
- u8 autoCommit; /* The auto-commit flag. */
- u8 temp_store; /* 1: file 2: memory 0: default */
- u8 mallocFailed; /* True if we have seen a malloc failure */
- u8 dfltLockMode; /* Default locking-mode for attached dbs */
- u8 dfltJournalMode; /* Default journal mode for attached dbs */
- signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
- int nextPagesize; /* Pagesize after VACUUM if >0 */
- int nTable; /* Number of tables in the database */
- CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
- i64 lastRowid; /* ROWID of most recent insert (see above) */
- u32 magic; /* Magic number for detect library misuse */
- int nChange; /* Value returned by sqlite3_changes() */
- int nTotalChange; /* Value returned by sqlite3_total_changes() */
- sqlite3_mutex *mutex; /* Connection mutex */
- int aLimit[SQLITE_N_LIMIT]; /* Limits */
- struct sqlite3InitInfo { /* Information used during initialization */
- int iDb; /* When back is being initialized */
- int newTnum; /* Rootpage of table being initialized */
- u8 busy; /* TRUE if currently initializing */
- u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
- } init;
- int nExtension; /* Number of loaded extensions */
- void **aExtension; /* Array of shared library handles */
- struct Vdbe *pVdbe; /* List of active virtual machines */
- int activeVdbeCnt; /* Number of VDBEs currently executing */
- int writeVdbeCnt; /* Number of active VDBEs that are writing */
- void (*xTrace)(void*,const char*); /* Trace function */
- void *pTraceArg; /* Argument to the trace function */
- void (*xProfile)(void*,const char*,u64); /* Profiling function */
- void *pProfileArg; /* Argument to profile function */
- void *pCommitArg; /* Argument to xCommitCallback() */
- int (*xCommitCallback)(void*); /* Invoked at every commit. */
- void *pRollbackArg; /* Argument to xRollbackCallback() */
- void (*xRollbackCallback)(void*); /* Invoked at every commit. */
- void *pUpdateArg;
- void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
- void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
- void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
- void *pCollNeededArg;
- sqlite3_value *pErr; /* Most recent error message */
- char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
- char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
- union {
- volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
- double notUsed1; /* Spacer */
- } u1;
- Lookaside lookaside; /* Lookaside malloc configuration */
-#ifndef SQLITE_OMIT_AUTHORIZATION
- int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
- /* Access authorization function */
- void *pAuthArg; /* 1st argument to the access auth function */
-#endif
-#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
- int (*xProgress)(void *); /* The progress callback */
- void *pProgressArg; /* Argument to the progress callback */
- int nProgressOps; /* Number of opcodes for progress callback */
-#endif
-#ifndef SQLITE_OMIT_VIRTUALTABLE
- Hash aModule; /* populated by sqlite3_create_module() */
- Table *pVTab; /* vtab with active Connect/Create method */
- VTable **aVTrans; /* Virtual tables with open transactions */
- int nVTrans; /* Allocated size of aVTrans */
- VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
-#endif
- FuncDefHash aFunc; /* Hash table of connection functions */
- Hash aCollSeq; /* All collating sequences */
- BusyHandler busyHandler; /* Busy callback */
- int busyTimeout; /* Busy handler timeout, in msec */
- Db aDbStatic[2]; /* Static space for the 2 default backends */
- Savepoint *pSavepoint; /* List of active savepoints */
- int nSavepoint; /* Number of non-transaction savepoints */
- int nStatement; /* Number of nested statement-transactions */
- u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
- i64 nDeferredCons; /* Net deferred constraints this transaction. */
-
-#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
- /* The following variables are all protected by the STATIC_MASTER
- ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
- **
- ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
- ** unlock so that it can proceed.
- **
- ** When X.pBlockingConnection==Y, that means that something that X tried
- ** tried to do recently failed with an SQLITE_LOCKED error due to locks
- ** held by Y.
- */
- sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
- sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
- void *pUnlockArg; /* Argument to xUnlockNotify */
- void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
- sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
-#endif
-};
-
-/*
-** A macro to discover the encoding of a database.
-*/
-#define ENC(db) ((db)->aDb[0].pSchema->enc)
-
-/*
-** Possible values for the sqlite3.flags.
-*/
-#define SQLITE_VdbeTrace 0x00000100 /* True to trace VDBE execution */
-#define SQLITE_InternChanges 0x00000200 /* Uncommitted Hash table changes */
-#define SQLITE_FullColNames 0x00000400 /* Show full column names on SELECT */
-#define SQLITE_ShortColNames 0x00000800 /* Show short columns names */
-#define SQLITE_CountRows 0x00001000 /* Count rows changed by INSERT, */
- /* DELETE, or UPDATE and return */
- /* the count using a callback. */
-#define SQLITE_NullCallback 0x00002000 /* Invoke the callback once if the */
- /* result set is empty */
-#define SQLITE_SqlTrace 0x00004000 /* Debug print SQL as it executes */
-#define SQLITE_VdbeListing 0x00008000 /* Debug listings of VDBE programs */
-#define SQLITE_WriteSchema 0x00010000 /* OK to update SQLITE_MASTER */
-#define SQLITE_NoReadlock 0x00020000 /* Readlocks are omitted when
- ** accessing read-only databases */
-#define SQLITE_IgnoreChecks 0x00040000 /* Do not enforce check constraints */
-#define SQLITE_ReadUncommitted 0x0080000 /* For shared-cache mode */
-#define SQLITE_LegacyFileFmt 0x00100000 /* Create new databases in format 1 */
-#define SQLITE_FullFSync 0x00200000 /* Use full fsync on the backend */
-#define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
-#define SQLITE_RecoveryMode 0x00800000 /* Ignore schema errors */
-#define SQLITE_ReverseOrder 0x01000000 /* Reverse unordered SELECTs */
-#define SQLITE_RecTriggers 0x02000000 /* Enable recursive triggers */
-#define SQLITE_ForeignKeys 0x04000000 /* Enforce foreign key constraints */
-
-/*
-** Bits of the sqlite3.flags field that are used by the
-** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
-** These must be the low-order bits of the flags field.
-*/
-#define SQLITE_QueryFlattener 0x01 /* Disable query flattening */
-#define SQLITE_ColumnCache 0x02 /* Disable the column cache */
-#define SQLITE_IndexSort 0x04 /* Disable indexes for sorting */
-#define SQLITE_IndexSearch 0x08 /* Disable indexes for searching */
-#define SQLITE_IndexCover 0x10 /* Disable index covering table */
-#define SQLITE_OptMask 0x1f /* Mask of all disablable opts */
-
-/*
-** Possible values for the sqlite.magic field.
-** The numbers are obtained at random and have no special meaning, other
-** than being distinct from one another.
-*/
-#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
-#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
-#define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
-#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
-#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
-
-/*
-** Each SQL function is defined by an instance of the following
-** structure. A pointer to this structure is stored in the sqlite.aFunc
-** hash table. When multiple functions have the same name, the hash table
-** points to a linked list of these structures.
-*/
-struct FuncDef {
- i16 nArg; /* Number of arguments. -1 means unlimited */
- u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
- u8 flags; /* Some combination of SQLITE_FUNC_* */
- void *pUserData; /* User data parameter */
- FuncDef *pNext; /* Next function with same name */
- void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
- void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
- void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
- char *zName; /* SQL name of the function. */
- FuncDef *pHash; /* Next with a different name but the same hash */
-};
-
-/*
-** Possible values for FuncDef.flags
-*/
-#define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
-#define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
-#define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */
-#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
-#define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */
-#define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */
-#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
-
-/*
-** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
-** used to create the initializers for the FuncDef structures.
-**
-** FUNCTION(zName, nArg, iArg, bNC, xFunc)
-** Used to create a scalar function definition of a function zName
-** implemented by C function xFunc that accepts nArg arguments. The
-** value passed as iArg is cast to a (void*) and made available
-** as the user-data (sqlite3_user_data()) for the function. If
-** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
-**
-** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
-** Used to create an aggregate function definition implemented by
-** the C functions xStep and xFinal. The first four parameters
-** are interpreted in the same way as the first 4 parameters to
-** FUNCTION().
-**
-** LIKEFUNC(zName, nArg, pArg, flags)
-** Used to create a scalar function definition of a function zName
-** that accepts nArg arguments and is implemented by a call to C
-** function likeFunc. Argument pArg is cast to a (void *) and made
-** available as the function user-data (sqlite3_user_data()). The
-** FuncDef.flags variable is set to the value passed as the flags
-** parameter.
-*/
-#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
- {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
- SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
-#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
- {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
- pArg, 0, xFunc, 0, 0, #zName, 0}
-#define LIKEFUNC(zName, nArg, arg, flags) \
- {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
-#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
- {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
- SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
-
-/*
-** All current savepoints are stored in a linked list starting at
-** sqlite3.pSavepoint. The first element in the list is the most recently
-** opened savepoint. Savepoints are added to the list by the vdbe
-** OP_Savepoint instruction.
-*/
-struct Savepoint {
- char *zName; /* Savepoint name (nul-terminated) */
- i64 nDeferredCons; /* Number of deferred fk violations */
- Savepoint *pNext; /* Parent savepoint (if any) */
-};
-
-/*
-** The following are used as the second parameter to sqlite3Savepoint(),
-** and as the P1 argument to the OP_Savepoint instruction.
-*/
-#define SAVEPOINT_BEGIN 0
-#define SAVEPOINT_RELEASE 1
-#define SAVEPOINT_ROLLBACK 2
-
-
-/*
-** Each SQLite module (virtual table definition) is defined by an
-** instance of the following structure, stored in the sqlite3.aModule
-** hash table.
-*/
-struct Module {
- const sqlite3_module *pModule; /* Callback pointers */
- const char *zName; /* Name passed to create_module() */
- void *pAux; /* pAux passed to create_module() */
- void (*xDestroy)(void *); /* Module destructor function */
-};
-
-/*
-** information about each column of an SQL table is held in an instance
-** of this structure.
-*/
-struct Column {
- char *zName; /* Name of this column */
- Expr *pDflt; /* Default value of this column */
- char *zDflt; /* Original text of the default value */
- char *zType; /* Data type for this column */
- char *zColl; /* Collating sequence. If NULL, use the default */
- u8 notNull; /* True if there is a NOT NULL constraint */
- u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
- char affinity; /* One of the SQLITE_AFF_... values */
-#ifndef SQLITE_OMIT_VIRTUALTABLE
- u8 isHidden; /* True if this column is 'hidden' */
-#endif
-};
-
-/*
-** A "Collating Sequence" is defined by an instance of the following
-** structure. Conceptually, a collating sequence consists of a name and
-** a comparison routine that defines the order of that sequence.
-**
-** There may two separate implementations of the collation function, one
-** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
-** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
-** native byte order. When a collation sequence is invoked, SQLite selects
-** the version that will require the least expensive encoding
-** translations, if any.
-**
-** The CollSeq.pUser member variable is an extra parameter that passed in
-** as the first argument to the UTF-8 comparison function, xCmp.
-** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
-** xCmp16.
-**
-** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
-** collating sequence is undefined. Indices built on an undefined
-** collating sequence may not be read or written.
-*/
-struct CollSeq {
- char *zName; /* Name of the collating sequence, UTF-8 encoded */
- u8 enc; /* Text encoding handled by xCmp() */
- u8 type; /* One of the SQLITE_COLL_... values below */
- void *pUser; /* First argument to xCmp() */
- int (*xCmp)(void*,int, const void*, int, const void*);
- void (*xDel)(void*); /* Destructor for pUser */
-};
-
-/*
-** Allowed values of CollSeq.type:
-*/
-#define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */
-#define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */
-#define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */
-#define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */
-
-/*
-** A sort order can be either ASC or DESC.
-*/
-#define SQLITE_SO_ASC 0 /* Sort in ascending order */
-#define SQLITE_SO_DESC 1 /* Sort in ascending order */
-
-/*
-** Column affinity types.
-**
-** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
-** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
-** the speed a little by numbering the values consecutively.
-**
-** But rather than start with 0 or 1, we begin with 'a'. That way,
-** when multiple affinity types are concatenated into a string and
-** used as the P4 operand, they will be more readable.
-**
-** Note also that the numeric types are grouped together so that testing
-** for a numeric type is a single comparison.
-*/
-#define SQLITE_AFF_TEXT 'a'
-#define SQLITE_AFF_NONE 'b'
-#define SQLITE_AFF_NUMERIC 'c'
-#define SQLITE_AFF_INTEGER 'd'
-#define SQLITE_AFF_REAL 'e'
-
-#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
-
-/*
-** The SQLITE_AFF_MASK values masks off the significant bits of an
-** affinity value.
-*/
-#define SQLITE_AFF_MASK 0x67
-
-/*
-** Additional bit values that can be ORed with an affinity without
-** changing the affinity.
-*/
-#define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
-#define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
-#define SQLITE_NULLEQ 0x80 /* NULL=NULL */
-
-/*
-** An object of this type is created for each virtual table present in
-** the database schema.
-**
-** If the database schema is shared, then there is one instance of this
-** structure for each database connection (sqlite3*) that uses the shared
-** schema. This is because each database connection requires its own unique
-** instance of the sqlite3_vtab* handle used to access the virtual table
-** implementation. sqlite3_vtab* handles can not be shared between
-** database connections, even when the rest of the in-memory database
-** schema is shared, as the implementation often stores the database
-** connection handle passed to it via the xConnect() or xCreate() method
-** during initialization internally. This database connection handle may
-** then used by the virtual table implementation to access real tables
-** within the database. So that they appear as part of the callers
-** transaction, these accesses need to be made via the same database
-** connection as that used to execute SQL operations on the virtual table.
-**
-** All VTable objects that correspond to a single table in a shared
-** database schema are initially stored in a linked-list pointed to by
-** the Table.pVTable member variable of the corresponding Table object.
-** When an sqlite3_prepare() operation is required to access the virtual
-** table, it searches the list for the VTable that corresponds to the
-** database connection doing the preparing so as to use the correct
-** sqlite3_vtab* handle in the compiled query.
-**
-** When an in-memory Table object is deleted (for example when the
-** schema is being reloaded for some reason), the VTable objects are not
-** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
-** immediately. Instead, they are moved from the Table.pVTable list to
-** another linked list headed by the sqlite3.pDisconnect member of the
-** corresponding sqlite3 structure. They are then deleted/xDisconnected
-** next time a statement is prepared using said sqlite3*. This is done
-** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
-** Refer to comments above function sqlite3VtabUnlockList() for an
-** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
-** list without holding the corresponding sqlite3.mutex mutex.
-**
-** The memory for objects of this type is always allocated by
-** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
-** the first argument.
-*/
-struct VTable {
- sqlite3 *db; /* Database connection associated with this table */
- Module *pMod; /* Pointer to module implementation */
- sqlite3_vtab *pVtab; /* Pointer to vtab instance */
- int nRef; /* Number of pointers to this structure */
- VTable *pNext; /* Next in linked list (see above) */
-};
-
-/*
-** Each SQL table is represented in memory by an instance of the
-** following structure.
-**
-** Table.zName is the name of the table. The case of the original
-** CREATE TABLE statement is stored, but case is not significant for
-** comparisons.
-**
-** Table.nCol is the number of columns in this table. Table.aCol is a
-** pointer to an array of Column structures, one for each column.
-**
-** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
-** the column that is that key. Otherwise Table.iPKey is negative. Note
-** that the datatype of the PRIMARY KEY must be INTEGER for this field to
-** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
-** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
-** is generated for each row of the table. TF_HasPrimaryKey is set if
-** the table has any PRIMARY KEY, INTEGER or otherwise.
-**
-** Table.tnum is the page number for the root BTree page of the table in the
-** database file. If Table.iDb is the index of the database table backend
-** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
-** holds temporary tables and indices. If TF_Ephemeral is set
-** then the table is stored in a file that is automatically deleted
-** when the VDBE cursor to the table is closed. In this case Table.tnum
-** refers VDBE cursor number that holds the table open, not to the root
-** page number. Transient tables are used to hold the results of a
-** sub-query that appears instead of a real table name in the FROM clause
-** of a SELECT statement.
-*/
-struct Table {
- sqlite3 *dbMem; /* DB connection used for lookaside allocations. */
- char *zName; /* Name of the table or view */
- int iPKey; /* If not negative, use aCol[iPKey] as the primary key */
- int nCol; /* Number of columns in this table */
- Column *aCol; /* Information about each column */
- Index *pIndex; /* List of SQL indexes on this table. */
- int tnum; /* Root BTree node for this table (see note above) */
- Select *pSelect; /* NULL for tables. Points to definition if a view. */
- u16 nRef; /* Number of pointers to this Table */
- u8 tabFlags; /* Mask of TF_* values */
- u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
- FKey *pFKey; /* Linked list of all foreign keys in this table */
- char *zColAff; /* String defining the affinity of each column */
-#ifndef SQLITE_OMIT_CHECK
- Expr *pCheck; /* The AND of all CHECK constraints */
-#endif
-#ifndef SQLITE_OMIT_ALTERTABLE
- int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
-#endif
-#ifndef SQLITE_OMIT_VIRTUALTABLE
- VTable *pVTable; /* List of VTable objects. */
- int nModuleArg; /* Number of arguments to the module */
- char **azModuleArg; /* Text of all module args. [0] is module name */
-#endif
- Trigger *pTrigger; /* List of triggers stored in pSchema */
- Schema *pSchema; /* Schema that contains this table */
- Table *pNextZombie; /* Next on the Parse.pZombieTab list */
-};
-
-/*
-** Allowed values for Tabe.tabFlags.
-*/
-#define TF_Readonly 0x01 /* Read-only system table */
-#define TF_Ephemeral 0x02 /* An ephemeral table */
-#define TF_HasPrimaryKey 0x04 /* Table has a primary key */
-#define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
-#define TF_Virtual 0x10 /* Is a virtual table */
-#define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */
-
-
-
-/*
-** Test to see whether or not a table is a virtual table. This is
-** done as a macro so that it will be optimized out when virtual
-** table support is omitted from the build.
-*/
-#ifndef SQLITE_OMIT_VIRTUALTABLE
-# define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
-# define IsHiddenColumn(X) ((X)->isHidden)
-#else
-# define IsVirtual(X) 0
-# define IsHiddenColumn(X) 0
-#endif
-
-/*
-** Each foreign key constraint is an instance of the following structure.
-**
-** A foreign key is associated with two tables. The "from" table is
-** the table that contains the REFERENCES clause that creates the foreign
-** key. The "to" table is the table that is named in the REFERENCES clause.
-** Consider this example:
-**
-** CREATE TABLE ex1(
-** a INTEGER PRIMARY KEY,
-** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
-** );
-**
-** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
-**
-** Each REFERENCES clause generates an instance of the following structure
-** which is attached to the from-table. The to-table need not exist when
-** the from-table is created. The existence of the to-table is not checked.
-*/
-struct FKey {
- Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
- FKey *pNextFrom; /* Next foreign key in pFrom */
- char *zTo; /* Name of table that the key points to (aka: Parent) */
- FKey *pNextTo; /* Next foreign key on table named zTo */
- FKey *pPrevTo; /* Previous foreign key on table named zTo */
- int nCol; /* Number of columns in this key */
- /* EV: R-30323-21917 */
- u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
- u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
- Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
- struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
- int iFrom; /* Index of column in pFrom */
- char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
- } aCol[1]; /* One entry for each of nCol column s */
-};
-
-/*
-** SQLite supports many different ways to resolve a constraint
-** error. ROLLBACK processing means that a constraint violation
-** causes the operation in process to fail and for the current transaction
-** to be rolled back. ABORT processing means the operation in process
-** fails and any prior changes from that one operation are backed out,
-** but the transaction is not rolled back. FAIL processing means that
-** the operation in progress stops and returns an error code. But prior
-** changes due to the same operation are not backed out and no rollback
-** occurs. IGNORE means that the particular row that caused the constraint
-** error is not inserted or updated. Processing continues and no error
-** is returned. REPLACE means that preexisting database rows that caused
-** a UNIQUE constraint violation are removed so that the new insert or
-** update can proceed. Processing continues and no error is reported.
-**
-** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
-** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
-** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
-** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
-** referenced table row is propagated into the row that holds the
-** foreign key.
-**
-** The following symbolic values are used to record which type
-** of action to take.
-*/
-#define OE_None 0 /* There is no constraint to check */
-#define OE_Rollback 1 /* Fail the operation and rollback the transaction */
-#define OE_Abort 2 /* Back out changes but do no rollback transaction */
-#define OE_Fail 3 /* Stop the operation but leave all prior changes */
-#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
-#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
-
-#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
-#define OE_SetNull 7 /* Set the foreign key value to NULL */
-#define OE_SetDflt 8 /* Set the foreign key value to its default */
-#define OE_Cascade 9 /* Cascade the changes */
-
-#define OE_Default 99 /* Do whatever the default action is */
-
-
-/*
-** An instance of the following structure is passed as the first
-** argument to sqlite3VdbeKeyCompare and is used to control the
-** comparison of the two index keys.
-*/
-struct KeyInfo {
- sqlite3 *db; /* The database connection */
- u8 enc; /* Text encoding - one of the TEXT_Utf* values */
- u16 nField; /* Number of entries in aColl[] */
- u8 *aSortOrder; /* If defined an aSortOrder[i] is true, sort DESC */
- CollSeq *aColl[1]; /* Collating sequence for each term of the key */
-};
-
-/*
-** An instance of the following structure holds information about a
-** single index record that has already been parsed out into individual
-** values.
-**
-** A record is an object that contains one or more fields of data.
-** Records are used to store the content of a table row and to store
-** the key of an index. A blob encoding of a record is created by
-** the OP_MakeRecord opcode of the VDBE and is disassembled by the
-** OP_Column opcode.
-**
-** This structure holds a record that has already been disassembled
-** into its constituent fields.
-*/
-struct UnpackedRecord {
- KeyInfo *pKeyInfo; /* Collation and sort-order information */
- u16 nField; /* Number of entries in apMem[] */
- u16 flags; /* Boolean settings. UNPACKED_... below */
- i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
- Mem *aMem; /* Values */
-};
-
-/*
-** Allowed values of UnpackedRecord.flags
-*/
-#define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */
-#define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */
-#define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */
-#define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */
-#define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */
-#define UNPACKED_PREFIX_SEARCH 0x0020 /* A prefix match is considered OK */
-
-/*
-** Each SQL index is represented in memory by an
-** instance of the following structure.
-**
-** The columns of the table that are to be indexed are described
-** by the aiColumn[] field of this structure. For example, suppose
-** we have the following table and index:
-**
-** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
-** CREATE INDEX Ex2 ON Ex1(c3,c1);
-**
-** In the Table structure describing Ex1, nCol==3 because there are
-** three columns in the table. In the Index structure describing
-** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
-** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
-** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
-** The second column to be indexed (c1) has an index of 0 in
-** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
-**
-** The Index.onError field determines whether or not the indexed columns
-** must be unique and what to do if they are not. When Index.onError=OE_None,
-** it means this is not a unique index. Otherwise it is a unique index
-** and the value of Index.onError indicate the which conflict resolution
-** algorithm to employ whenever an attempt is made to insert a non-unique
-** element.
-*/
-struct Index {
- char *zName; /* Name of this index */
- int nColumn; /* Number of columns in the table used by this index */
- int *aiColumn; /* Which columns are used by this index. 1st is 0 */
- unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
- Table *pTable; /* The SQL table being indexed */
- int tnum; /* Page containing root of this index in database file */
- u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
- u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
- char *zColAff; /* String defining the affinity of each column */
- Index *pNext; /* The next index associated with the same table */
- Schema *pSchema; /* Schema containing this index */
- u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */
- char **azColl; /* Array of collation sequence names for index */
- IndexSample *aSample; /* Array of SQLITE_INDEX_SAMPLES samples */
-};
-
-/*
-** Each sample stored in the sqlite_stat2 table is represented in memory
-** using a structure of this type.
-*/
-struct IndexSample {
- union {
- char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
- double r; /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
- } u;
- u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
- u8 nByte; /* Size in byte of text or blob. */
-};
-
-/*
-** Each token coming out of the lexer is an instance of
-** this structure. Tokens are also used as part of an expression.
-**
-** Note if Token.z==0 then Token.dyn and Token.n are undefined and
-** may contain random values. Do not make any assumptions about Token.dyn
-** and Token.n when Token.z==0.
-*/
-struct Token {
- const char *z; /* Text of the token. Not NULL-terminated! */
- unsigned int n; /* Number of characters in this token */
-};
-
-/*
-** An instance of this structure contains information needed to generate
-** code for a SELECT that contains aggregate functions.
-**
-** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
-** pointer to this structure. The Expr.iColumn field is the index in
-** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
-** code for that node.
-**
-** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
-** original Select structure that describes the SELECT statement. These
-** fields do not need to be freed when deallocating the AggInfo structure.
-*/
-struct AggInfo {
- u8 directMode; /* Direct rendering mode means take data directly
- ** from source tables rather than from accumulators */
- u8 useSortingIdx; /* In direct mode, reference the sorting index rather
- ** than the source table */
- int sortingIdx; /* Cursor number of the sorting index */
- ExprList *pGroupBy; /* The group by clause */
- int nSortingColumn; /* Number of columns in the sorting index */
- struct AggInfo_col { /* For each column used in source tables */
- Table *pTab; /* Source table */
- int iTable; /* Cursor number of the source table */
- int iColumn; /* Column number within the source table */
- int iSorterColumn; /* Column number in the sorting index */
- int iMem; /* Memory location that acts as accumulator */
- Expr *pExpr; /* The original expression */
- } *aCol;
- int nColumn; /* Number of used entries in aCol[] */
- int nColumnAlloc; /* Number of slots allocated for aCol[] */
- int nAccumulator; /* Number of columns that show through to the output.
- ** Additional columns are used only as parameters to
- ** aggregate functions */
- struct AggInfo_func { /* For each aggregate function */
- Expr *pExpr; /* Expression encoding the function */
- FuncDef *pFunc; /* The aggregate function implementation */
- int iMem; /* Memory location that acts as accumulator */
- int iDistinct; /* Ephemeral table used to enforce DISTINCT */
- } *aFunc;
- int nFunc; /* Number of entries in aFunc[] */
- int nFuncAlloc; /* Number of slots allocated for aFunc[] */
-};
-
-/*
-** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
-** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
-** than 32767 we have to make it 32-bit. 16-bit is preferred because
-** it uses less memory in the Expr object, which is a big memory user
-** in systems with lots of prepared statements. And few applications
-** need more than about 10 or 20 variables. But some extreme users want
-** to have prepared statements with over 32767 variables, and for them
-** the option is available (at compile-time).
-*/
-#if SQLITE_MAX_VARIABLE_NUMBER<=32767
-typedef i16 ynVar;
-#else
-typedef int ynVar;
-#endif
-
-/*
-** Each node of an expression in the parse tree is an instance
-** of this structure.
-**
-** Expr.op is the opcode. The integer parser token codes are reused
-** as opcodes here. For example, the parser defines TK_GE to be an integer
-** code representing the ">=" operator. This same integer code is reused
-** to represent the greater-than-or-equal-to operator in the expression
-** tree.
-**
-** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
-** or TK_STRING), then Expr.token contains the text of the SQL literal. If
-** the expression is a variable (TK_VARIABLE), then Expr.token contains the
-** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
-** then Expr.token contains the name of the function.
-**
-** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
-** binary operator. Either or both may be NULL.
-**
-** Expr.x.pList is a list of arguments if the expression is an SQL function,
-** a CASE expression or an IN expression of the form " IN (, ...)".
-** Expr.x.pSelect is used if the expression is a sub-select or an expression of
-** the form " IN (SELECT ...)". If the EP_xIsSelect bit is set in the
-** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
-** valid.
-**
-** An expression of the form ID or ID.ID refers to a column in a table.
-** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
-** the integer cursor number of a VDBE cursor pointing to that table and
-** Expr.iColumn is the column number for the specific column. If the
-** expression is used as a result in an aggregate SELECT, then the
-** value is also stored in the Expr.iAgg column in the aggregate so that
-** it can be accessed after all aggregates are computed.
-**
-** If the expression is an unbound variable marker (a question mark
-** character '?' in the original SQL) then the Expr.iTable holds the index
-** number for that variable.
-**
-** If the expression is a subquery then Expr.iColumn holds an integer
-** register number containing the result of the subquery. If the
-** subquery gives a constant result, then iTable is -1. If the subquery
-** gives a different answer at different times during statement processing
-** then iTable is the address of a subroutine that computes the subquery.
-**
-** If the Expr is of type OP_Column, and the table it is selecting from
-** is a disk table or the "old.*" pseudo-table, then pTab points to the
-** corresponding table definition.
-**
-** ALLOCATION NOTES:
-**
-** Expr objects can use a lot of memory space in database schema. To
-** help reduce memory requirements, sometimes an Expr object will be
-** truncated. And to reduce the number of memory allocations, sometimes
-** two or more Expr objects will be stored in a single memory allocation,
-** together with Expr.zToken strings.
-**
-** If the EP_Reduced and EP_TokenOnly flags are set when
-** an Expr object is truncated. When EP_Reduced is set, then all
-** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
-** are contained within the same memory allocation. Note, however, that
-** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
-** allocated, regardless of whether or not EP_Reduced is set.
-*/
-struct Expr {
- u8 op; /* Operation performed by this node */
- char affinity; /* The affinity of the column or 0 if not a column */
- u16 flags; /* Various flags. EP_* See below */
- union {
- char *zToken; /* Token value. Zero terminated and dequoted */
- int iValue; /* Integer value if EP_IntValue */
- } u;
-
- /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
- ** space is allocated for the fields below this point. An attempt to
- ** access them will result in a segfault or malfunction.
- *********************************************************************/
-
- Expr *pLeft; /* Left subnode */
- Expr *pRight; /* Right subnode */
- union {
- ExprList *pList; /* Function arguments or in " IN ( IN (