I've been following the news about the FBI vs Apple subpoena and realized that the more I heard the less it made sense. What the FBI was reported to be asking for would work, but it would take a very long time. Why would they do it the slow way when they can crack the phone so much faster? So, I read the subpoena. Very interesting read. Well worth your time to read it. It is a beautiful example of verbal jujitsu. It says very clearly exactly what the FBI wants Apple to do, er NO, it does not.
While the subpoena seems to state exactly what the FBI wants, every demand is followed by weasel words something like "in an alternative technical manner if mutually preferable." (bottom of page 4 of the subpoena). In other words, Apple can help the FBI crack the phone any way they want to so long as they do help the FBI. The details being reported by the media are all misdirection. Apple is not required to carry out any of the reported actions. Apple is required to give the FBI technical aid in decrypting it.
There are a few things that really bother me about the subpoena even if you do assume it is all baffle-gab. The FBI makes statements about the security structure of IOS version 9 that are disturbing to me. The FBI asserts that Apple has the ability to download and execute code on a locked iPhone. That may be something that, if true, Apple does not want advertised in public. That bit of information tells every Apple customer that while the FBI can not crack your iPhone Apple can. Apple can load code onto your iPhone, execute that code, and then clean up after itself so you can't even tell it happened. The subpoena says that Apple can download code directly to RAM bypassing the file system and then cause that code to be executed. The FBI claims that Apple can do that to a locked iPhone without asking permission from the owner of the phone and without leaving a trace that they have done it.
All of that means anyone with access to the IOS code signing key can get anything they want off of any iPhone. Not really a surprise, I suppose. I tend to believe that everything on a computer is public knowledge. On the other hand while I was very tempted to buy an Apple II I have never owned any Apple products. I learned my lesson from Microsoft. (Required gratuitous MS slam just so I seem unbiased.)
According to the FBI the iPhone encrypts data using AES. The FBI says that each iPhone has a unique 256 bit key that is "burned in" at the factory. The FBI says that the actual key is created from a combination of the password and the AES key. That means that if the FBI wants to try to crack the phone by trying all possible keys they want Apple to provide a tool that pulls out that 256 bit unique key, the file system, along with details of the algorithm used to create the actual key.
Why does the FBI want Apple to do that? After all the FBI has the phone. They can extract the entire contents of the file system by extracting the flash drive and hooking it up to another system that understands the electronics of the drive. They can then download the entire file system and play with the data to their little hearts content. Why not subpoena the algorithms? And, why not issue the subpoena through a secret security court? None of this needed to be done in public.
It is possible extracting the AES key from the hardware of an iPhone is hard to do. If it were easy to get they could get it from the raw hardware. They may need an atomic force microscope to do it, but they should be able to get it. The key is stored in a way that allows the encryption algorithm to read it. If any piece of code or any piece of hardware can read it then anyone who has control of the physical device can also read it. Unless it is designed to self destruct...
Given the file system, the base key, and the relevant algorithms the FBI can use N (N is an arbitrarily large number greater than zero) computers loaded with copies of the file system, the AES key, and the appropriate software to try passcodes millions of times faster than they could do it using a wire connected to a cracked iPhone. Using possibly thousands of computers to brute force a crack beats all hell out of what it appears they are asking for.
(The FBI realizes, properly, that messing with the hardware is risky. No matter how careful you are the data you want could be lost if the hardware is accidentally damaged or if it is built to delete data when tampered with. Getting a cracking tool from Apple is safer for the FBI. Imagine the uproar if the FBI lost the data on that phone while taking it apart. That would be a nasty political black eye for the FBI. The FBI must keep their collective asses covered.)
My bogometer pinned in the red when I realized that what the FBI appeared to be demanding from Apple was millions of times slower than the obvious approach. I concluded that much of the subpoena is misdirection intended to make Apple look bad and direct public discussion in the direction the FBI wants it to go.
It appears the FBI, and by extension the DOJ, wants to undermine belief in the security of Apple products, to force Apple to provide details of all the encryption algorithms used by IOS, and software that reads out each iPhone's unique AES key and also dumps the file system. That is exactly what they need to let them use a super computer to smash open the doors on every iPhone.
If everything goes right for the FBI they get a way to crack all iPhones, a legal precedent saying they can force companies like Apple to provide cracking tools for their products, and a chance to get public support for laws that criminalize personal security. They may even be able to make building a truly secure device illegal. To make matters worse the FBI just told every hacker in the world about a potentially devastating hole in iPhone security.
The art of misdirection is vital to magicians, con men, and used car sales men. I just learned that it is a well developed part of the FBI's arsenal. I'll be watching for it in the future.
Feb 25, 2016
Nov 5, 2015
Who Watches the Watchers? Policing the Police and everyone else.
Quis custodiet ipsos custodes? Who watches the watchers? A question that goes back at least to a Roman poet named Juvenal who died roughly 2,000 years ago. It would seem that abuses by those with power have been a problem for a very long time.... You might say that it is a basic human flaw.
The recent series of highly publicized murders carried out by police brought the question to mind quite forcefully. Then, a few days ago I heard an interview on KUT, the local public radio station. The interview was on the subject of sex crimes committed by Police. It seems to work like this:
If enough women complain about this behavior the cop might get fired. They do not usually get charged they just move on to the next town where they start all over again. Sounds just like what happens to pedophiliac Catholic Priests. Hard to believe that cop rapists and priest rapists get treated the same way. Their powerful organizations cover up for them and let them go on to rape again.
The interesting thing is that we know about murderous cops because people with smart phones record them and post the videos to the Internet. Once on the Internet the cops can not get them back. They can try to suppress them but they can't. The power of the individual with a video camera and an Internet connections is at least equal to, if not greater than, the power of the police to suppress. But, you don't commit rape when there are other people around. So, not so many videos of cops raping women (and men... I should not leave out that they also rape men) make it on the Internet.
The answer to the 2,000 year old question is that *we* watch the watchers. I've already seen video of a police officer attacking a woman who was recording a police beat down. He didn't figure that someone else was also recording what was going on. We need as many cameras out there as we can get. And, they need to be under our control. Police dash cam and body cam recordings are just to easy to lose.
This answer became obvious when the beat down of Rodney King was videotaped and the tape was sent to a local television station. The Internet really wasn't ready for the job back then, but it is now. We must record what is going on and we must make sure that everyone sees what really happened.
So, I would like to suggest a little citizen action that we can take to do even a better job of watching the watchers. I would like someone or some group of someones to create a little high tech bump. What we need is a bump you can stick on a car, or a door, or anywhere. What I want is a bump with the ability to keep a recording of at least the last 24 hours of video and sound. The device should have a wifi interface and maybe USB connections. It should be battery powered with a solar cell to recharge it. It would be nice if it recorded in the infrared and ultraviolet as well as the normal visual spectrum. It must be cheap. I know I can put together something like that starting with an Arduino or Raspberry Pi and off the shelf add on boards. But, it would be better, and no doubt cheaper, to build it as a single unit. One critical feature is that the only way to erase the stored recording is to destroy the device. (Cast the whole thing in a solid block of epoxy?) But anyone can download the current stored recording.
The idea is that I can have these on my car and one stuck on the side of my house and so can you. They can be put most anywhere and if you put them where they don't belong you should go to jail. These things would create a fair witness. An unbiased recording of any thing that happens. It is important that anyone can download the recording but no one can destroy or modify the recording without making it obvious that they did so. The wifi connection would also let these things be monitored in real time.
My little bump sounds like on hell of an invasion of privacy. And it will be if used incorrectly. On the other hand they would make it a lot safer for people when they are walking down the street or when they are pulled over by a cop. If there is always a witness with a video recorder there is very little chance of getting away with a crime. Every programmer knows that you are more careful about your coding if you know other people are going to look at it. Knowing that you might be being watched just might help everyone, including cops, behave a little bit better.
I have known many cops. Every cop I have known has been a great guy. I have been helped out by cops I did not know and will never see again. I hate what is happening right now. I hate it more because it seems it has always gone on and cops have used their power to cover it up. I hate that this could happen. But it has, and it does, and something must be done to fix the problem. If you want to see the cockroaches you have to turn on a light. Video cameras and the Internet are the most powerful light ever made.
While most cops are great people, there is something about image of cops that attracts bullies the same way the job of Catholic Priest seems to attract pedophiles. I wouldn't be surprised if the job of surgeon attracts sadists. Some jobs just attract certain kinds of people. Have you ever met an extroverted programmer? You have? Really? Are you sure? Ever met a corporate executive that you suspected was a sociopath, a psychopath? I hope you get my point.
OK, all that feel good stuff aside, we need to use technology to create a fair witness system that is not controlled by police or the government. It needs to be a citizen action for the protection of our selves. The goal here is not to undermine the police. The goal is to make it possible to trust them again. Do you want to see the day when it is considered self defense to shoot a cop just because the cop pulled you over where you would be alone and it was after dark? That could happen if we do not do something to reestablish trust between the police and citizens. OK, in large parts of the country we need to establish trust between the police and the citizens for the first time.
I hate to admit it, but right now the idea of being pulled over by a cop scares me. I never thought that could happen. I want everyone to be able to trust a cop all the time and I want cops to be able to trust citizens as much as is possible.
The recent series of highly publicized murders carried out by police brought the question to mind quite forcefully. Then, a few days ago I heard an interview on KUT, the local public radio station. The interview was on the subject of sex crimes committed by Police. It seems to work like this:
- See a woman alone in a car.
- Pull her over for whatever, they can always come up with some reason to pull you over.
- Tell the woman to spread her legs, open her mouth, or go to jail.
- If she is not quick enough hold a gun to her head.
If enough women complain about this behavior the cop might get fired. They do not usually get charged they just move on to the next town where they start all over again. Sounds just like what happens to pedophiliac Catholic Priests. Hard to believe that cop rapists and priest rapists get treated the same way. Their powerful organizations cover up for them and let them go on to rape again.
The interesting thing is that we know about murderous cops because people with smart phones record them and post the videos to the Internet. Once on the Internet the cops can not get them back. They can try to suppress them but they can't. The power of the individual with a video camera and an Internet connections is at least equal to, if not greater than, the power of the police to suppress. But, you don't commit rape when there are other people around. So, not so many videos of cops raping women (and men... I should not leave out that they also rape men) make it on the Internet.
The answer to the 2,000 year old question is that *we* watch the watchers. I've already seen video of a police officer attacking a woman who was recording a police beat down. He didn't figure that someone else was also recording what was going on. We need as many cameras out there as we can get. And, they need to be under our control. Police dash cam and body cam recordings are just to easy to lose.
This answer became obvious when the beat down of Rodney King was videotaped and the tape was sent to a local television station. The Internet really wasn't ready for the job back then, but it is now. We must record what is going on and we must make sure that everyone sees what really happened.
So, I would like to suggest a little citizen action that we can take to do even a better job of watching the watchers. I would like someone or some group of someones to create a little high tech bump. What we need is a bump you can stick on a car, or a door, or anywhere. What I want is a bump with the ability to keep a recording of at least the last 24 hours of video and sound. The device should have a wifi interface and maybe USB connections. It should be battery powered with a solar cell to recharge it. It would be nice if it recorded in the infrared and ultraviolet as well as the normal visual spectrum. It must be cheap. I know I can put together something like that starting with an Arduino or Raspberry Pi and off the shelf add on boards. But, it would be better, and no doubt cheaper, to build it as a single unit. One critical feature is that the only way to erase the stored recording is to destroy the device. (Cast the whole thing in a solid block of epoxy?) But anyone can download the current stored recording.
The idea is that I can have these on my car and one stuck on the side of my house and so can you. They can be put most anywhere and if you put them where they don't belong you should go to jail. These things would create a fair witness. An unbiased recording of any thing that happens. It is important that anyone can download the recording but no one can destroy or modify the recording without making it obvious that they did so. The wifi connection would also let these things be monitored in real time.
My little bump sounds like on hell of an invasion of privacy. And it will be if used incorrectly. On the other hand they would make it a lot safer for people when they are walking down the street or when they are pulled over by a cop. If there is always a witness with a video recorder there is very little chance of getting away with a crime. Every programmer knows that you are more careful about your coding if you know other people are going to look at it. Knowing that you might be being watched just might help everyone, including cops, behave a little bit better.
I have known many cops. Every cop I have known has been a great guy. I have been helped out by cops I did not know and will never see again. I hate what is happening right now. I hate it more because it seems it has always gone on and cops have used their power to cover it up. I hate that this could happen. But it has, and it does, and something must be done to fix the problem. If you want to see the cockroaches you have to turn on a light. Video cameras and the Internet are the most powerful light ever made.
While most cops are great people, there is something about image of cops that attracts bullies the same way the job of Catholic Priest seems to attract pedophiles. I wouldn't be surprised if the job of surgeon attracts sadists. Some jobs just attract certain kinds of people. Have you ever met an extroverted programmer? You have? Really? Are you sure? Ever met a corporate executive that you suspected was a sociopath, a psychopath? I hope you get my point.
OK, all that feel good stuff aside, we need to use technology to create a fair witness system that is not controlled by police or the government. It needs to be a citizen action for the protection of our selves. The goal here is not to undermine the police. The goal is to make it possible to trust them again. Do you want to see the day when it is considered self defense to shoot a cop just because the cop pulled you over where you would be alone and it was after dark? That could happen if we do not do something to reestablish trust between the police and citizens. OK, in large parts of the country we need to establish trust between the police and the citizens for the first time.
I hate to admit it, but right now the idea of being pulled over by a cop scares me. I never thought that could happen. I want everyone to be able to trust a cop all the time and I want cops to be able to trust citizens as much as is possible.
Oct 30, 2015
$866,304.61 per GigaByte
Recently I was looking for drives for a new DVR I was building. (The old one based on a 10 year old PC I inherited from one of my kids died of a fatal thunderstorm.) I looked around on the net and wound up just buying a 4TB disk at Fry's (the place where old men go to be ignored...). It was made by Seagate and cost $160. No big deal, right?
Buying that drive made me think of the first hard drive I ever owned. It happened to be made by the same company under a different name and I bought it in the early '80s. It was an ST-506. ST stood for Shugart Technology, Inc. The company was renamed Seagate Technology to avoid a law suit over the name. The ST-506 was the first hard drive intended for use with personal computers. I should mention that at the time a personal computer was most likely a Z80 with 64K of RAM. IBM had not gotten into the PC business in 1980 and a personal computer was any old computer, not what we would not call a PC.
When first introduced in 1980 the ST-506 stored 5 MegaBytes. That's right, MEGA, with an M, not GigaBytes or TeraBytes, MegaBytes. It stored 5,000,000 bytes. My new drive stores 4,000,000,000,000 bytes. Did I pound the difference in capacity into your head? The new drive stores close to a million times as much as my first hard drive.
Think of it this way. I paid $0.04 for a gigabyte of disk space a couple of weeks ago. 35 years ago I would have had to buy 200 ST-506 drives to make up a gigabyte of storage. I do not remember what I paid for that drive, it was part of a bundle... And, it was a long time ago. But, when it was first released the ST-506 cost $1,500 dollars. So, what would a GigaByte cost if using ST-506 drives? Let's see... $1,500 * 200 = $300,000 dollars. Of course, those are 1980 dollars. Taking into account 35 years of inflation and the cost in 2015 dollars is $866,304.61. That is a lot of money.
Four cents versus $866K is a... large, change in price.
It hurts my poor little mind to realize that I thought a 5 MegaByte disk was freaking HUGE back then. Today I am wishing I could make a case for building a redundant RAID out of 4 TeraByte drives. I like RAID's, RAIDs are cool. But I just don't need that much storage right now.
We have just passed "Back to the Future" day and I was watching a documentary about that amazing movie. The folks making the documentary asked why the original film makers hadn't used CGI. The answer was that back in 1980 there was no CGI because there were no computers capable of doing CGI back then. Think about it. An ST-506 could not store even one frame of 1920x1080 HD video. Let me say that again for emphasis: an ST-506 could not store even one frame of HD video. No personal computer from that era could be used for video production work. Things we do on phones were not possible on high end workstations of that era.
The 35 years from 1980 to 2015 do not seem like a long time in a human life. It was enough time to raise a couple of kids. Pay off the mortgage on a house. Raise a dog from puppyhood to old age a couple of times over. It was enough time for the price of desktop hard drives to drop by a factor of 10 and for their capacity to increase by a factor of 1,000,000. A short time for a human. A long long time in the history of technology.
I can't wait to see what's next.
Buying that drive made me think of the first hard drive I ever owned. It happened to be made by the same company under a different name and I bought it in the early '80s. It was an ST-506. ST stood for Shugart Technology, Inc. The company was renamed Seagate Technology to avoid a law suit over the name. The ST-506 was the first hard drive intended for use with personal computers. I should mention that at the time a personal computer was most likely a Z80 with 64K of RAM. IBM had not gotten into the PC business in 1980 and a personal computer was any old computer, not what we would not call a PC.
When first introduced in 1980 the ST-506 stored 5 MegaBytes. That's right, MEGA, with an M, not GigaBytes or TeraBytes, MegaBytes. It stored 5,000,000 bytes. My new drive stores 4,000,000,000,000 bytes. Did I pound the difference in capacity into your head? The new drive stores close to a million times as much as my first hard drive.
Think of it this way. I paid $0.04 for a gigabyte of disk space a couple of weeks ago. 35 years ago I would have had to buy 200 ST-506 drives to make up a gigabyte of storage. I do not remember what I paid for that drive, it was part of a bundle... And, it was a long time ago. But, when it was first released the ST-506 cost $1,500 dollars. So, what would a GigaByte cost if using ST-506 drives? Let's see... $1,500 * 200 = $300,000 dollars. Of course, those are 1980 dollars. Taking into account 35 years of inflation and the cost in 2015 dollars is $866,304.61. That is a lot of money.
Four cents versus $866K is a... large, change in price.
It hurts my poor little mind to realize that I thought a 5 MegaByte disk was freaking HUGE back then. Today I am wishing I could make a case for building a redundant RAID out of 4 TeraByte drives. I like RAID's, RAIDs are cool. But I just don't need that much storage right now.
We have just passed "Back to the Future" day and I was watching a documentary about that amazing movie. The folks making the documentary asked why the original film makers hadn't used CGI. The answer was that back in 1980 there was no CGI because there were no computers capable of doing CGI back then. Think about it. An ST-506 could not store even one frame of 1920x1080 HD video. Let me say that again for emphasis: an ST-506 could not store even one frame of HD video. No personal computer from that era could be used for video production work. Things we do on phones were not possible on high end workstations of that era.
The 35 years from 1980 to 2015 do not seem like a long time in a human life. It was enough time to raise a couple of kids. Pay off the mortgage on a house. Raise a dog from puppyhood to old age a couple of times over. It was enough time for the price of desktop hard drives to drop by a factor of 10 and for their capacity to increase by a factor of 1,000,000. A short time for a human. A long long time in the history of technology.
I can't wait to see what's next.
Aug 14, 2015
My Favorite Bugs: Java Memory Leak
This is a story of how I managed to create the largest memory leak I have ever seen, in fact, the largest memory leak I have ever heard of. I did it using Java, a garbage collected programming language. You are not supposed to be able to have memory leaks in garbage collected languages.
This story is not in anyway a slam at Java. I really like Java. It is a story about unintended consequences and how what you do not know can bite you right on the ass.
I know a lot about garbage collectors and garbage collected languages. I have implemented Lisp several times. I have implemented it as an interpreter and as a compiler. That means I have written several garbage collectors. I have actually written at least a half dozen garbage collectors of various sorts. I have read at least 100 papers and several books on garbage collection and at least that many on storage management in general. Not counting garbage collectors I have written... Ok, I've lost count... general heap management systems using many different methods including both relocating handle based systems and pointer based systems.
I know a little bit about memory management. I do not claim to be an expert. In the bad old days you just often had to write your own memory managers to make it possible to write the application you that you were actually working on. Anyway, I was so very glad to find myself in a situation where I was able to use a garbage collected language. So very very glad not to have to write yet another memory manager, not to have to worry about memory management at all. And, that was my first mistake.
It takes a few mistakes to create a memory leak in a garbage collected language.
I was writing a web spider. I was working on a research project that required a web spider and at the same time was supposed to be evaluating Java. It was actually new when I was doing this work. I.E. it was a while ago. So, I decided to write a web spider in Java to kill multiple birds with one stone.
So, I did just that. I wrote a multithreaded web spider in Java. In the end it was very handy for collecting the statistics I was looking for and it showed me some statistics I was not expecting. What did I find? Well I found that the distribution of vocabulary used on the web varies significantly depending on where you start your web spider. I found that (at the time) there was a porn site within three links of any page on whitehouse.gov. Of course (at the time) whitehouse.com was a porn site. People just can't seem to avoid typing ".com" when they mean ".gov".
I also found out that using whitehouse.gov as a starting point for testing a web spider is a bad idea. I was working for a large phone company at the time and it seems that upper management was not pleased when they got a telephone call from the real live White House, the Official Residence of POTUS asking the telco to cut it out. They were OK with me hitting them at night, but not during working hours. That taught me to salt the search queue with many starting URLs so that the initial start up activity would be spread all over the net and not dumped on one poor little old web server. It also taught me that paying taxes is not a justification for beating up the White House web server.
I also found out that every URL I hit was being recorded by the Telephone Company Police (yes, really). I found out about this little detail when the TCP showed up in my bosses office with a list of the tens of thousands (yes, really) porn sites I had hit from my PC. After she started breathing again she explained what was going on and the TCP left without dragging me, and possibly her, out to the parking lot and firing me on the spot. (I am talking about the company that fired Dilbert...) The fact is that if you start a web spider you will find porn sites.
It turned out the TCP were really more interested in how I was managing to hit thousands of porn sites per minute without downloading any pictures. They found the pattern to be ... odd.
OK, so I wrote and used a web spider and had some interesting experiences and actually accomplished several tasks that I was getting paid to do. But, there is still the story about the giant memory leak to tell.
This all started with the problem of parsing web pages. To write a web spider you have to examine a web page and find all the HTTP type URLs that are in it. You store the URLs in a queue if you want to do a breadth first search or a stack if you want to do a depth first search. You can also sort the URLs by first assigning them a weight based on some measure you apply to them. You also need a list of URLs you have already visited so that you do not visit them again. The web, and webs in general, have lots and lots of cycles.
(Oh yeah, if you want a really useful web spider you should never do what those pesky robot.txt files tell you to do. Really they do get in the way. It can be fun to down load them and analyze them though. They give you clues for finding really interesting stuff.)
I thought that the way to find the URLs was to parse the HTML and look in all the places you are supposed to have URLs. I wrote a parser that, like most parsers, treated the source document as a stream. That should work, right? It turns out that very few web pages that I found were syntactically correct HTML. Tags were misspelled or just plain missing. If the tags were there their contents were not what they were supposed to be. It seems the syntax of HTML is not defined by the standard documents but by what web browsers will accept. Web browsers are very flexible about what they accept as valid HTML.
I also found out that most of the URLs, especially the ones people do not want you to find, are hidden inside chunks of Javascript. You can't find those by parsing HTML. If I were writing it today I would definitely scan all the CSS for URLs. I've found some interesting stuff in CSS with out a web spider.
My first attempt at parsing web pages was a total bust. The technique that worked was to down load the entire web page as a single chunk of text and apply pattern matching to it. So I did just that. I down loaded each page and stored it in a Java string and searched for patterns. For the first version of the working spider I did everything in memory. Since everything was being done in memory I was not surprised when the spider ran out of memory. That turned out to be a mistake. I should have been surprised.
So, what was taking up memory? Well I had a queue for storing URLs that were waiting to be scanned. The values in that queue were actually pairs of URLs. I stored the source URL of the page along with the new URL. I did that so that if the new URL didn't work the spider would log both URLs so I could go back and learn something new about how to hide URLs. There was also a hash that I used to keep track of URLs that had been scanned so that the spider would not get caught in loops and rescan pages multiple times. Then there were the structures I used to store the statistics I was interested in.
OK, so I expected to run out of memory and It did so I assumed that I needed to reduce memory use. I did not suspect a memory leak. What to do? Well, I built a file based queue. That was slower than RAM but it moved all that information out to a disk. Sure enough, I still ran out of RAM. Moving the queue to a file had no effect. Time to move the hash, right?
I had some old C code for B-Tree files so I converted that to Java. (Later I converted the same code to C++. Good code never dies...) That code let me substitute a B-Tree file for the hash that I had been using to keep track of previously visited URLs. Putting all that stuff on disk also let me stop a scan and restart it at a later time.
The spider was still running out of memory. I learned how to monitor memory usage in a Java program. I learned how to dig through RAM in a Java program. I dumped all sorts of information as the spider ran around the web. I noticed something. The program still ran out of RAM, but the rate at which it used RAM declined over time. Really weird. I now suspected a memory leak.
I finally figured it out. I also just found out that what caught me was fixed in 2013 in version Java 1.7.0_06. BTW, that is only about 15 years after I reported the problem to Sun. The problem was with the original implementation of strings in Java and my lack of understanding of that design. If I had understood the design I would not have had a problem so I can hardly put all the blame on Java. What you don't know can kill you.
I believe that the original version of Java strings was designed to both save memory and avoid memory fragmentation. Strings are hell for garbage collectors and all other storage managers because they tend to have random sizes. Most data types have a single fixed size. If you create one and delete it then create another one you are usually going to find a free block exactly the size you need. But, not so with strings. Strings tend to be small and random sized. Just finding a piece of memory the right size can be time consuming. But, worse, you wind up with lots of small random sized blobs of memory scattered all through your heap. These little nasty blobs can take up a lot of space but not be large enough to be useful. So, the original designers of Java tried to avoid all those problems. Can't blame them. And, they did a pretty good job too. I have a lot of respect for Gosling.
When I download those pages and stored them in a single string I was creating a large string. I "assumed" that when I was done with the string it would be garbage collected. But, the strings were not being garbage collected. In the original version of Java a string has a pointer to the text of the string, plus an offset to the starting position of the string within the text and a length. This representation lets you take substrings of a string with out copying any part of the text of the original string. What happens is that the substring has a pointer to the original text of the string, but the offset indicates the starting byte of the substring in the original text and the length is the length of the substring. Allowing substrings to share the text of the original string helps avoid all the problems with memory management I described above. The trouble is that I was keeping substrings around in memory as part of my statistical information. Keeping a substring around pinned the entire original string into memory.
I down loaded a page into a single string. I then scanned for words and looked them up in my "dictionary". If the word was already in the dictionary I incremented its count by one. If not, I added the word to the dictionary with a count of one. That means that every time I added a word to my dictionary I pinned the entire source page in RAM. Even though I had no reference to the original text, the substring did and so the page could not be garbage collected.
The first pages I down loaded had lots of new words in them because the dictionary started out empty. As time went on fewer and fewer new words were found. Many pages had no new words. If a page had no new words is would be garbage collected. But, every time I found a new word, and I eventually found tens of thousands of words, an entire page was being pinned in memory.
Once I understood the problem, the solution was easy. Just create an actual copy of any substring I wanted to keep around. Doing that removed all those pesky invisible references and suddenly I could let the spider run for weeks without running out of RAM.
So what is the moral of our story?
This story is not in anyway a slam at Java. I really like Java. It is a story about unintended consequences and how what you do not know can bite you right on the ass.
I know a lot about garbage collectors and garbage collected languages. I have implemented Lisp several times. I have implemented it as an interpreter and as a compiler. That means I have written several garbage collectors. I have actually written at least a half dozen garbage collectors of various sorts. I have read at least 100 papers and several books on garbage collection and at least that many on storage management in general. Not counting garbage collectors I have written... Ok, I've lost count... general heap management systems using many different methods including both relocating handle based systems and pointer based systems.
I know a little bit about memory management. I do not claim to be an expert. In the bad old days you just often had to write your own memory managers to make it possible to write the application you that you were actually working on. Anyway, I was so very glad to find myself in a situation where I was able to use a garbage collected language. So very very glad not to have to write yet another memory manager, not to have to worry about memory management at all. And, that was my first mistake.
It takes a few mistakes to create a memory leak in a garbage collected language.
I was writing a web spider. I was working on a research project that required a web spider and at the same time was supposed to be evaluating Java. It was actually new when I was doing this work. I.E. it was a while ago. So, I decided to write a web spider in Java to kill multiple birds with one stone.
So, I did just that. I wrote a multithreaded web spider in Java. In the end it was very handy for collecting the statistics I was looking for and it showed me some statistics I was not expecting. What did I find? Well I found that the distribution of vocabulary used on the web varies significantly depending on where you start your web spider. I found that (at the time) there was a porn site within three links of any page on whitehouse.gov. Of course (at the time) whitehouse.com was a porn site. People just can't seem to avoid typing ".com" when they mean ".gov".
I also found out that using whitehouse.gov as a starting point for testing a web spider is a bad idea. I was working for a large phone company at the time and it seems that upper management was not pleased when they got a telephone call from the real live White House, the Official Residence of POTUS asking the telco to cut it out. They were OK with me hitting them at night, but not during working hours. That taught me to salt the search queue with many starting URLs so that the initial start up activity would be spread all over the net and not dumped on one poor little old web server. It also taught me that paying taxes is not a justification for beating up the White House web server.
I also found out that every URL I hit was being recorded by the Telephone Company Police (yes, really). I found out about this little detail when the TCP showed up in my bosses office with a list of the tens of thousands (yes, really) porn sites I had hit from my PC. After she started breathing again she explained what was going on and the TCP left without dragging me, and possibly her, out to the parking lot and firing me on the spot. (I am talking about the company that fired Dilbert...) The fact is that if you start a web spider you will find porn sites.
It turned out the TCP were really more interested in how I was managing to hit thousands of porn sites per minute without downloading any pictures. They found the pattern to be ... odd.
OK, so I wrote and used a web spider and had some interesting experiences and actually accomplished several tasks that I was getting paid to do. But, there is still the story about the giant memory leak to tell.
This all started with the problem of parsing web pages. To write a web spider you have to examine a web page and find all the HTTP type URLs that are in it. You store the URLs in a queue if you want to do a breadth first search or a stack if you want to do a depth first search. You can also sort the URLs by first assigning them a weight based on some measure you apply to them. You also need a list of URLs you have already visited so that you do not visit them again. The web, and webs in general, have lots and lots of cycles.
(Oh yeah, if you want a really useful web spider you should never do what those pesky robot.txt files tell you to do. Really they do get in the way. It can be fun to down load them and analyze them though. They give you clues for finding really interesting stuff.)
I thought that the way to find the URLs was to parse the HTML and look in all the places you are supposed to have URLs. I wrote a parser that, like most parsers, treated the source document as a stream. That should work, right? It turns out that very few web pages that I found were syntactically correct HTML. Tags were misspelled or just plain missing. If the tags were there their contents were not what they were supposed to be. It seems the syntax of HTML is not defined by the standard documents but by what web browsers will accept. Web browsers are very flexible about what they accept as valid HTML.
I also found out that most of the URLs, especially the ones people do not want you to find, are hidden inside chunks of Javascript. You can't find those by parsing HTML. If I were writing it today I would definitely scan all the CSS for URLs. I've found some interesting stuff in CSS with out a web spider.
My first attempt at parsing web pages was a total bust. The technique that worked was to down load the entire web page as a single chunk of text and apply pattern matching to it. So I did just that. I down loaded each page and stored it in a Java string and searched for patterns. For the first version of the working spider I did everything in memory. Since everything was being done in memory I was not surprised when the spider ran out of memory. That turned out to be a mistake. I should have been surprised.
So, what was taking up memory? Well I had a queue for storing URLs that were waiting to be scanned. The values in that queue were actually pairs of URLs. I stored the source URL of the page along with the new URL. I did that so that if the new URL didn't work the spider would log both URLs so I could go back and learn something new about how to hide URLs. There was also a hash that I used to keep track of URLs that had been scanned so that the spider would not get caught in loops and rescan pages multiple times. Then there were the structures I used to store the statistics I was interested in.
OK, so I expected to run out of memory and It did so I assumed that I needed to reduce memory use. I did not suspect a memory leak. What to do? Well, I built a file based queue. That was slower than RAM but it moved all that information out to a disk. Sure enough, I still ran out of RAM. Moving the queue to a file had no effect. Time to move the hash, right?
I had some old C code for B-Tree files so I converted that to Java. (Later I converted the same code to C++. Good code never dies...) That code let me substitute a B-Tree file for the hash that I had been using to keep track of previously visited URLs. Putting all that stuff on disk also let me stop a scan and restart it at a later time.
The spider was still running out of memory. I learned how to monitor memory usage in a Java program. I learned how to dig through RAM in a Java program. I dumped all sorts of information as the spider ran around the web. I noticed something. The program still ran out of RAM, but the rate at which it used RAM declined over time. Really weird. I now suspected a memory leak.
I finally figured it out. I also just found out that what caught me was fixed in 2013 in version Java 1.7.0_06. BTW, that is only about 15 years after I reported the problem to Sun. The problem was with the original implementation of strings in Java and my lack of understanding of that design. If I had understood the design I would not have had a problem so I can hardly put all the blame on Java. What you don't know can kill you.
I believe that the original version of Java strings was designed to both save memory and avoid memory fragmentation. Strings are hell for garbage collectors and all other storage managers because they tend to have random sizes. Most data types have a single fixed size. If you create one and delete it then create another one you are usually going to find a free block exactly the size you need. But, not so with strings. Strings tend to be small and random sized. Just finding a piece of memory the right size can be time consuming. But, worse, you wind up with lots of small random sized blobs of memory scattered all through your heap. These little nasty blobs can take up a lot of space but not be large enough to be useful. So, the original designers of Java tried to avoid all those problems. Can't blame them. And, they did a pretty good job too. I have a lot of respect for Gosling.
When I download those pages and stored them in a single string I was creating a large string. I "assumed" that when I was done with the string it would be garbage collected. But, the strings were not being garbage collected. In the original version of Java a string has a pointer to the text of the string, plus an offset to the starting position of the string within the text and a length. This representation lets you take substrings of a string with out copying any part of the text of the original string. What happens is that the substring has a pointer to the original text of the string, but the offset indicates the starting byte of the substring in the original text and the length is the length of the substring. Allowing substrings to share the text of the original string helps avoid all the problems with memory management I described above. The trouble is that I was keeping substrings around in memory as part of my statistical information. Keeping a substring around pinned the entire original string into memory.
I down loaded a page into a single string. I then scanned for words and looked them up in my "dictionary". If the word was already in the dictionary I incremented its count by one. If not, I added the word to the dictionary with a count of one. That means that every time I added a word to my dictionary I pinned the entire source page in RAM. Even though I had no reference to the original text, the substring did and so the page could not be garbage collected.
The first pages I down loaded had lots of new words in them because the dictionary started out empty. As time went on fewer and fewer new words were found. Many pages had no new words. If a page had no new words is would be garbage collected. But, every time I found a new word, and I eventually found tens of thousands of words, an entire page was being pinned in memory.
Once I understood the problem, the solution was easy. Just create an actual copy of any substring I wanted to keep around. Doing that removed all those pesky invisible references and suddenly I could let the spider run for weeks without running out of RAM.
So what is the moral of our story?
- Do not make assumptions about anything.
- Do not use any language feature if you do not understand how it is implemented.
- You must understand the implications of the implementation.
There are more things in heaven and earth, Horatio,Another way to say that would be:
Than are dreamt of in your philosophy.
- Do not make assumptions about how programmers will use your language.
- Features should work the way programmers believe they work.
- The distance between clever and stupid is very short.
Aug 6, 2015
Rainbow Time
This isn't one of my usual grumpy stories. This morning I had rainbow time. It was wonderful.
When my children were young Mother's Day became a really problem for me. My two kids always made some kind of craft, usually at school, for Mom. But, they also wanted to get her something special. They wanted to get her something beautiful, and artistic, something Mom would love and remember forever. On the other hand, taking two active inquisitive children into stores that sell beautiful artistic things usually means taking two active inquisitive children into stores that have many fragile things that little hands should not touch. One parent, two kids, the math just doesn't work. You can't watch them both at the same time.
But I found a solution. My wife loves Swarovski style cut lead glass crystals. And, every child I have ever met loves rainbows. Those prismatic crystals are wonderful rainbow makers.
There is a swarovski store near where we live and one of its nicest features is that everything in the store is either out of the reach of small children or in locked cases. These stores are actually child proof. I could take my kids in there and know that even if I got distracted my children could do no damage. They were good kids. Well behaved. But, they were children.
The trouble with giving someone a beautiful prismatic lead glass crystal is that the crystals usually wind up in a box in a drawer where they may be looked at only once every few years, if they are looked at at all. Or, they wind up in a curio cabinet where they become part of the wall paper and are never looked at at all.
I found a solution to that too. When I was a little kid, almost eight years old, I saw the move Pollyanna. That movie had a surprisingly large effect on my life.
Back then, in the late '50s and early '60s, my parents would dress the three of us, me and my two sisters, in our PJs and load us in the back of the car with our pillows and some blankets. Mom always made sure to tuck in a blanket over the whole back seat so that we wouldn't sweat and stick to it. Then we would head out to the drive in movie theater. The idea was that my parents would watch the double feature and that we would fall asleep sometime during the first film of the night. It usually worked very well, but sometimes I would manage to stay awake and watch the whole first film. But I always fell asleep in the back seat of the car curled up with my sisters like a pile of sleeping kittens. I have a few memories of awaking in my father's arms as he carried me from the car to my bed and tucked me in.
In the movie, Pollyanna notices that the prismatic decorations hanging on a huge chandelier cast "rainbows" on the wall when sunlight hits them just right. She and her guardian then take all the rainbow makers and hangs them in a window. As the sun sets the light streams through the window and casts what seen like hundreds of rainbows on the walls of the room. I saw the same effect in the old Hansen Planetarium in Salt Lake City. It had beveled glass windows and just as the sun set over the Great Salt Lake the second floor gallery would light up with dozens of rainbows.
Those Mother's Day crystals are wonderful rainbow makers. We put cup hooks at the tops of our living room and kitchen windows and hung the crystals where, once in a while, the light through the window casts dozens of dancing rainbows across the whole first floor of my home.
Rainbow time is the time when sunlight manages to come through the windows at just the right angle to get past the trees and clouds and be diffracted by the crystals into dancing rainbows. It doesn't happen every day. It only happens when the sun rises in the right position and there are no clouds or mist to block the direct rays of sunshine. But when it happens it is a amazing and wonderful.
When my children were small we would play a game where we tried to catch a rainbow. We would put our hands in just the right place to catch a rainbow in our palms. Then we would follow the rainbow as far as we could toward the crystals and toward the walls.
Over the decades many of the crystals have wound up in a display case. But there are two left in the arch of the living room window. This morning I had rainbow time and I caught a rainbow in the palm of my hand and on my big toe. My children are grown now and I'm a grandfather. But, I still get to play catch the rainbow and remember when I was the father of two young children. I tried my best to fill their world with wonder.
I believe that my fascination with prisms, inspire by that movie, is part of what drove me to become so curious and so fascinated by science. I saw light going in one side. I saw the rainbow coming out the other side. I was desperate to understand how and why that could happen. I now know the standard explanation, and I also know that at the bottommost level we do not know why the Universe works that way. There are so many unanswered questions. I hope we never run out of questions and people who are willing to spend their lives answering one more level of "Why?"
When my children were young Mother's Day became a really problem for me. My two kids always made some kind of craft, usually at school, for Mom. But, they also wanted to get her something special. They wanted to get her something beautiful, and artistic, something Mom would love and remember forever. On the other hand, taking two active inquisitive children into stores that sell beautiful artistic things usually means taking two active inquisitive children into stores that have many fragile things that little hands should not touch. One parent, two kids, the math just doesn't work. You can't watch them both at the same time.
But I found a solution. My wife loves Swarovski style cut lead glass crystals. And, every child I have ever met loves rainbows. Those prismatic crystals are wonderful rainbow makers.
There is a swarovski store near where we live and one of its nicest features is that everything in the store is either out of the reach of small children or in locked cases. These stores are actually child proof. I could take my kids in there and know that even if I got distracted my children could do no damage. They were good kids. Well behaved. But, they were children.
The trouble with giving someone a beautiful prismatic lead glass crystal is that the crystals usually wind up in a box in a drawer where they may be looked at only once every few years, if they are looked at at all. Or, they wind up in a curio cabinet where they become part of the wall paper and are never looked at at all.
I found a solution to that too. When I was a little kid, almost eight years old, I saw the move Pollyanna. That movie had a surprisingly large effect on my life.
Back then, in the late '50s and early '60s, my parents would dress the three of us, me and my two sisters, in our PJs and load us in the back of the car with our pillows and some blankets. Mom always made sure to tuck in a blanket over the whole back seat so that we wouldn't sweat and stick to it. Then we would head out to the drive in movie theater. The idea was that my parents would watch the double feature and that we would fall asleep sometime during the first film of the night. It usually worked very well, but sometimes I would manage to stay awake and watch the whole first film. But I always fell asleep in the back seat of the car curled up with my sisters like a pile of sleeping kittens. I have a few memories of awaking in my father's arms as he carried me from the car to my bed and tucked me in.
In the movie, Pollyanna notices that the prismatic decorations hanging on a huge chandelier cast "rainbows" on the wall when sunlight hits them just right. She and her guardian then take all the rainbow makers and hangs them in a window. As the sun sets the light streams through the window and casts what seen like hundreds of rainbows on the walls of the room. I saw the same effect in the old Hansen Planetarium in Salt Lake City. It had beveled glass windows and just as the sun set over the Great Salt Lake the second floor gallery would light up with dozens of rainbows.
Those Mother's Day crystals are wonderful rainbow makers. We put cup hooks at the tops of our living room and kitchen windows and hung the crystals where, once in a while, the light through the window casts dozens of dancing rainbows across the whole first floor of my home.
Rainbow time is the time when sunlight manages to come through the windows at just the right angle to get past the trees and clouds and be diffracted by the crystals into dancing rainbows. It doesn't happen every day. It only happens when the sun rises in the right position and there are no clouds or mist to block the direct rays of sunshine. But when it happens it is a amazing and wonderful.
When my children were small we would play a game where we tried to catch a rainbow. We would put our hands in just the right place to catch a rainbow in our palms. Then we would follow the rainbow as far as we could toward the crystals and toward the walls.
Over the decades many of the crystals have wound up in a display case. But there are two left in the arch of the living room window. This morning I had rainbow time and I caught a rainbow in the palm of my hand and on my big toe. My children are grown now and I'm a grandfather. But, I still get to play catch the rainbow and remember when I was the father of two young children. I tried my best to fill their world with wonder.
I believe that my fascination with prisms, inspire by that movie, is part of what drove me to become so curious and so fascinated by science. I saw light going in one side. I saw the rainbow coming out the other side. I was desperate to understand how and why that could happen. I now know the standard explanation, and I also know that at the bottommost level we do not know why the Universe works that way. There are so many unanswered questions. I hope we never run out of questions and people who are willing to spend their lives answering one more level of "Why?"
Subscribe to:
Posts (Atom)